1 //===-- IOHandlerCursesGUI.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "lldb/Core/IOHandlerCursesGUI.h"
10 #include "lldb/Host/Config.h"
11
12 #if LLDB_ENABLE_CURSES
13 #include <curses.h>
14 #include <panel.h>
15 #endif
16
17 #if defined(__APPLE__)
18 #include <deque>
19 #endif
20 #include <string>
21
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Host/File.h"
25 #include "lldb/Utility/Predicate.h"
26 #include "lldb/Utility/Status.h"
27 #include "lldb/Utility/StreamString.h"
28 #include "lldb/Utility/StringList.h"
29 #include "lldb/lldb-forward.h"
30
31 #include "lldb/Interpreter/CommandCompletions.h"
32 #include "lldb/Interpreter/CommandInterpreter.h"
33
34 #if LLDB_ENABLE_CURSES
35 #include "lldb/Breakpoint/BreakpointLocation.h"
36 #include "lldb/Core/Module.h"
37 #include "lldb/Core/ValueObject.h"
38 #include "lldb/Core/ValueObjectRegister.h"
39 #include "lldb/Symbol/Block.h"
40 #include "lldb/Symbol/Function.h"
41 #include "lldb/Symbol/Symbol.h"
42 #include "lldb/Symbol/VariableList.h"
43 #include "lldb/Target/Process.h"
44 #include "lldb/Target/RegisterContext.h"
45 #include "lldb/Target/StackFrame.h"
46 #include "lldb/Target/StopInfo.h"
47 #include "lldb/Target/Target.h"
48 #include "lldb/Target/Thread.h"
49 #include "lldb/Utility/State.h"
50 #endif
51
52 #include "llvm/ADT/StringRef.h"
53
54 #ifdef _WIN32
55 #include "lldb/Host/windows/windows.h"
56 #endif
57
58 #include <memory>
59 #include <mutex>
60
61 #include <assert.h>
62 #include <ctype.h>
63 #include <errno.h>
64 #include <locale.h>
65 #include <stdint.h>
66 #include <stdio.h>
67 #include <string.h>
68 #include <type_traits>
69
70 using namespace lldb;
71 using namespace lldb_private;
72 using llvm::None;
73 using llvm::Optional;
74 using llvm::StringRef;
75
76 // we may want curses to be disabled for some builds for instance, windows
77 #if LLDB_ENABLE_CURSES
78
79 #define KEY_RETURN 10
80 #define KEY_ESCAPE 27
81
82 namespace curses {
83 class Menu;
84 class MenuDelegate;
85 class Window;
86 class WindowDelegate;
87 typedef std::shared_ptr<Menu> MenuSP;
88 typedef std::shared_ptr<MenuDelegate> MenuDelegateSP;
89 typedef std::shared_ptr<Window> WindowSP;
90 typedef std::shared_ptr<WindowDelegate> WindowDelegateSP;
91 typedef std::vector<MenuSP> Menus;
92 typedef std::vector<WindowSP> Windows;
93 typedef std::vector<WindowDelegateSP> WindowDelegates;
94
95 #if 0
96 type summary add -s "x=${var.x}, y=${var.y}" curses::Point
97 type summary add -s "w=${var.width}, h=${var.height}" curses::Size
98 type summary add -s "${var.origin%S} ${var.size%S}" curses::Rect
99 #endif
100
101 struct Point {
102 int x;
103 int y;
104
Pointcurses::Point105 Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
106
Clearcurses::Point107 void Clear() {
108 x = 0;
109 y = 0;
110 }
111
operator +=curses::Point112 Point &operator+=(const Point &rhs) {
113 x += rhs.x;
114 y += rhs.y;
115 return *this;
116 }
117
Dumpcurses::Point118 void Dump() { printf("(x=%i, y=%i)\n", x, y); }
119 };
120
operator ==(const Point & lhs,const Point & rhs)121 bool operator==(const Point &lhs, const Point &rhs) {
122 return lhs.x == rhs.x && lhs.y == rhs.y;
123 }
124
operator !=(const Point & lhs,const Point & rhs)125 bool operator!=(const Point &lhs, const Point &rhs) {
126 return lhs.x != rhs.x || lhs.y != rhs.y;
127 }
128
129 struct Size {
130 int width;
131 int height;
Sizecurses::Size132 Size(int w = 0, int h = 0) : width(w), height(h) {}
133
Clearcurses::Size134 void Clear() {
135 width = 0;
136 height = 0;
137 }
138
Dumpcurses::Size139 void Dump() { printf("(w=%i, h=%i)\n", width, height); }
140 };
141
operator ==(const Size & lhs,const Size & rhs)142 bool operator==(const Size &lhs, const Size &rhs) {
143 return lhs.width == rhs.width && lhs.height == rhs.height;
144 }
145
operator !=(const Size & lhs,const Size & rhs)146 bool operator!=(const Size &lhs, const Size &rhs) {
147 return lhs.width != rhs.width || lhs.height != rhs.height;
148 }
149
150 struct Rect {
151 Point origin;
152 Size size;
153
Rectcurses::Rect154 Rect() : origin(), size() {}
155
Rectcurses::Rect156 Rect(const Point &p, const Size &s) : origin(p), size(s) {}
157
Clearcurses::Rect158 void Clear() {
159 origin.Clear();
160 size.Clear();
161 }
162
Dumpcurses::Rect163 void Dump() {
164 printf("(x=%i, y=%i), w=%i, h=%i)\n", origin.x, origin.y, size.width,
165 size.height);
166 }
167
Insetcurses::Rect168 void Inset(int w, int h) {
169 if (size.width > w * 2)
170 size.width -= w * 2;
171 origin.x += w;
172
173 if (size.height > h * 2)
174 size.height -= h * 2;
175 origin.y += h;
176 }
177
178 // Return a status bar rectangle which is the last line of this rectangle.
179 // This rectangle will be modified to not include the status bar area.
MakeStatusBarcurses::Rect180 Rect MakeStatusBar() {
181 Rect status_bar;
182 if (size.height > 1) {
183 status_bar.origin.x = origin.x;
184 status_bar.origin.y = size.height;
185 status_bar.size.width = size.width;
186 status_bar.size.height = 1;
187 --size.height;
188 }
189 return status_bar;
190 }
191
192 // Return a menubar rectangle which is the first line of this rectangle. This
193 // rectangle will be modified to not include the menubar area.
MakeMenuBarcurses::Rect194 Rect MakeMenuBar() {
195 Rect menubar;
196 if (size.height > 1) {
197 menubar.origin.x = origin.x;
198 menubar.origin.y = origin.y;
199 menubar.size.width = size.width;
200 menubar.size.height = 1;
201 ++origin.y;
202 --size.height;
203 }
204 return menubar;
205 }
206
HorizontalSplitPercentagecurses::Rect207 void HorizontalSplitPercentage(float top_percentage, Rect &top,
208 Rect &bottom) const {
209 float top_height = top_percentage * size.height;
210 HorizontalSplit(top_height, top, bottom);
211 }
212
HorizontalSplitcurses::Rect213 void HorizontalSplit(int top_height, Rect &top, Rect &bottom) const {
214 top = *this;
215 if (top_height < size.height) {
216 top.size.height = top_height;
217 bottom.origin.x = origin.x;
218 bottom.origin.y = origin.y + top.size.height;
219 bottom.size.width = size.width;
220 bottom.size.height = size.height - top.size.height;
221 } else {
222 bottom.Clear();
223 }
224 }
225
VerticalSplitPercentagecurses::Rect226 void VerticalSplitPercentage(float left_percentage, Rect &left,
227 Rect &right) const {
228 float left_width = left_percentage * size.width;
229 VerticalSplit(left_width, left, right);
230 }
231
VerticalSplitcurses::Rect232 void VerticalSplit(int left_width, Rect &left, Rect &right) const {
233 left = *this;
234 if (left_width < size.width) {
235 left.size.width = left_width;
236 right.origin.x = origin.x + left.size.width;
237 right.origin.y = origin.y;
238 right.size.width = size.width - left.size.width;
239 right.size.height = size.height;
240 } else {
241 right.Clear();
242 }
243 }
244 };
245
operator ==(const Rect & lhs,const Rect & rhs)246 bool operator==(const Rect &lhs, const Rect &rhs) {
247 return lhs.origin == rhs.origin && lhs.size == rhs.size;
248 }
249
operator !=(const Rect & lhs,const Rect & rhs)250 bool operator!=(const Rect &lhs, const Rect &rhs) {
251 return lhs.origin != rhs.origin || lhs.size != rhs.size;
252 }
253
254 enum HandleCharResult {
255 eKeyNotHandled = 0,
256 eKeyHandled = 1,
257 eQuitApplication = 2
258 };
259
260 enum class MenuActionResult {
261 Handled,
262 NotHandled,
263 Quit // Exit all menus and quit
264 };
265
266 struct KeyHelp {
267 int ch;
268 const char *description;
269 };
270
271 class WindowDelegate {
272 public:
273 virtual ~WindowDelegate() = default;
274
WindowDelegateDraw(Window & window,bool force)275 virtual bool WindowDelegateDraw(Window &window, bool force) {
276 return false; // Drawing not handled
277 }
278
WindowDelegateHandleChar(Window & window,int key)279 virtual HandleCharResult WindowDelegateHandleChar(Window &window, int key) {
280 return eKeyNotHandled;
281 }
282
WindowDelegateGetHelpText()283 virtual const char *WindowDelegateGetHelpText() { return nullptr; }
284
WindowDelegateGetKeyHelp()285 virtual KeyHelp *WindowDelegateGetKeyHelp() { return nullptr; }
286 };
287
288 class HelpDialogDelegate : public WindowDelegate {
289 public:
290 HelpDialogDelegate(const char *text, KeyHelp *key_help_array);
291
292 ~HelpDialogDelegate() override;
293
294 bool WindowDelegateDraw(Window &window, bool force) override;
295
296 HandleCharResult WindowDelegateHandleChar(Window &window, int key) override;
297
GetNumLines() const298 size_t GetNumLines() const { return m_text.GetSize(); }
299
GetMaxLineLength() const300 size_t GetMaxLineLength() const { return m_text.GetMaxStringLength(); }
301
302 protected:
303 StringList m_text;
304 int m_first_visible_line;
305 };
306
307 class Window {
308 public:
Window(const char * name)309 Window(const char *name)
310 : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr),
311 m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
312 m_prev_active_window_idx(UINT32_MAX), m_delete(false),
313 m_needs_update(true), m_can_activate(true), m_is_subwin(false) {}
314
Window(const char * name,WINDOW * w,bool del=true)315 Window(const char *name, WINDOW *w, bool del = true)
316 : m_name(name), m_window(nullptr), m_panel(nullptr), m_parent(nullptr),
317 m_subwindows(), m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
318 m_prev_active_window_idx(UINT32_MAX), m_delete(del),
319 m_needs_update(true), m_can_activate(true), m_is_subwin(false) {
320 if (w)
321 Reset(w);
322 }
323
Window(const char * name,const Rect & bounds)324 Window(const char *name, const Rect &bounds)
325 : m_name(name), m_window(nullptr), m_parent(nullptr), m_subwindows(),
326 m_delegate_sp(), m_curr_active_window_idx(UINT32_MAX),
327 m_prev_active_window_idx(UINT32_MAX), m_delete(true),
328 m_needs_update(true), m_can_activate(true), m_is_subwin(false) {
329 Reset(::newwin(bounds.size.height, bounds.size.width, bounds.origin.y,
330 bounds.origin.y));
331 }
332
~Window()333 virtual ~Window() {
334 RemoveSubWindows();
335 Reset();
336 }
337
Reset(WINDOW * w=nullptr,bool del=true)338 void Reset(WINDOW *w = nullptr, bool del = true) {
339 if (m_window == w)
340 return;
341
342 if (m_panel) {
343 ::del_panel(m_panel);
344 m_panel = nullptr;
345 }
346 if (m_window && m_delete) {
347 ::delwin(m_window);
348 m_window = nullptr;
349 m_delete = false;
350 }
351 if (w) {
352 m_window = w;
353 m_panel = ::new_panel(m_window);
354 m_delete = del;
355 }
356 }
357
AttributeOn(attr_t attr)358 void AttributeOn(attr_t attr) { ::wattron(m_window, attr); }
AttributeOff(attr_t attr)359 void AttributeOff(attr_t attr) { ::wattroff(m_window, attr); }
Box(chtype v_char=ACS_VLINE,chtype h_char=ACS_HLINE)360 void Box(chtype v_char = ACS_VLINE, chtype h_char = ACS_HLINE) {
361 ::box(m_window, v_char, h_char);
362 }
Clear()363 void Clear() { ::wclear(m_window); }
Erase()364 void Erase() { ::werase(m_window); }
GetBounds()365 Rect GetBounds() {
366 return Rect(GetParentOrigin(), GetSize());
367 } // Get the rectangle in our parent window
GetChar()368 int GetChar() { return ::wgetch(m_window); }
GetCursorX()369 int GetCursorX() { return getcurx(m_window); }
GetCursorY()370 int GetCursorY() { return getcury(m_window); }
GetFrame()371 Rect GetFrame() {
372 return Rect(Point(), GetSize());
373 } // Get our rectangle in our own coordinate system
GetParentOrigin()374 Point GetParentOrigin() { return Point(GetParentX(), GetParentY()); }
GetSize()375 Size GetSize() { return Size(GetWidth(), GetHeight()); }
GetParentX()376 int GetParentX() { return getparx(m_window); }
GetParentY()377 int GetParentY() { return getpary(m_window); }
GetMaxX()378 int GetMaxX() { return getmaxx(m_window); }
GetMaxY()379 int GetMaxY() { return getmaxy(m_window); }
GetWidth()380 int GetWidth() { return GetMaxX(); }
GetHeight()381 int GetHeight() { return GetMaxY(); }
MoveCursor(int x,int y)382 void MoveCursor(int x, int y) { ::wmove(m_window, y, x); }
MoveWindow(int x,int y)383 void MoveWindow(int x, int y) { MoveWindow(Point(x, y)); }
Resize(int w,int h)384 void Resize(int w, int h) { ::wresize(m_window, h, w); }
Resize(const Size & size)385 void Resize(const Size &size) {
386 ::wresize(m_window, size.height, size.width);
387 }
PutChar(int ch)388 void PutChar(int ch) { ::waddch(m_window, ch); }
PutCString(const char * s,int len=-1)389 void PutCString(const char *s, int len = -1) { ::waddnstr(m_window, s, len); }
SetBackground(int color_pair_idx)390 void SetBackground(int color_pair_idx) {
391 ::wbkgd(m_window, COLOR_PAIR(color_pair_idx));
392 }
393
PutCStringTruncated(const char * s,int right_pad)394 void PutCStringTruncated(const char *s, int right_pad) {
395 int bytes_left = GetWidth() - GetCursorX();
396 if (bytes_left > right_pad) {
397 bytes_left -= right_pad;
398 ::waddnstr(m_window, s, bytes_left);
399 }
400 }
401
MoveWindow(const Point & origin)402 void MoveWindow(const Point &origin) {
403 const bool moving_window = origin != GetParentOrigin();
404 if (m_is_subwin && moving_window) {
405 // Can't move subwindows, must delete and re-create
406 Size size = GetSize();
407 Reset(::subwin(m_parent->m_window, size.height, size.width, origin.y,
408 origin.x),
409 true);
410 } else {
411 ::mvwin(m_window, origin.y, origin.x);
412 }
413 }
414
SetBounds(const Rect & bounds)415 void SetBounds(const Rect &bounds) {
416 const bool moving_window = bounds.origin != GetParentOrigin();
417 if (m_is_subwin && moving_window) {
418 // Can't move subwindows, must delete and re-create
419 Reset(::subwin(m_parent->m_window, bounds.size.height, bounds.size.width,
420 bounds.origin.y, bounds.origin.x),
421 true);
422 } else {
423 if (moving_window)
424 MoveWindow(bounds.origin);
425 Resize(bounds.size);
426 }
427 }
428
Printf(const char * format,...)429 void Printf(const char *format, ...) __attribute__((format(printf, 2, 3))) {
430 va_list args;
431 va_start(args, format);
432 vwprintw(m_window, format, args);
433 va_end(args);
434 }
435
Touch()436 void Touch() {
437 ::touchwin(m_window);
438 if (m_parent)
439 m_parent->Touch();
440 }
441
CreateSubWindow(const char * name,const Rect & bounds,bool make_active)442 WindowSP CreateSubWindow(const char *name, const Rect &bounds,
443 bool make_active) {
444 auto get_window = [this, &bounds]() {
445 return m_window
446 ? ::subwin(m_window, bounds.size.height, bounds.size.width,
447 bounds.origin.y, bounds.origin.x)
448 : ::newwin(bounds.size.height, bounds.size.width,
449 bounds.origin.y, bounds.origin.x);
450 };
451 WindowSP subwindow_sp = std::make_shared<Window>(name, get_window(), true);
452 subwindow_sp->m_is_subwin = subwindow_sp.operator bool();
453 subwindow_sp->m_parent = this;
454 if (make_active) {
455 m_prev_active_window_idx = m_curr_active_window_idx;
456 m_curr_active_window_idx = m_subwindows.size();
457 }
458 m_subwindows.push_back(subwindow_sp);
459 ::top_panel(subwindow_sp->m_panel);
460 m_needs_update = true;
461 return subwindow_sp;
462 }
463
RemoveSubWindow(Window * window)464 bool RemoveSubWindow(Window *window) {
465 Windows::iterator pos, end = m_subwindows.end();
466 size_t i = 0;
467 for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) {
468 if ((*pos).get() == window) {
469 if (m_prev_active_window_idx == i)
470 m_prev_active_window_idx = UINT32_MAX;
471 else if (m_prev_active_window_idx != UINT32_MAX &&
472 m_prev_active_window_idx > i)
473 --m_prev_active_window_idx;
474
475 if (m_curr_active_window_idx == i)
476 m_curr_active_window_idx = UINT32_MAX;
477 else if (m_curr_active_window_idx != UINT32_MAX &&
478 m_curr_active_window_idx > i)
479 --m_curr_active_window_idx;
480 window->Erase();
481 m_subwindows.erase(pos);
482 m_needs_update = true;
483 if (m_parent)
484 m_parent->Touch();
485 else
486 ::touchwin(stdscr);
487 return true;
488 }
489 }
490 return false;
491 }
492
FindSubWindow(const char * name)493 WindowSP FindSubWindow(const char *name) {
494 Windows::iterator pos, end = m_subwindows.end();
495 size_t i = 0;
496 for (pos = m_subwindows.begin(); pos != end; ++pos, ++i) {
497 if ((*pos)->m_name == name)
498 return *pos;
499 }
500 return WindowSP();
501 }
502
RemoveSubWindows()503 void RemoveSubWindows() {
504 m_curr_active_window_idx = UINT32_MAX;
505 m_prev_active_window_idx = UINT32_MAX;
506 for (Windows::iterator pos = m_subwindows.begin();
507 pos != m_subwindows.end(); pos = m_subwindows.erase(pos)) {
508 (*pos)->Erase();
509 }
510 if (m_parent)
511 m_parent->Touch();
512 else
513 ::touchwin(stdscr);
514 }
515
get()516 WINDOW *get() { return m_window; }
517
operator WINDOW*()518 operator WINDOW *() { return m_window; }
519
520 // Window drawing utilities
DrawTitleBox(const char * title,const char * bottom_message=nullptr)521 void DrawTitleBox(const char *title, const char *bottom_message = nullptr) {
522 attr_t attr = 0;
523 if (IsActive())
524 attr = A_BOLD | COLOR_PAIR(2);
525 else
526 attr = 0;
527 if (attr)
528 AttributeOn(attr);
529
530 Box();
531 MoveCursor(3, 0);
532
533 if (title && title[0]) {
534 PutChar('<');
535 PutCString(title);
536 PutChar('>');
537 }
538
539 if (bottom_message && bottom_message[0]) {
540 int bottom_message_length = strlen(bottom_message);
541 int x = GetWidth() - 3 - (bottom_message_length + 2);
542
543 if (x > 0) {
544 MoveCursor(x, GetHeight() - 1);
545 PutChar('[');
546 PutCString(bottom_message);
547 PutChar(']');
548 } else {
549 MoveCursor(1, GetHeight() - 1);
550 PutChar('[');
551 PutCStringTruncated(bottom_message, 1);
552 }
553 }
554 if (attr)
555 AttributeOff(attr);
556 }
557
Draw(bool force)558 virtual void Draw(bool force) {
559 if (m_delegate_sp && m_delegate_sp->WindowDelegateDraw(*this, force))
560 return;
561
562 for (auto &subwindow_sp : m_subwindows)
563 subwindow_sp->Draw(force);
564 }
565
CreateHelpSubwindow()566 bool CreateHelpSubwindow() {
567 if (m_delegate_sp) {
568 const char *text = m_delegate_sp->WindowDelegateGetHelpText();
569 KeyHelp *key_help = m_delegate_sp->WindowDelegateGetKeyHelp();
570 if ((text && text[0]) || key_help) {
571 std::unique_ptr<HelpDialogDelegate> help_delegate_up(
572 new HelpDialogDelegate(text, key_help));
573 const size_t num_lines = help_delegate_up->GetNumLines();
574 const size_t max_length = help_delegate_up->GetMaxLineLength();
575 Rect bounds = GetBounds();
576 bounds.Inset(1, 1);
577 if (max_length + 4 < static_cast<size_t>(bounds.size.width)) {
578 bounds.origin.x += (bounds.size.width - max_length + 4) / 2;
579 bounds.size.width = max_length + 4;
580 } else {
581 if (bounds.size.width > 100) {
582 const int inset_w = bounds.size.width / 4;
583 bounds.origin.x += inset_w;
584 bounds.size.width -= 2 * inset_w;
585 }
586 }
587
588 if (num_lines + 2 < static_cast<size_t>(bounds.size.height)) {
589 bounds.origin.y += (bounds.size.height - num_lines + 2) / 2;
590 bounds.size.height = num_lines + 2;
591 } else {
592 if (bounds.size.height > 100) {
593 const int inset_h = bounds.size.height / 4;
594 bounds.origin.y += inset_h;
595 bounds.size.height -= 2 * inset_h;
596 }
597 }
598 WindowSP help_window_sp;
599 Window *parent_window = GetParent();
600 if (parent_window)
601 help_window_sp = parent_window->CreateSubWindow("Help", bounds, true);
602 else
603 help_window_sp = CreateSubWindow("Help", bounds, true);
604 help_window_sp->SetDelegate(
605 WindowDelegateSP(help_delegate_up.release()));
606 return true;
607 }
608 }
609 return false;
610 }
611
HandleChar(int key)612 virtual HandleCharResult HandleChar(int key) {
613 // Always check the active window first
614 HandleCharResult result = eKeyNotHandled;
615 WindowSP active_window_sp = GetActiveWindow();
616 if (active_window_sp) {
617 result = active_window_sp->HandleChar(key);
618 if (result != eKeyNotHandled)
619 return result;
620 }
621
622 if (m_delegate_sp) {
623 result = m_delegate_sp->WindowDelegateHandleChar(*this, key);
624 if (result != eKeyNotHandled)
625 return result;
626 }
627
628 // Then check for any windows that want any keys that weren't handled. This
629 // is typically only for a menubar. Make a copy of the subwindows in case
630 // any HandleChar() functions muck with the subwindows. If we don't do
631 // this, we can crash when iterating over the subwindows.
632 Windows subwindows(m_subwindows);
633 for (auto subwindow_sp : subwindows) {
634 if (!subwindow_sp->m_can_activate) {
635 HandleCharResult result = subwindow_sp->HandleChar(key);
636 if (result != eKeyNotHandled)
637 return result;
638 }
639 }
640
641 return eKeyNotHandled;
642 }
643
GetActiveWindow()644 WindowSP GetActiveWindow() {
645 if (!m_subwindows.empty()) {
646 if (m_curr_active_window_idx >= m_subwindows.size()) {
647 if (m_prev_active_window_idx < m_subwindows.size()) {
648 m_curr_active_window_idx = m_prev_active_window_idx;
649 m_prev_active_window_idx = UINT32_MAX;
650 } else if (IsActive()) {
651 m_prev_active_window_idx = UINT32_MAX;
652 m_curr_active_window_idx = UINT32_MAX;
653
654 // Find first window that wants to be active if this window is active
655 const size_t num_subwindows = m_subwindows.size();
656 for (size_t i = 0; i < num_subwindows; ++i) {
657 if (m_subwindows[i]->GetCanBeActive()) {
658 m_curr_active_window_idx = i;
659 break;
660 }
661 }
662 }
663 }
664
665 if (m_curr_active_window_idx < m_subwindows.size())
666 return m_subwindows[m_curr_active_window_idx];
667 }
668 return WindowSP();
669 }
670
GetCanBeActive() const671 bool GetCanBeActive() const { return m_can_activate; }
672
SetCanBeActive(bool b)673 void SetCanBeActive(bool b) { m_can_activate = b; }
674
SetDelegate(const WindowDelegateSP & delegate_sp)675 void SetDelegate(const WindowDelegateSP &delegate_sp) {
676 m_delegate_sp = delegate_sp;
677 }
678
GetParent() const679 Window *GetParent() const { return m_parent; }
680
IsActive() const681 bool IsActive() const {
682 if (m_parent)
683 return m_parent->GetActiveWindow().get() == this;
684 else
685 return true; // Top level window is always active
686 }
687
SelectNextWindowAsActive()688 void SelectNextWindowAsActive() {
689 // Move active focus to next window
690 const size_t num_subwindows = m_subwindows.size();
691 if (m_curr_active_window_idx == UINT32_MAX) {
692 uint32_t idx = 0;
693 for (auto subwindow_sp : m_subwindows) {
694 if (subwindow_sp->GetCanBeActive()) {
695 m_curr_active_window_idx = idx;
696 break;
697 }
698 ++idx;
699 }
700 } else if (m_curr_active_window_idx + 1 < num_subwindows) {
701 bool handled = false;
702 m_prev_active_window_idx = m_curr_active_window_idx;
703 for (size_t idx = m_curr_active_window_idx + 1; idx < num_subwindows;
704 ++idx) {
705 if (m_subwindows[idx]->GetCanBeActive()) {
706 m_curr_active_window_idx = idx;
707 handled = true;
708 break;
709 }
710 }
711 if (!handled) {
712 for (size_t idx = 0; idx <= m_prev_active_window_idx; ++idx) {
713 if (m_subwindows[idx]->GetCanBeActive()) {
714 m_curr_active_window_idx = idx;
715 break;
716 }
717 }
718 }
719 } else {
720 m_prev_active_window_idx = m_curr_active_window_idx;
721 for (size_t idx = 0; idx < num_subwindows; ++idx) {
722 if (m_subwindows[idx]->GetCanBeActive()) {
723 m_curr_active_window_idx = idx;
724 break;
725 }
726 }
727 }
728 }
729
GetName() const730 const char *GetName() const { return m_name.c_str(); }
731
732 protected:
733 std::string m_name;
734 WINDOW *m_window;
735 PANEL *m_panel;
736 Window *m_parent;
737 Windows m_subwindows;
738 WindowDelegateSP m_delegate_sp;
739 uint32_t m_curr_active_window_idx;
740 uint32_t m_prev_active_window_idx;
741 bool m_delete;
742 bool m_needs_update;
743 bool m_can_activate;
744 bool m_is_subwin;
745
746 private:
747 Window(const Window &) = delete;
748 const Window &operator=(const Window &) = delete;
749 };
750
751 class MenuDelegate {
752 public:
753 virtual ~MenuDelegate() = default;
754
755 virtual MenuActionResult MenuDelegateAction(Menu &menu) = 0;
756 };
757
758 class Menu : public WindowDelegate {
759 public:
760 enum class Type { Invalid, Bar, Item, Separator };
761
762 // Menubar or separator constructor
763 Menu(Type type);
764
765 // Menuitem constructor
766 Menu(const char *name, const char *key_name, int key_value,
767 uint64_t identifier);
768
769 ~Menu() override = default;
770
GetDelegate() const771 const MenuDelegateSP &GetDelegate() const { return m_delegate_sp; }
772
SetDelegate(const MenuDelegateSP & delegate_sp)773 void SetDelegate(const MenuDelegateSP &delegate_sp) {
774 m_delegate_sp = delegate_sp;
775 }
776
777 void RecalculateNameLengths();
778
779 void AddSubmenu(const MenuSP &menu_sp);
780
781 int DrawAndRunMenu(Window &window);
782
783 void DrawMenuTitle(Window &window, bool highlight);
784
785 bool WindowDelegateDraw(Window &window, bool force) override;
786
787 HandleCharResult WindowDelegateHandleChar(Window &window, int key) override;
788
ActionPrivate(Menu & menu)789 MenuActionResult ActionPrivate(Menu &menu) {
790 MenuActionResult result = MenuActionResult::NotHandled;
791 if (m_delegate_sp) {
792 result = m_delegate_sp->MenuDelegateAction(menu);
793 if (result != MenuActionResult::NotHandled)
794 return result;
795 } else if (m_parent) {
796 result = m_parent->ActionPrivate(menu);
797 if (result != MenuActionResult::NotHandled)
798 return result;
799 }
800 return m_canned_result;
801 }
802
Action()803 MenuActionResult Action() {
804 // Call the recursive action so it can try to handle it with the menu
805 // delegate, and if not, try our parent menu
806 return ActionPrivate(*this);
807 }
808
SetCannedResult(MenuActionResult result)809 void SetCannedResult(MenuActionResult result) { m_canned_result = result; }
810
GetSubmenus()811 Menus &GetSubmenus() { return m_submenus; }
812
GetSubmenus() const813 const Menus &GetSubmenus() const { return m_submenus; }
814
GetSelectedSubmenuIndex() const815 int GetSelectedSubmenuIndex() const { return m_selected; }
816
SetSelectedSubmenuIndex(int idx)817 void SetSelectedSubmenuIndex(int idx) { m_selected = idx; }
818
GetType() const819 Type GetType() const { return m_type; }
820
GetStartingColumn() const821 int GetStartingColumn() const { return m_start_col; }
822
SetStartingColumn(int col)823 void SetStartingColumn(int col) { m_start_col = col; }
824
GetKeyValue() const825 int GetKeyValue() const { return m_key_value; }
826
GetName()827 std::string &GetName() { return m_name; }
828
GetDrawWidth() const829 int GetDrawWidth() const {
830 return m_max_submenu_name_length + m_max_submenu_key_name_length + 8;
831 }
832
GetIdentifier() const833 uint64_t GetIdentifier() const { return m_identifier; }
834
SetIdentifier(uint64_t identifier)835 void SetIdentifier(uint64_t identifier) { m_identifier = identifier; }
836
837 protected:
838 std::string m_name;
839 std::string m_key_name;
840 uint64_t m_identifier;
841 Type m_type;
842 int m_key_value;
843 int m_start_col;
844 int m_max_submenu_name_length;
845 int m_max_submenu_key_name_length;
846 int m_selected;
847 Menu *m_parent;
848 Menus m_submenus;
849 WindowSP m_menu_window_sp;
850 MenuActionResult m_canned_result;
851 MenuDelegateSP m_delegate_sp;
852 };
853
854 // Menubar or separator constructor
Menu(Type type)855 Menu::Menu(Type type)
856 : m_name(), m_key_name(), m_identifier(0), m_type(type), m_key_value(0),
857 m_start_col(0), m_max_submenu_name_length(0),
858 m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr),
859 m_submenus(), m_canned_result(MenuActionResult::NotHandled),
860 m_delegate_sp() {}
861
862 // Menuitem constructor
Menu(const char * name,const char * key_name,int key_value,uint64_t identifier)863 Menu::Menu(const char *name, const char *key_name, int key_value,
864 uint64_t identifier)
865 : m_name(), m_key_name(), m_identifier(identifier), m_type(Type::Invalid),
866 m_key_value(key_value), m_start_col(0), m_max_submenu_name_length(0),
867 m_max_submenu_key_name_length(0), m_selected(0), m_parent(nullptr),
868 m_submenus(), m_canned_result(MenuActionResult::NotHandled),
869 m_delegate_sp() {
870 if (name && name[0]) {
871 m_name = name;
872 m_type = Type::Item;
873 if (key_name && key_name[0])
874 m_key_name = key_name;
875 } else {
876 m_type = Type::Separator;
877 }
878 }
879
RecalculateNameLengths()880 void Menu::RecalculateNameLengths() {
881 m_max_submenu_name_length = 0;
882 m_max_submenu_key_name_length = 0;
883 Menus &submenus = GetSubmenus();
884 const size_t num_submenus = submenus.size();
885 for (size_t i = 0; i < num_submenus; ++i) {
886 Menu *submenu = submenus[i].get();
887 if (static_cast<size_t>(m_max_submenu_name_length) < submenu->m_name.size())
888 m_max_submenu_name_length = submenu->m_name.size();
889 if (static_cast<size_t>(m_max_submenu_key_name_length) <
890 submenu->m_key_name.size())
891 m_max_submenu_key_name_length = submenu->m_key_name.size();
892 }
893 }
894
AddSubmenu(const MenuSP & menu_sp)895 void Menu::AddSubmenu(const MenuSP &menu_sp) {
896 menu_sp->m_parent = this;
897 if (static_cast<size_t>(m_max_submenu_name_length) < menu_sp->m_name.size())
898 m_max_submenu_name_length = menu_sp->m_name.size();
899 if (static_cast<size_t>(m_max_submenu_key_name_length) <
900 menu_sp->m_key_name.size())
901 m_max_submenu_key_name_length = menu_sp->m_key_name.size();
902 m_submenus.push_back(menu_sp);
903 }
904
DrawMenuTitle(Window & window,bool highlight)905 void Menu::DrawMenuTitle(Window &window, bool highlight) {
906 if (m_type == Type::Separator) {
907 window.MoveCursor(0, window.GetCursorY());
908 window.PutChar(ACS_LTEE);
909 int width = window.GetWidth();
910 if (width > 2) {
911 width -= 2;
912 for (int i = 0; i < width; ++i)
913 window.PutChar(ACS_HLINE);
914 }
915 window.PutChar(ACS_RTEE);
916 } else {
917 const int shortcut_key = m_key_value;
918 bool underlined_shortcut = false;
919 const attr_t hilgight_attr = A_REVERSE;
920 if (highlight)
921 window.AttributeOn(hilgight_attr);
922 if (llvm::isPrint(shortcut_key)) {
923 size_t lower_pos = m_name.find(tolower(shortcut_key));
924 size_t upper_pos = m_name.find(toupper(shortcut_key));
925 const char *name = m_name.c_str();
926 size_t pos = std::min<size_t>(lower_pos, upper_pos);
927 if (pos != std::string::npos) {
928 underlined_shortcut = true;
929 if (pos > 0) {
930 window.PutCString(name, pos);
931 name += pos;
932 }
933 const attr_t shortcut_attr = A_UNDERLINE | A_BOLD;
934 window.AttributeOn(shortcut_attr);
935 window.PutChar(name[0]);
936 window.AttributeOff(shortcut_attr);
937 name++;
938 if (name[0])
939 window.PutCString(name);
940 }
941 }
942
943 if (!underlined_shortcut) {
944 window.PutCString(m_name.c_str());
945 }
946
947 if (highlight)
948 window.AttributeOff(hilgight_attr);
949
950 if (m_key_name.empty()) {
951 if (!underlined_shortcut && llvm::isPrint(m_key_value)) {
952 window.AttributeOn(COLOR_PAIR(3));
953 window.Printf(" (%c)", m_key_value);
954 window.AttributeOff(COLOR_PAIR(3));
955 }
956 } else {
957 window.AttributeOn(COLOR_PAIR(3));
958 window.Printf(" (%s)", m_key_name.c_str());
959 window.AttributeOff(COLOR_PAIR(3));
960 }
961 }
962 }
963
WindowDelegateDraw(Window & window,bool force)964 bool Menu::WindowDelegateDraw(Window &window, bool force) {
965 Menus &submenus = GetSubmenus();
966 const size_t num_submenus = submenus.size();
967 const int selected_idx = GetSelectedSubmenuIndex();
968 Menu::Type menu_type = GetType();
969 switch (menu_type) {
970 case Menu::Type::Bar: {
971 window.SetBackground(2);
972 window.MoveCursor(0, 0);
973 for (size_t i = 0; i < num_submenus; ++i) {
974 Menu *menu = submenus[i].get();
975 if (i > 0)
976 window.PutChar(' ');
977 menu->SetStartingColumn(window.GetCursorX());
978 window.PutCString("| ");
979 menu->DrawMenuTitle(window, false);
980 }
981 window.PutCString(" |");
982 } break;
983
984 case Menu::Type::Item: {
985 int y = 1;
986 int x = 3;
987 // Draw the menu
988 int cursor_x = 0;
989 int cursor_y = 0;
990 window.Erase();
991 window.SetBackground(2);
992 window.Box();
993 for (size_t i = 0; i < num_submenus; ++i) {
994 const bool is_selected = (i == static_cast<size_t>(selected_idx));
995 window.MoveCursor(x, y + i);
996 if (is_selected) {
997 // Remember where we want the cursor to be
998 cursor_x = x - 1;
999 cursor_y = y + i;
1000 }
1001 submenus[i]->DrawMenuTitle(window, is_selected);
1002 }
1003 window.MoveCursor(cursor_x, cursor_y);
1004 } break;
1005
1006 default:
1007 case Menu::Type::Separator:
1008 break;
1009 }
1010 return true; // Drawing handled...
1011 }
1012
WindowDelegateHandleChar(Window & window,int key)1013 HandleCharResult Menu::WindowDelegateHandleChar(Window &window, int key) {
1014 HandleCharResult result = eKeyNotHandled;
1015
1016 Menus &submenus = GetSubmenus();
1017 const size_t num_submenus = submenus.size();
1018 const int selected_idx = GetSelectedSubmenuIndex();
1019 Menu::Type menu_type = GetType();
1020 if (menu_type == Menu::Type::Bar) {
1021 MenuSP run_menu_sp;
1022 switch (key) {
1023 case KEY_DOWN:
1024 case KEY_UP:
1025 // Show last menu or first menu
1026 if (selected_idx < static_cast<int>(num_submenus))
1027 run_menu_sp = submenus[selected_idx];
1028 else if (!submenus.empty())
1029 run_menu_sp = submenus.front();
1030 result = eKeyHandled;
1031 break;
1032
1033 case KEY_RIGHT:
1034 ++m_selected;
1035 if (m_selected >= static_cast<int>(num_submenus))
1036 m_selected = 0;
1037 if (m_selected < static_cast<int>(num_submenus))
1038 run_menu_sp = submenus[m_selected];
1039 else if (!submenus.empty())
1040 run_menu_sp = submenus.front();
1041 result = eKeyHandled;
1042 break;
1043
1044 case KEY_LEFT:
1045 --m_selected;
1046 if (m_selected < 0)
1047 m_selected = num_submenus - 1;
1048 if (m_selected < static_cast<int>(num_submenus))
1049 run_menu_sp = submenus[m_selected];
1050 else if (!submenus.empty())
1051 run_menu_sp = submenus.front();
1052 result = eKeyHandled;
1053 break;
1054
1055 default:
1056 for (size_t i = 0; i < num_submenus; ++i) {
1057 if (submenus[i]->GetKeyValue() == key) {
1058 SetSelectedSubmenuIndex(i);
1059 run_menu_sp = submenus[i];
1060 result = eKeyHandled;
1061 break;
1062 }
1063 }
1064 break;
1065 }
1066
1067 if (run_menu_sp) {
1068 // Run the action on this menu in case we need to populate the menu with
1069 // dynamic content and also in case check marks, and any other menu
1070 // decorations need to be calculated
1071 if (run_menu_sp->Action() == MenuActionResult::Quit)
1072 return eQuitApplication;
1073
1074 Rect menu_bounds;
1075 menu_bounds.origin.x = run_menu_sp->GetStartingColumn();
1076 menu_bounds.origin.y = 1;
1077 menu_bounds.size.width = run_menu_sp->GetDrawWidth();
1078 menu_bounds.size.height = run_menu_sp->GetSubmenus().size() + 2;
1079 if (m_menu_window_sp)
1080 window.GetParent()->RemoveSubWindow(m_menu_window_sp.get());
1081
1082 m_menu_window_sp = window.GetParent()->CreateSubWindow(
1083 run_menu_sp->GetName().c_str(), menu_bounds, true);
1084 m_menu_window_sp->SetDelegate(run_menu_sp);
1085 }
1086 } else if (menu_type == Menu::Type::Item) {
1087 switch (key) {
1088 case KEY_DOWN:
1089 if (m_submenus.size() > 1) {
1090 const int start_select = m_selected;
1091 while (++m_selected != start_select) {
1092 if (static_cast<size_t>(m_selected) >= num_submenus)
1093 m_selected = 0;
1094 if (m_submenus[m_selected]->GetType() == Type::Separator)
1095 continue;
1096 else
1097 break;
1098 }
1099 return eKeyHandled;
1100 }
1101 break;
1102
1103 case KEY_UP:
1104 if (m_submenus.size() > 1) {
1105 const int start_select = m_selected;
1106 while (--m_selected != start_select) {
1107 if (m_selected < static_cast<int>(0))
1108 m_selected = num_submenus - 1;
1109 if (m_submenus[m_selected]->GetType() == Type::Separator)
1110 continue;
1111 else
1112 break;
1113 }
1114 return eKeyHandled;
1115 }
1116 break;
1117
1118 case KEY_RETURN:
1119 if (static_cast<size_t>(selected_idx) < num_submenus) {
1120 if (submenus[selected_idx]->Action() == MenuActionResult::Quit)
1121 return eQuitApplication;
1122 window.GetParent()->RemoveSubWindow(&window);
1123 return eKeyHandled;
1124 }
1125 break;
1126
1127 case KEY_ESCAPE: // Beware: pressing escape key has 1 to 2 second delay in
1128 // case other chars are entered for escaped sequences
1129 window.GetParent()->RemoveSubWindow(&window);
1130 return eKeyHandled;
1131
1132 default:
1133 for (size_t i = 0; i < num_submenus; ++i) {
1134 Menu *menu = submenus[i].get();
1135 if (menu->GetKeyValue() == key) {
1136 SetSelectedSubmenuIndex(i);
1137 window.GetParent()->RemoveSubWindow(&window);
1138 if (menu->Action() == MenuActionResult::Quit)
1139 return eQuitApplication;
1140 return eKeyHandled;
1141 }
1142 }
1143 break;
1144 }
1145 } else if (menu_type == Menu::Type::Separator) {
1146 }
1147 return result;
1148 }
1149
1150 class Application {
1151 public:
Application(FILE * in,FILE * out)1152 Application(FILE *in, FILE *out)
1153 : m_window_sp(), m_screen(nullptr), m_in(in), m_out(out) {}
1154
~Application()1155 ~Application() {
1156 m_window_delegates.clear();
1157 m_window_sp.reset();
1158 if (m_screen) {
1159 ::delscreen(m_screen);
1160 m_screen = nullptr;
1161 }
1162 }
1163
Initialize()1164 void Initialize() {
1165 ::setlocale(LC_ALL, "");
1166 ::setlocale(LC_CTYPE, "");
1167 m_screen = ::newterm(nullptr, m_out, m_in);
1168 ::start_color();
1169 ::curs_set(0);
1170 ::noecho();
1171 ::keypad(stdscr, TRUE);
1172 }
1173
Terminate()1174 void Terminate() { ::endwin(); }
1175
Run(Debugger & debugger)1176 void Run(Debugger &debugger) {
1177 bool done = false;
1178 int delay_in_tenths_of_a_second = 1;
1179
1180 // Alas the threading model in curses is a bit lame so we need to resort to
1181 // polling every 0.5 seconds. We could poll for stdin ourselves and then
1182 // pass the keys down but then we need to translate all of the escape
1183 // sequences ourselves. So we resort to polling for input because we need
1184 // to receive async process events while in this loop.
1185
1186 halfdelay(delay_in_tenths_of_a_second); // Poll using some number of tenths
1187 // of seconds seconds when calling
1188 // Window::GetChar()
1189
1190 ListenerSP listener_sp(
1191 Listener::MakeListener("lldb.IOHandler.curses.Application"));
1192 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1193 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1194 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1195 debugger.EnableForwardEvents(listener_sp);
1196
1197 bool update = true;
1198 #if defined(__APPLE__)
1199 std::deque<int> escape_chars;
1200 #endif
1201
1202 while (!done) {
1203 if (update) {
1204 m_window_sp->Draw(false);
1205 // All windows should be calling Window::DeferredRefresh() instead of
1206 // Window::Refresh() so we can do a single update and avoid any screen
1207 // blinking
1208 update_panels();
1209
1210 // Cursor hiding isn't working on MacOSX, so hide it in the top left
1211 // corner
1212 m_window_sp->MoveCursor(0, 0);
1213
1214 doupdate();
1215 update = false;
1216 }
1217
1218 #if defined(__APPLE__)
1219 // Terminal.app doesn't map its function keys correctly, F1-F4 default
1220 // to: \033OP, \033OQ, \033OR, \033OS, so lets take care of this here if
1221 // possible
1222 int ch;
1223 if (escape_chars.empty())
1224 ch = m_window_sp->GetChar();
1225 else {
1226 ch = escape_chars.front();
1227 escape_chars.pop_front();
1228 }
1229 if (ch == KEY_ESCAPE) {
1230 int ch2 = m_window_sp->GetChar();
1231 if (ch2 == 'O') {
1232 int ch3 = m_window_sp->GetChar();
1233 switch (ch3) {
1234 case 'P':
1235 ch = KEY_F(1);
1236 break;
1237 case 'Q':
1238 ch = KEY_F(2);
1239 break;
1240 case 'R':
1241 ch = KEY_F(3);
1242 break;
1243 case 'S':
1244 ch = KEY_F(4);
1245 break;
1246 default:
1247 escape_chars.push_back(ch2);
1248 if (ch3 != -1)
1249 escape_chars.push_back(ch3);
1250 break;
1251 }
1252 } else if (ch2 != -1)
1253 escape_chars.push_back(ch2);
1254 }
1255 #else
1256 int ch = m_window_sp->GetChar();
1257
1258 #endif
1259 if (ch == -1) {
1260 if (feof(m_in) || ferror(m_in)) {
1261 done = true;
1262 } else {
1263 // Just a timeout from using halfdelay(), check for events
1264 EventSP event_sp;
1265 while (listener_sp->PeekAtNextEvent()) {
1266 listener_sp->GetEvent(event_sp, std::chrono::seconds(0));
1267
1268 if (event_sp) {
1269 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1270 if (broadcaster) {
1271 // uint32_t event_type = event_sp->GetType();
1272 ConstString broadcaster_class(
1273 broadcaster->GetBroadcasterClass());
1274 if (broadcaster_class == broadcaster_class_process) {
1275 debugger.GetCommandInterpreter().UpdateExecutionContext(
1276 nullptr);
1277 update = true;
1278 continue; // Don't get any key, just update our view
1279 }
1280 }
1281 }
1282 }
1283 }
1284 } else {
1285 HandleCharResult key_result = m_window_sp->HandleChar(ch);
1286 switch (key_result) {
1287 case eKeyHandled:
1288 debugger.GetCommandInterpreter().UpdateExecutionContext(nullptr);
1289 update = true;
1290 break;
1291 case eKeyNotHandled:
1292 break;
1293 case eQuitApplication:
1294 done = true;
1295 break;
1296 }
1297 }
1298 }
1299
1300 debugger.CancelForwardEvents(listener_sp);
1301 }
1302
GetMainWindow()1303 WindowSP &GetMainWindow() {
1304 if (!m_window_sp)
1305 m_window_sp = std::make_shared<Window>("main", stdscr, false);
1306 return m_window_sp;
1307 }
1308
1309 protected:
1310 WindowSP m_window_sp;
1311 WindowDelegates m_window_delegates;
1312 SCREEN *m_screen;
1313 FILE *m_in;
1314 FILE *m_out;
1315 };
1316
1317 } // namespace curses
1318
1319 using namespace curses;
1320
1321 struct Row {
1322 ValueObjectManager value;
1323 Row *parent;
1324 // The process stop ID when the children were calculated.
1325 uint32_t children_stop_id;
1326 int row_idx;
1327 int x;
1328 int y;
1329 bool might_have_children;
1330 bool expanded;
1331 bool calculated_children;
1332 std::vector<Row> children;
1333
RowRow1334 Row(const ValueObjectSP &v, Row *p)
1335 : value(v, lldb::eDynamicDontRunTarget, true), parent(p), row_idx(0),
1336 x(1), y(1), might_have_children(v ? v->MightHaveChildren() : false),
1337 expanded(false), calculated_children(false), children() {}
1338
GetDepthRow1339 size_t GetDepth() const {
1340 if (parent)
1341 return 1 + parent->GetDepth();
1342 return 0;
1343 }
1344
ExpandRow1345 void Expand() { expanded = true; }
1346
GetChildrenRow1347 std::vector<Row> &GetChildren() {
1348 ProcessSP process_sp = value.GetProcessSP();
1349 auto stop_id = process_sp->GetStopID();
1350 if (process_sp && stop_id != children_stop_id) {
1351 children_stop_id = stop_id;
1352 calculated_children = false;
1353 }
1354 if (!calculated_children) {
1355 children.clear();
1356 calculated_children = true;
1357 ValueObjectSP valobj = value.GetSP();
1358 if (valobj) {
1359 const size_t num_children = valobj->GetNumChildren();
1360 for (size_t i = 0; i < num_children; ++i) {
1361 children.push_back(Row(valobj->GetChildAtIndex(i, true), this));
1362 }
1363 }
1364 }
1365 return children;
1366 }
1367
UnexpandRow1368 void Unexpand() {
1369 expanded = false;
1370 calculated_children = false;
1371 children.clear();
1372 }
1373
DrawTreeRow1374 void DrawTree(Window &window) {
1375 if (parent)
1376 parent->DrawTreeForChild(window, this, 0);
1377
1378 if (might_have_children) {
1379 // It we can get UTF8 characters to work we should try to use the
1380 // "symbol" UTF8 string below
1381 // const char *symbol = "";
1382 // if (row.expanded)
1383 // symbol = "\xe2\x96\xbd ";
1384 // else
1385 // symbol = "\xe2\x96\xb7 ";
1386 // window.PutCString (symbol);
1387
1388 // The ACS_DARROW and ACS_RARROW don't look very nice they are just a 'v'
1389 // or '>' character...
1390 // if (expanded)
1391 // window.PutChar (ACS_DARROW);
1392 // else
1393 // window.PutChar (ACS_RARROW);
1394 // Since we can't find any good looking right arrow/down arrow symbols,
1395 // just use a diamond...
1396 window.PutChar(ACS_DIAMOND);
1397 window.PutChar(ACS_HLINE);
1398 }
1399 }
1400
DrawTreeForChildRow1401 void DrawTreeForChild(Window &window, Row *child, uint32_t reverse_depth) {
1402 if (parent)
1403 parent->DrawTreeForChild(window, this, reverse_depth + 1);
1404
1405 if (&GetChildren().back() == child) {
1406 // Last child
1407 if (reverse_depth == 0) {
1408 window.PutChar(ACS_LLCORNER);
1409 window.PutChar(ACS_HLINE);
1410 } else {
1411 window.PutChar(' ');
1412 window.PutChar(' ');
1413 }
1414 } else {
1415 if (reverse_depth == 0) {
1416 window.PutChar(ACS_LTEE);
1417 window.PutChar(ACS_HLINE);
1418 } else {
1419 window.PutChar(ACS_VLINE);
1420 window.PutChar(' ');
1421 }
1422 }
1423 }
1424 };
1425
1426 struct DisplayOptions {
1427 bool show_types;
1428 };
1429
1430 class TreeItem;
1431
1432 class TreeDelegate {
1433 public:
1434 TreeDelegate() = default;
1435 virtual ~TreeDelegate() = default;
1436
1437 virtual void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) = 0;
1438 virtual void TreeDelegateGenerateChildren(TreeItem &item) = 0;
1439 virtual bool TreeDelegateItemSelected(
1440 TreeItem &item) = 0; // Return true if we need to update views
1441 };
1442
1443 typedef std::shared_ptr<TreeDelegate> TreeDelegateSP;
1444
1445 class TreeItem {
1446 public:
TreeItem(TreeItem * parent,TreeDelegate & delegate,bool might_have_children)1447 TreeItem(TreeItem *parent, TreeDelegate &delegate, bool might_have_children)
1448 : m_parent(parent), m_delegate(delegate), m_user_data(nullptr),
1449 m_identifier(0), m_row_idx(-1), m_children(),
1450 m_might_have_children(might_have_children), m_is_expanded(false) {}
1451
operator =(const TreeItem & rhs)1452 TreeItem &operator=(const TreeItem &rhs) {
1453 if (this != &rhs) {
1454 m_parent = rhs.m_parent;
1455 m_delegate = rhs.m_delegate;
1456 m_user_data = rhs.m_user_data;
1457 m_identifier = rhs.m_identifier;
1458 m_row_idx = rhs.m_row_idx;
1459 m_children = rhs.m_children;
1460 m_might_have_children = rhs.m_might_have_children;
1461 m_is_expanded = rhs.m_is_expanded;
1462 }
1463 return *this;
1464 }
1465
1466 TreeItem(const TreeItem &) = default;
1467
GetDepth() const1468 size_t GetDepth() const {
1469 if (m_parent)
1470 return 1 + m_parent->GetDepth();
1471 return 0;
1472 }
1473
GetRowIndex() const1474 int GetRowIndex() const { return m_row_idx; }
1475
ClearChildren()1476 void ClearChildren() { m_children.clear(); }
1477
Resize(size_t n,const TreeItem & t)1478 void Resize(size_t n, const TreeItem &t) { m_children.resize(n, t); }
1479
operator [](size_t i)1480 TreeItem &operator[](size_t i) { return m_children[i]; }
1481
SetRowIndex(int row_idx)1482 void SetRowIndex(int row_idx) { m_row_idx = row_idx; }
1483
GetNumChildren()1484 size_t GetNumChildren() {
1485 m_delegate.TreeDelegateGenerateChildren(*this);
1486 return m_children.size();
1487 }
1488
ItemWasSelected()1489 void ItemWasSelected() { m_delegate.TreeDelegateItemSelected(*this); }
1490
CalculateRowIndexes(int & row_idx)1491 void CalculateRowIndexes(int &row_idx) {
1492 SetRowIndex(row_idx);
1493 ++row_idx;
1494
1495 const bool expanded = IsExpanded();
1496
1497 // The root item must calculate its children, or we must calculate the
1498 // number of children if the item is expanded
1499 if (m_parent == nullptr || expanded)
1500 GetNumChildren();
1501
1502 for (auto &item : m_children) {
1503 if (expanded)
1504 item.CalculateRowIndexes(row_idx);
1505 else
1506 item.SetRowIndex(-1);
1507 }
1508 }
1509
GetParent()1510 TreeItem *GetParent() { return m_parent; }
1511
IsExpanded() const1512 bool IsExpanded() const { return m_is_expanded; }
1513
Expand()1514 void Expand() { m_is_expanded = true; }
1515
Unexpand()1516 void Unexpand() { m_is_expanded = false; }
1517
Draw(Window & window,const int first_visible_row,const uint32_t selected_row_idx,int & row_idx,int & num_rows_left)1518 bool Draw(Window &window, const int first_visible_row,
1519 const uint32_t selected_row_idx, int &row_idx, int &num_rows_left) {
1520 if (num_rows_left <= 0)
1521 return false;
1522
1523 if (m_row_idx >= first_visible_row) {
1524 window.MoveCursor(2, row_idx + 1);
1525
1526 if (m_parent)
1527 m_parent->DrawTreeForChild(window, this, 0);
1528
1529 if (m_might_have_children) {
1530 // It we can get UTF8 characters to work we should try to use the
1531 // "symbol" UTF8 string below
1532 // const char *symbol = "";
1533 // if (row.expanded)
1534 // symbol = "\xe2\x96\xbd ";
1535 // else
1536 // symbol = "\xe2\x96\xb7 ";
1537 // window.PutCString (symbol);
1538
1539 // The ACS_DARROW and ACS_RARROW don't look very nice they are just a
1540 // 'v' or '>' character...
1541 // if (expanded)
1542 // window.PutChar (ACS_DARROW);
1543 // else
1544 // window.PutChar (ACS_RARROW);
1545 // Since we can't find any good looking right arrow/down arrow symbols,
1546 // just use a diamond...
1547 window.PutChar(ACS_DIAMOND);
1548 window.PutChar(ACS_HLINE);
1549 }
1550 bool highlight = (selected_row_idx == static_cast<size_t>(m_row_idx)) &&
1551 window.IsActive();
1552
1553 if (highlight)
1554 window.AttributeOn(A_REVERSE);
1555
1556 m_delegate.TreeDelegateDrawTreeItem(*this, window);
1557
1558 if (highlight)
1559 window.AttributeOff(A_REVERSE);
1560 ++row_idx;
1561 --num_rows_left;
1562 }
1563
1564 if (num_rows_left <= 0)
1565 return false; // We are done drawing...
1566
1567 if (IsExpanded()) {
1568 for (auto &item : m_children) {
1569 // If we displayed all the rows and item.Draw() returns false we are
1570 // done drawing and can exit this for loop
1571 if (!item.Draw(window, first_visible_row, selected_row_idx, row_idx,
1572 num_rows_left))
1573 break;
1574 }
1575 }
1576 return num_rows_left >= 0; // Return true if not done drawing yet
1577 }
1578
DrawTreeForChild(Window & window,TreeItem * child,uint32_t reverse_depth)1579 void DrawTreeForChild(Window &window, TreeItem *child,
1580 uint32_t reverse_depth) {
1581 if (m_parent)
1582 m_parent->DrawTreeForChild(window, this, reverse_depth + 1);
1583
1584 if (&m_children.back() == child) {
1585 // Last child
1586 if (reverse_depth == 0) {
1587 window.PutChar(ACS_LLCORNER);
1588 window.PutChar(ACS_HLINE);
1589 } else {
1590 window.PutChar(' ');
1591 window.PutChar(' ');
1592 }
1593 } else {
1594 if (reverse_depth == 0) {
1595 window.PutChar(ACS_LTEE);
1596 window.PutChar(ACS_HLINE);
1597 } else {
1598 window.PutChar(ACS_VLINE);
1599 window.PutChar(' ');
1600 }
1601 }
1602 }
1603
GetItemForRowIndex(uint32_t row_idx)1604 TreeItem *GetItemForRowIndex(uint32_t row_idx) {
1605 if (static_cast<uint32_t>(m_row_idx) == row_idx)
1606 return this;
1607 if (m_children.empty())
1608 return nullptr;
1609 if (IsExpanded()) {
1610 for (auto &item : m_children) {
1611 TreeItem *selected_item_ptr = item.GetItemForRowIndex(row_idx);
1612 if (selected_item_ptr)
1613 return selected_item_ptr;
1614 }
1615 }
1616 return nullptr;
1617 }
1618
GetUserData() const1619 void *GetUserData() const { return m_user_data; }
1620
SetUserData(void * user_data)1621 void SetUserData(void *user_data) { m_user_data = user_data; }
1622
GetIdentifier() const1623 uint64_t GetIdentifier() const { return m_identifier; }
1624
SetIdentifier(uint64_t identifier)1625 void SetIdentifier(uint64_t identifier) { m_identifier = identifier; }
1626
SetMightHaveChildren(bool b)1627 void SetMightHaveChildren(bool b) { m_might_have_children = b; }
1628
1629 protected:
1630 TreeItem *m_parent;
1631 TreeDelegate &m_delegate;
1632 void *m_user_data;
1633 uint64_t m_identifier;
1634 int m_row_idx; // Zero based visible row index, -1 if not visible or for the
1635 // root item
1636 std::vector<TreeItem> m_children;
1637 bool m_might_have_children;
1638 bool m_is_expanded;
1639 };
1640
1641 class TreeWindowDelegate : public WindowDelegate {
1642 public:
TreeWindowDelegate(Debugger & debugger,const TreeDelegateSP & delegate_sp)1643 TreeWindowDelegate(Debugger &debugger, const TreeDelegateSP &delegate_sp)
1644 : m_debugger(debugger), m_delegate_sp(delegate_sp),
1645 m_root(nullptr, *delegate_sp, true), m_selected_item(nullptr),
1646 m_num_rows(0), m_selected_row_idx(0), m_first_visible_row(0),
1647 m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {}
1648
NumVisibleRows() const1649 int NumVisibleRows() const { return m_max_y - m_min_y; }
1650
WindowDelegateDraw(Window & window,bool force)1651 bool WindowDelegateDraw(Window &window, bool force) override {
1652 ExecutionContext exe_ctx(
1653 m_debugger.GetCommandInterpreter().GetExecutionContext());
1654 Process *process = exe_ctx.GetProcessPtr();
1655
1656 bool display_content = false;
1657 if (process) {
1658 StateType state = process->GetState();
1659 if (StateIsStoppedState(state, true)) {
1660 // We are stopped, so it is ok to
1661 display_content = true;
1662 } else if (StateIsRunningState(state)) {
1663 return true; // Don't do any updating when we are running
1664 }
1665 }
1666
1667 m_min_x = 2;
1668 m_min_y = 1;
1669 m_max_x = window.GetWidth() - 1;
1670 m_max_y = window.GetHeight() - 1;
1671
1672 window.Erase();
1673 window.DrawTitleBox(window.GetName());
1674
1675 if (display_content) {
1676 const int num_visible_rows = NumVisibleRows();
1677 m_num_rows = 0;
1678 m_root.CalculateRowIndexes(m_num_rows);
1679
1680 // If we unexpanded while having something selected our total number of
1681 // rows is less than the num visible rows, then make sure we show all the
1682 // rows by setting the first visible row accordingly.
1683 if (m_first_visible_row > 0 && m_num_rows < num_visible_rows)
1684 m_first_visible_row = 0;
1685
1686 // Make sure the selected row is always visible
1687 if (m_selected_row_idx < m_first_visible_row)
1688 m_first_visible_row = m_selected_row_idx;
1689 else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx)
1690 m_first_visible_row = m_selected_row_idx - num_visible_rows + 1;
1691
1692 int row_idx = 0;
1693 int num_rows_left = num_visible_rows;
1694 m_root.Draw(window, m_first_visible_row, m_selected_row_idx, row_idx,
1695 num_rows_left);
1696 // Get the selected row
1697 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
1698 } else {
1699 m_selected_item = nullptr;
1700 }
1701
1702 return true; // Drawing handled
1703 }
1704
WindowDelegateGetHelpText()1705 const char *WindowDelegateGetHelpText() override {
1706 return "Thread window keyboard shortcuts:";
1707 }
1708
WindowDelegateGetKeyHelp()1709 KeyHelp *WindowDelegateGetKeyHelp() override {
1710 static curses::KeyHelp g_source_view_key_help[] = {
1711 {KEY_UP, "Select previous item"},
1712 {KEY_DOWN, "Select next item"},
1713 {KEY_RIGHT, "Expand the selected item"},
1714 {KEY_LEFT,
1715 "Unexpand the selected item or select parent if not expanded"},
1716 {KEY_PPAGE, "Page up"},
1717 {KEY_NPAGE, "Page down"},
1718 {'h', "Show help dialog"},
1719 {' ', "Toggle item expansion"},
1720 {',', "Page up"},
1721 {'.', "Page down"},
1722 {'\0', nullptr}};
1723 return g_source_view_key_help;
1724 }
1725
WindowDelegateHandleChar(Window & window,int c)1726 HandleCharResult WindowDelegateHandleChar(Window &window, int c) override {
1727 switch (c) {
1728 case ',':
1729 case KEY_PPAGE:
1730 // Page up key
1731 if (m_first_visible_row > 0) {
1732 if (m_first_visible_row > m_max_y)
1733 m_first_visible_row -= m_max_y;
1734 else
1735 m_first_visible_row = 0;
1736 m_selected_row_idx = m_first_visible_row;
1737 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
1738 if (m_selected_item)
1739 m_selected_item->ItemWasSelected();
1740 }
1741 return eKeyHandled;
1742
1743 case '.':
1744 case KEY_NPAGE:
1745 // Page down key
1746 if (m_num_rows > m_max_y) {
1747 if (m_first_visible_row + m_max_y < m_num_rows) {
1748 m_first_visible_row += m_max_y;
1749 m_selected_row_idx = m_first_visible_row;
1750 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
1751 if (m_selected_item)
1752 m_selected_item->ItemWasSelected();
1753 }
1754 }
1755 return eKeyHandled;
1756
1757 case KEY_UP:
1758 if (m_selected_row_idx > 0) {
1759 --m_selected_row_idx;
1760 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
1761 if (m_selected_item)
1762 m_selected_item->ItemWasSelected();
1763 }
1764 return eKeyHandled;
1765
1766 case KEY_DOWN:
1767 if (m_selected_row_idx + 1 < m_num_rows) {
1768 ++m_selected_row_idx;
1769 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
1770 if (m_selected_item)
1771 m_selected_item->ItemWasSelected();
1772 }
1773 return eKeyHandled;
1774
1775 case KEY_RIGHT:
1776 if (m_selected_item) {
1777 if (!m_selected_item->IsExpanded())
1778 m_selected_item->Expand();
1779 }
1780 return eKeyHandled;
1781
1782 case KEY_LEFT:
1783 if (m_selected_item) {
1784 if (m_selected_item->IsExpanded())
1785 m_selected_item->Unexpand();
1786 else if (m_selected_item->GetParent()) {
1787 m_selected_row_idx = m_selected_item->GetParent()->GetRowIndex();
1788 m_selected_item = m_root.GetItemForRowIndex(m_selected_row_idx);
1789 if (m_selected_item)
1790 m_selected_item->ItemWasSelected();
1791 }
1792 }
1793 return eKeyHandled;
1794
1795 case ' ':
1796 // Toggle expansion state when SPACE is pressed
1797 if (m_selected_item) {
1798 if (m_selected_item->IsExpanded())
1799 m_selected_item->Unexpand();
1800 else
1801 m_selected_item->Expand();
1802 }
1803 return eKeyHandled;
1804
1805 case 'h':
1806 window.CreateHelpSubwindow();
1807 return eKeyHandled;
1808
1809 default:
1810 break;
1811 }
1812 return eKeyNotHandled;
1813 }
1814
1815 protected:
1816 Debugger &m_debugger;
1817 TreeDelegateSP m_delegate_sp;
1818 TreeItem m_root;
1819 TreeItem *m_selected_item;
1820 int m_num_rows;
1821 int m_selected_row_idx;
1822 int m_first_visible_row;
1823 int m_min_x;
1824 int m_min_y;
1825 int m_max_x;
1826 int m_max_y;
1827 };
1828
1829 class FrameTreeDelegate : public TreeDelegate {
1830 public:
FrameTreeDelegate()1831 FrameTreeDelegate() : TreeDelegate() {
1832 FormatEntity::Parse(
1833 "frame #${frame.index}: {${function.name}${function.pc-offset}}}",
1834 m_format);
1835 }
1836
1837 ~FrameTreeDelegate() override = default;
1838
TreeDelegateDrawTreeItem(TreeItem & item,Window & window)1839 void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override {
1840 Thread *thread = (Thread *)item.GetUserData();
1841 if (thread) {
1842 const uint64_t frame_idx = item.GetIdentifier();
1843 StackFrameSP frame_sp = thread->GetStackFrameAtIndex(frame_idx);
1844 if (frame_sp) {
1845 StreamString strm;
1846 const SymbolContext &sc =
1847 frame_sp->GetSymbolContext(eSymbolContextEverything);
1848 ExecutionContext exe_ctx(frame_sp);
1849 if (FormatEntity::Format(m_format, strm, &sc, &exe_ctx, nullptr,
1850 nullptr, false, false)) {
1851 int right_pad = 1;
1852 window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad);
1853 }
1854 }
1855 }
1856 }
1857
TreeDelegateGenerateChildren(TreeItem & item)1858 void TreeDelegateGenerateChildren(TreeItem &item) override {
1859 // No children for frames yet...
1860 }
1861
TreeDelegateItemSelected(TreeItem & item)1862 bool TreeDelegateItemSelected(TreeItem &item) override {
1863 Thread *thread = (Thread *)item.GetUserData();
1864 if (thread) {
1865 thread->GetProcess()->GetThreadList().SetSelectedThreadByID(
1866 thread->GetID());
1867 const uint64_t frame_idx = item.GetIdentifier();
1868 thread->SetSelectedFrameByIndex(frame_idx);
1869 return true;
1870 }
1871 return false;
1872 }
1873
1874 protected:
1875 FormatEntity::Entry m_format;
1876 };
1877
1878 class ThreadTreeDelegate : public TreeDelegate {
1879 public:
ThreadTreeDelegate(Debugger & debugger)1880 ThreadTreeDelegate(Debugger &debugger)
1881 : TreeDelegate(), m_debugger(debugger), m_tid(LLDB_INVALID_THREAD_ID),
1882 m_stop_id(UINT32_MAX) {
1883 FormatEntity::Parse("thread #${thread.index}: tid = ${thread.id}{, stop "
1884 "reason = ${thread.stop-reason}}",
1885 m_format);
1886 }
1887
1888 ~ThreadTreeDelegate() override = default;
1889
GetProcess()1890 ProcessSP GetProcess() {
1891 return m_debugger.GetCommandInterpreter()
1892 .GetExecutionContext()
1893 .GetProcessSP();
1894 }
1895
GetThread(const TreeItem & item)1896 ThreadSP GetThread(const TreeItem &item) {
1897 ProcessSP process_sp = GetProcess();
1898 if (process_sp)
1899 return process_sp->GetThreadList().FindThreadByID(item.GetIdentifier());
1900 return ThreadSP();
1901 }
1902
TreeDelegateDrawTreeItem(TreeItem & item,Window & window)1903 void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override {
1904 ThreadSP thread_sp = GetThread(item);
1905 if (thread_sp) {
1906 StreamString strm;
1907 ExecutionContext exe_ctx(thread_sp);
1908 if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr,
1909 nullptr, false, false)) {
1910 int right_pad = 1;
1911 window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad);
1912 }
1913 }
1914 }
1915
TreeDelegateGenerateChildren(TreeItem & item)1916 void TreeDelegateGenerateChildren(TreeItem &item) override {
1917 ProcessSP process_sp = GetProcess();
1918 if (process_sp && process_sp->IsAlive()) {
1919 StateType state = process_sp->GetState();
1920 if (StateIsStoppedState(state, true)) {
1921 ThreadSP thread_sp = GetThread(item);
1922 if (thread_sp) {
1923 if (m_stop_id == process_sp->GetStopID() &&
1924 thread_sp->GetID() == m_tid)
1925 return; // Children are already up to date
1926 if (!m_frame_delegate_sp) {
1927 // Always expand the thread item the first time we show it
1928 m_frame_delegate_sp = std::make_shared<FrameTreeDelegate>();
1929 }
1930
1931 m_stop_id = process_sp->GetStopID();
1932 m_tid = thread_sp->GetID();
1933
1934 TreeItem t(&item, *m_frame_delegate_sp, false);
1935 size_t num_frames = thread_sp->GetStackFrameCount();
1936 item.Resize(num_frames, t);
1937 for (size_t i = 0; i < num_frames; ++i) {
1938 item[i].SetUserData(thread_sp.get());
1939 item[i].SetIdentifier(i);
1940 }
1941 }
1942 return;
1943 }
1944 }
1945 item.ClearChildren();
1946 }
1947
TreeDelegateItemSelected(TreeItem & item)1948 bool TreeDelegateItemSelected(TreeItem &item) override {
1949 ProcessSP process_sp = GetProcess();
1950 if (process_sp && process_sp->IsAlive()) {
1951 StateType state = process_sp->GetState();
1952 if (StateIsStoppedState(state, true)) {
1953 ThreadSP thread_sp = GetThread(item);
1954 if (thread_sp) {
1955 ThreadList &thread_list = thread_sp->GetProcess()->GetThreadList();
1956 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1957 ThreadSP selected_thread_sp = thread_list.GetSelectedThread();
1958 if (selected_thread_sp->GetID() != thread_sp->GetID()) {
1959 thread_list.SetSelectedThreadByID(thread_sp->GetID());
1960 return true;
1961 }
1962 }
1963 }
1964 }
1965 return false;
1966 }
1967
1968 protected:
1969 Debugger &m_debugger;
1970 std::shared_ptr<FrameTreeDelegate> m_frame_delegate_sp;
1971 lldb::user_id_t m_tid;
1972 uint32_t m_stop_id;
1973 FormatEntity::Entry m_format;
1974 };
1975
1976 class ThreadsTreeDelegate : public TreeDelegate {
1977 public:
ThreadsTreeDelegate(Debugger & debugger)1978 ThreadsTreeDelegate(Debugger &debugger)
1979 : TreeDelegate(), m_thread_delegate_sp(), m_debugger(debugger),
1980 m_stop_id(UINT32_MAX) {
1981 FormatEntity::Parse("process ${process.id}{, name = ${process.name}}",
1982 m_format);
1983 }
1984
1985 ~ThreadsTreeDelegate() override = default;
1986
GetProcess()1987 ProcessSP GetProcess() {
1988 return m_debugger.GetCommandInterpreter()
1989 .GetExecutionContext()
1990 .GetProcessSP();
1991 }
1992
TreeDelegateDrawTreeItem(TreeItem & item,Window & window)1993 void TreeDelegateDrawTreeItem(TreeItem &item, Window &window) override {
1994 ProcessSP process_sp = GetProcess();
1995 if (process_sp && process_sp->IsAlive()) {
1996 StreamString strm;
1997 ExecutionContext exe_ctx(process_sp);
1998 if (FormatEntity::Format(m_format, strm, nullptr, &exe_ctx, nullptr,
1999 nullptr, false, false)) {
2000 int right_pad = 1;
2001 window.PutCStringTruncated(strm.GetString().str().c_str(), right_pad);
2002 }
2003 }
2004 }
2005
TreeDelegateGenerateChildren(TreeItem & item)2006 void TreeDelegateGenerateChildren(TreeItem &item) override {
2007 ProcessSP process_sp = GetProcess();
2008 if (process_sp && process_sp->IsAlive()) {
2009 StateType state = process_sp->GetState();
2010 if (StateIsStoppedState(state, true)) {
2011 const uint32_t stop_id = process_sp->GetStopID();
2012 if (m_stop_id == stop_id)
2013 return; // Children are already up to date
2014
2015 m_stop_id = stop_id;
2016
2017 if (!m_thread_delegate_sp) {
2018 // Always expand the thread item the first time we show it
2019 // item.Expand();
2020 m_thread_delegate_sp =
2021 std::make_shared<ThreadTreeDelegate>(m_debugger);
2022 }
2023
2024 TreeItem t(&item, *m_thread_delegate_sp, false);
2025 ThreadList &threads = process_sp->GetThreadList();
2026 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
2027 size_t num_threads = threads.GetSize();
2028 item.Resize(num_threads, t);
2029 for (size_t i = 0; i < num_threads; ++i) {
2030 item[i].SetIdentifier(threads.GetThreadAtIndex(i)->GetID());
2031 item[i].SetMightHaveChildren(true);
2032 }
2033 return;
2034 }
2035 }
2036 item.ClearChildren();
2037 }
2038
TreeDelegateItemSelected(TreeItem & item)2039 bool TreeDelegateItemSelected(TreeItem &item) override { return false; }
2040
2041 protected:
2042 std::shared_ptr<ThreadTreeDelegate> m_thread_delegate_sp;
2043 Debugger &m_debugger;
2044 uint32_t m_stop_id;
2045 FormatEntity::Entry m_format;
2046 };
2047
2048 class ValueObjectListDelegate : public WindowDelegate {
2049 public:
ValueObjectListDelegate()2050 ValueObjectListDelegate()
2051 : m_rows(), m_selected_row(nullptr), m_selected_row_idx(0),
2052 m_first_visible_row(0), m_num_rows(0), m_max_x(0), m_max_y(0) {}
2053
ValueObjectListDelegate(ValueObjectList & valobj_list)2054 ValueObjectListDelegate(ValueObjectList &valobj_list)
2055 : m_rows(), m_selected_row(nullptr), m_selected_row_idx(0),
2056 m_first_visible_row(0), m_num_rows(0), m_max_x(0), m_max_y(0) {
2057 SetValues(valobj_list);
2058 }
2059
2060 ~ValueObjectListDelegate() override = default;
2061
SetValues(ValueObjectList & valobj_list)2062 void SetValues(ValueObjectList &valobj_list) {
2063 m_selected_row = nullptr;
2064 m_selected_row_idx = 0;
2065 m_first_visible_row = 0;
2066 m_num_rows = 0;
2067 m_rows.clear();
2068 for (auto &valobj_sp : valobj_list.GetObjects())
2069 m_rows.push_back(Row(valobj_sp, nullptr));
2070 }
2071
WindowDelegateDraw(Window & window,bool force)2072 bool WindowDelegateDraw(Window &window, bool force) override {
2073 m_num_rows = 0;
2074 m_min_x = 2;
2075 m_min_y = 1;
2076 m_max_x = window.GetWidth() - 1;
2077 m_max_y = window.GetHeight() - 1;
2078
2079 window.Erase();
2080 window.DrawTitleBox(window.GetName());
2081
2082 const int num_visible_rows = NumVisibleRows();
2083 const int num_rows = CalculateTotalNumberRows(m_rows);
2084
2085 // If we unexpanded while having something selected our total number of
2086 // rows is less than the num visible rows, then make sure we show all the
2087 // rows by setting the first visible row accordingly.
2088 if (m_first_visible_row > 0 && num_rows < num_visible_rows)
2089 m_first_visible_row = 0;
2090
2091 // Make sure the selected row is always visible
2092 if (m_selected_row_idx < m_first_visible_row)
2093 m_first_visible_row = m_selected_row_idx;
2094 else if (m_first_visible_row + num_visible_rows <= m_selected_row_idx)
2095 m_first_visible_row = m_selected_row_idx - num_visible_rows + 1;
2096
2097 DisplayRows(window, m_rows, g_options);
2098
2099 // Get the selected row
2100 m_selected_row = GetRowForRowIndex(m_selected_row_idx);
2101 // Keep the cursor on the selected row so the highlight and the cursor are
2102 // always on the same line
2103 if (m_selected_row)
2104 window.MoveCursor(m_selected_row->x, m_selected_row->y);
2105
2106 return true; // Drawing handled
2107 }
2108
WindowDelegateGetKeyHelp()2109 KeyHelp *WindowDelegateGetKeyHelp() override {
2110 static curses::KeyHelp g_source_view_key_help[] = {
2111 {KEY_UP, "Select previous item"},
2112 {KEY_DOWN, "Select next item"},
2113 {KEY_RIGHT, "Expand selected item"},
2114 {KEY_LEFT, "Unexpand selected item or select parent if not expanded"},
2115 {KEY_PPAGE, "Page up"},
2116 {KEY_NPAGE, "Page down"},
2117 {'A', "Format as annotated address"},
2118 {'b', "Format as binary"},
2119 {'B', "Format as hex bytes with ASCII"},
2120 {'c', "Format as character"},
2121 {'d', "Format as a signed integer"},
2122 {'D', "Format selected value using the default format for the type"},
2123 {'f', "Format as float"},
2124 {'h', "Show help dialog"},
2125 {'i', "Format as instructions"},
2126 {'o', "Format as octal"},
2127 {'p', "Format as pointer"},
2128 {'s', "Format as C string"},
2129 {'t', "Toggle showing/hiding type names"},
2130 {'u', "Format as an unsigned integer"},
2131 {'x', "Format as hex"},
2132 {'X', "Format as uppercase hex"},
2133 {' ', "Toggle item expansion"},
2134 {',', "Page up"},
2135 {'.', "Page down"},
2136 {'\0', nullptr}};
2137 return g_source_view_key_help;
2138 }
2139
WindowDelegateHandleChar(Window & window,int c)2140 HandleCharResult WindowDelegateHandleChar(Window &window, int c) override {
2141 switch (c) {
2142 case 'x':
2143 case 'X':
2144 case 'o':
2145 case 's':
2146 case 'u':
2147 case 'd':
2148 case 'D':
2149 case 'i':
2150 case 'A':
2151 case 'p':
2152 case 'c':
2153 case 'b':
2154 case 'B':
2155 case 'f':
2156 // Change the format for the currently selected item
2157 if (m_selected_row) {
2158 auto valobj_sp = m_selected_row->value.GetSP();
2159 if (valobj_sp)
2160 valobj_sp->SetFormat(FormatForChar(c));
2161 }
2162 return eKeyHandled;
2163
2164 case 't':
2165 // Toggle showing type names
2166 g_options.show_types = !g_options.show_types;
2167 return eKeyHandled;
2168
2169 case ',':
2170 case KEY_PPAGE:
2171 // Page up key
2172 if (m_first_visible_row > 0) {
2173 if (static_cast<int>(m_first_visible_row) > m_max_y)
2174 m_first_visible_row -= m_max_y;
2175 else
2176 m_first_visible_row = 0;
2177 m_selected_row_idx = m_first_visible_row;
2178 }
2179 return eKeyHandled;
2180
2181 case '.':
2182 case KEY_NPAGE:
2183 // Page down key
2184 if (m_num_rows > static_cast<size_t>(m_max_y)) {
2185 if (m_first_visible_row + m_max_y < m_num_rows) {
2186 m_first_visible_row += m_max_y;
2187 m_selected_row_idx = m_first_visible_row;
2188 }
2189 }
2190 return eKeyHandled;
2191
2192 case KEY_UP:
2193 if (m_selected_row_idx > 0)
2194 --m_selected_row_idx;
2195 return eKeyHandled;
2196
2197 case KEY_DOWN:
2198 if (m_selected_row_idx + 1 < m_num_rows)
2199 ++m_selected_row_idx;
2200 return eKeyHandled;
2201
2202 case KEY_RIGHT:
2203 if (m_selected_row) {
2204 if (!m_selected_row->expanded)
2205 m_selected_row->Expand();
2206 }
2207 return eKeyHandled;
2208
2209 case KEY_LEFT:
2210 if (m_selected_row) {
2211 if (m_selected_row->expanded)
2212 m_selected_row->Unexpand();
2213 else if (m_selected_row->parent)
2214 m_selected_row_idx = m_selected_row->parent->row_idx;
2215 }
2216 return eKeyHandled;
2217
2218 case ' ':
2219 // Toggle expansion state when SPACE is pressed
2220 if (m_selected_row) {
2221 if (m_selected_row->expanded)
2222 m_selected_row->Unexpand();
2223 else
2224 m_selected_row->Expand();
2225 }
2226 return eKeyHandled;
2227
2228 case 'h':
2229 window.CreateHelpSubwindow();
2230 return eKeyHandled;
2231
2232 default:
2233 break;
2234 }
2235 return eKeyNotHandled;
2236 }
2237
2238 protected:
2239 std::vector<Row> m_rows;
2240 Row *m_selected_row;
2241 uint32_t m_selected_row_idx;
2242 uint32_t m_first_visible_row;
2243 uint32_t m_num_rows;
2244 int m_min_x;
2245 int m_min_y;
2246 int m_max_x;
2247 int m_max_y;
2248
FormatForChar(int c)2249 static Format FormatForChar(int c) {
2250 switch (c) {
2251 case 'x':
2252 return eFormatHex;
2253 case 'X':
2254 return eFormatHexUppercase;
2255 case 'o':
2256 return eFormatOctal;
2257 case 's':
2258 return eFormatCString;
2259 case 'u':
2260 return eFormatUnsigned;
2261 case 'd':
2262 return eFormatDecimal;
2263 case 'D':
2264 return eFormatDefault;
2265 case 'i':
2266 return eFormatInstruction;
2267 case 'A':
2268 return eFormatAddressInfo;
2269 case 'p':
2270 return eFormatPointer;
2271 case 'c':
2272 return eFormatChar;
2273 case 'b':
2274 return eFormatBinary;
2275 case 'B':
2276 return eFormatBytesWithASCII;
2277 case 'f':
2278 return eFormatFloat;
2279 }
2280 return eFormatDefault;
2281 }
2282
DisplayRowObject(Window & window,Row & row,DisplayOptions & options,bool highlight,bool last_child)2283 bool DisplayRowObject(Window &window, Row &row, DisplayOptions &options,
2284 bool highlight, bool last_child) {
2285 ValueObject *valobj = row.value.GetSP().get();
2286
2287 if (valobj == nullptr)
2288 return false;
2289
2290 const char *type_name =
2291 options.show_types ? valobj->GetTypeName().GetCString() : nullptr;
2292 const char *name = valobj->GetName().GetCString();
2293 const char *value = valobj->GetValueAsCString();
2294 const char *summary = valobj->GetSummaryAsCString();
2295
2296 window.MoveCursor(row.x, row.y);
2297
2298 row.DrawTree(window);
2299
2300 if (highlight)
2301 window.AttributeOn(A_REVERSE);
2302
2303 if (type_name && type_name[0])
2304 window.Printf("(%s) ", type_name);
2305
2306 if (name && name[0])
2307 window.PutCString(name);
2308
2309 attr_t changd_attr = 0;
2310 if (valobj->GetValueDidChange())
2311 changd_attr = COLOR_PAIR(5) | A_BOLD;
2312
2313 if (value && value[0]) {
2314 window.PutCString(" = ");
2315 if (changd_attr)
2316 window.AttributeOn(changd_attr);
2317 window.PutCString(value);
2318 if (changd_attr)
2319 window.AttributeOff(changd_attr);
2320 }
2321
2322 if (summary && summary[0]) {
2323 window.PutChar(' ');
2324 if (changd_attr)
2325 window.AttributeOn(changd_attr);
2326 window.PutCString(summary);
2327 if (changd_attr)
2328 window.AttributeOff(changd_attr);
2329 }
2330
2331 if (highlight)
2332 window.AttributeOff(A_REVERSE);
2333
2334 return true;
2335 }
2336
DisplayRows(Window & window,std::vector<Row> & rows,DisplayOptions & options)2337 void DisplayRows(Window &window, std::vector<Row> &rows,
2338 DisplayOptions &options) {
2339 // > 0x25B7
2340 // \/ 0x25BD
2341
2342 bool window_is_active = window.IsActive();
2343 for (auto &row : rows) {
2344 const bool last_child = row.parent && &rows[rows.size() - 1] == &row;
2345 // Save the row index in each Row structure
2346 row.row_idx = m_num_rows;
2347 if ((m_num_rows >= m_first_visible_row) &&
2348 ((m_num_rows - m_first_visible_row) <
2349 static_cast<size_t>(NumVisibleRows()))) {
2350 row.x = m_min_x;
2351 row.y = m_num_rows - m_first_visible_row + 1;
2352 if (DisplayRowObject(window, row, options,
2353 window_is_active &&
2354 m_num_rows == m_selected_row_idx,
2355 last_child)) {
2356 ++m_num_rows;
2357 } else {
2358 row.x = 0;
2359 row.y = 0;
2360 }
2361 } else {
2362 row.x = 0;
2363 row.y = 0;
2364 ++m_num_rows;
2365 }
2366
2367 auto &children = row.GetChildren();
2368 if (row.expanded && !children.empty()) {
2369 DisplayRows(window, children, options);
2370 }
2371 }
2372 }
2373
CalculateTotalNumberRows(std::vector<Row> & rows)2374 int CalculateTotalNumberRows(std::vector<Row> &rows) {
2375 int row_count = 0;
2376 for (auto &row : rows) {
2377 ++row_count;
2378 if (row.expanded)
2379 row_count += CalculateTotalNumberRows(row.GetChildren());
2380 }
2381 return row_count;
2382 }
2383
GetRowForRowIndexImpl(std::vector<Row> & rows,size_t & row_index)2384 static Row *GetRowForRowIndexImpl(std::vector<Row> &rows, size_t &row_index) {
2385 for (auto &row : rows) {
2386 if (row_index == 0)
2387 return &row;
2388 else {
2389 --row_index;
2390 auto &children = row.GetChildren();
2391 if (row.expanded && !children.empty()) {
2392 Row *result = GetRowForRowIndexImpl(children, row_index);
2393 if (result)
2394 return result;
2395 }
2396 }
2397 }
2398 return nullptr;
2399 }
2400
GetRowForRowIndex(size_t row_index)2401 Row *GetRowForRowIndex(size_t row_index) {
2402 return GetRowForRowIndexImpl(m_rows, row_index);
2403 }
2404
NumVisibleRows() const2405 int NumVisibleRows() const { return m_max_y - m_min_y; }
2406
2407 static DisplayOptions g_options;
2408 };
2409
2410 class FrameVariablesWindowDelegate : public ValueObjectListDelegate {
2411 public:
FrameVariablesWindowDelegate(Debugger & debugger)2412 FrameVariablesWindowDelegate(Debugger &debugger)
2413 : ValueObjectListDelegate(), m_debugger(debugger),
2414 m_frame_block(nullptr) {}
2415
2416 ~FrameVariablesWindowDelegate() override = default;
2417
WindowDelegateGetHelpText()2418 const char *WindowDelegateGetHelpText() override {
2419 return "Frame variable window keyboard shortcuts:";
2420 }
2421
WindowDelegateDraw(Window & window,bool force)2422 bool WindowDelegateDraw(Window &window, bool force) override {
2423 ExecutionContext exe_ctx(
2424 m_debugger.GetCommandInterpreter().GetExecutionContext());
2425 Process *process = exe_ctx.GetProcessPtr();
2426 Block *frame_block = nullptr;
2427 StackFrame *frame = nullptr;
2428
2429 if (process) {
2430 StateType state = process->GetState();
2431 if (StateIsStoppedState(state, true)) {
2432 frame = exe_ctx.GetFramePtr();
2433 if (frame)
2434 frame_block = frame->GetFrameBlock();
2435 } else if (StateIsRunningState(state)) {
2436 return true; // Don't do any updating when we are running
2437 }
2438 }
2439
2440 ValueObjectList local_values;
2441 if (frame_block) {
2442 // Only update the variables if they have changed
2443 if (m_frame_block != frame_block) {
2444 m_frame_block = frame_block;
2445
2446 VariableList *locals = frame->GetVariableList(true);
2447 if (locals) {
2448 const DynamicValueType use_dynamic = eDynamicDontRunTarget;
2449 for (const VariableSP &local_sp : *locals) {
2450 ValueObjectSP value_sp =
2451 frame->GetValueObjectForFrameVariable(local_sp, use_dynamic);
2452 if (value_sp) {
2453 ValueObjectSP synthetic_value_sp = value_sp->GetSyntheticValue();
2454 if (synthetic_value_sp)
2455 local_values.Append(synthetic_value_sp);
2456 else
2457 local_values.Append(value_sp);
2458 }
2459 }
2460 // Update the values
2461 SetValues(local_values);
2462 }
2463 }
2464 } else {
2465 m_frame_block = nullptr;
2466 // Update the values with an empty list if there is no frame
2467 SetValues(local_values);
2468 }
2469
2470 return ValueObjectListDelegate::WindowDelegateDraw(window, force);
2471 }
2472
2473 protected:
2474 Debugger &m_debugger;
2475 Block *m_frame_block;
2476 };
2477
2478 class RegistersWindowDelegate : public ValueObjectListDelegate {
2479 public:
RegistersWindowDelegate(Debugger & debugger)2480 RegistersWindowDelegate(Debugger &debugger)
2481 : ValueObjectListDelegate(), m_debugger(debugger) {}
2482
2483 ~RegistersWindowDelegate() override = default;
2484
WindowDelegateGetHelpText()2485 const char *WindowDelegateGetHelpText() override {
2486 return "Register window keyboard shortcuts:";
2487 }
2488
WindowDelegateDraw(Window & window,bool force)2489 bool WindowDelegateDraw(Window &window, bool force) override {
2490 ExecutionContext exe_ctx(
2491 m_debugger.GetCommandInterpreter().GetExecutionContext());
2492 StackFrame *frame = exe_ctx.GetFramePtr();
2493
2494 ValueObjectList value_list;
2495 if (frame) {
2496 if (frame->GetStackID() != m_stack_id) {
2497 m_stack_id = frame->GetStackID();
2498 RegisterContextSP reg_ctx(frame->GetRegisterContext());
2499 if (reg_ctx) {
2500 const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
2501 for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
2502 value_list.Append(
2503 ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx));
2504 }
2505 }
2506 SetValues(value_list);
2507 }
2508 } else {
2509 Process *process = exe_ctx.GetProcessPtr();
2510 if (process && process->IsAlive())
2511 return true; // Don't do any updating if we are running
2512 else {
2513 // Update the values with an empty list if there is no process or the
2514 // process isn't alive anymore
2515 SetValues(value_list);
2516 }
2517 }
2518 return ValueObjectListDelegate::WindowDelegateDraw(window, force);
2519 }
2520
2521 protected:
2522 Debugger &m_debugger;
2523 StackID m_stack_id;
2524 };
2525
CursesKeyToCString(int ch)2526 static const char *CursesKeyToCString(int ch) {
2527 static char g_desc[32];
2528 if (ch >= KEY_F0 && ch < KEY_F0 + 64) {
2529 snprintf(g_desc, sizeof(g_desc), "F%u", ch - KEY_F0);
2530 return g_desc;
2531 }
2532 switch (ch) {
2533 case KEY_DOWN:
2534 return "down";
2535 case KEY_UP:
2536 return "up";
2537 case KEY_LEFT:
2538 return "left";
2539 case KEY_RIGHT:
2540 return "right";
2541 case KEY_HOME:
2542 return "home";
2543 case KEY_BACKSPACE:
2544 return "backspace";
2545 case KEY_DL:
2546 return "delete-line";
2547 case KEY_IL:
2548 return "insert-line";
2549 case KEY_DC:
2550 return "delete-char";
2551 case KEY_IC:
2552 return "insert-char";
2553 case KEY_CLEAR:
2554 return "clear";
2555 case KEY_EOS:
2556 return "clear-to-eos";
2557 case KEY_EOL:
2558 return "clear-to-eol";
2559 case KEY_SF:
2560 return "scroll-forward";
2561 case KEY_SR:
2562 return "scroll-backward";
2563 case KEY_NPAGE:
2564 return "page-down";
2565 case KEY_PPAGE:
2566 return "page-up";
2567 case KEY_STAB:
2568 return "set-tab";
2569 case KEY_CTAB:
2570 return "clear-tab";
2571 case KEY_CATAB:
2572 return "clear-all-tabs";
2573 case KEY_ENTER:
2574 return "enter";
2575 case KEY_PRINT:
2576 return "print";
2577 case KEY_LL:
2578 return "lower-left key";
2579 case KEY_A1:
2580 return "upper left of keypad";
2581 case KEY_A3:
2582 return "upper right of keypad";
2583 case KEY_B2:
2584 return "center of keypad";
2585 case KEY_C1:
2586 return "lower left of keypad";
2587 case KEY_C3:
2588 return "lower right of keypad";
2589 case KEY_BTAB:
2590 return "back-tab key";
2591 case KEY_BEG:
2592 return "begin key";
2593 case KEY_CANCEL:
2594 return "cancel key";
2595 case KEY_CLOSE:
2596 return "close key";
2597 case KEY_COMMAND:
2598 return "command key";
2599 case KEY_COPY:
2600 return "copy key";
2601 case KEY_CREATE:
2602 return "create key";
2603 case KEY_END:
2604 return "end key";
2605 case KEY_EXIT:
2606 return "exit key";
2607 case KEY_FIND:
2608 return "find key";
2609 case KEY_HELP:
2610 return "help key";
2611 case KEY_MARK:
2612 return "mark key";
2613 case KEY_MESSAGE:
2614 return "message key";
2615 case KEY_MOVE:
2616 return "move key";
2617 case KEY_NEXT:
2618 return "next key";
2619 case KEY_OPEN:
2620 return "open key";
2621 case KEY_OPTIONS:
2622 return "options key";
2623 case KEY_PREVIOUS:
2624 return "previous key";
2625 case KEY_REDO:
2626 return "redo key";
2627 case KEY_REFERENCE:
2628 return "reference key";
2629 case KEY_REFRESH:
2630 return "refresh key";
2631 case KEY_REPLACE:
2632 return "replace key";
2633 case KEY_RESTART:
2634 return "restart key";
2635 case KEY_RESUME:
2636 return "resume key";
2637 case KEY_SAVE:
2638 return "save key";
2639 case KEY_SBEG:
2640 return "shifted begin key";
2641 case KEY_SCANCEL:
2642 return "shifted cancel key";
2643 case KEY_SCOMMAND:
2644 return "shifted command key";
2645 case KEY_SCOPY:
2646 return "shifted copy key";
2647 case KEY_SCREATE:
2648 return "shifted create key";
2649 case KEY_SDC:
2650 return "shifted delete-character key";
2651 case KEY_SDL:
2652 return "shifted delete-line key";
2653 case KEY_SELECT:
2654 return "select key";
2655 case KEY_SEND:
2656 return "shifted end key";
2657 case KEY_SEOL:
2658 return "shifted clear-to-end-of-line key";
2659 case KEY_SEXIT:
2660 return "shifted exit key";
2661 case KEY_SFIND:
2662 return "shifted find key";
2663 case KEY_SHELP:
2664 return "shifted help key";
2665 case KEY_SHOME:
2666 return "shifted home key";
2667 case KEY_SIC:
2668 return "shifted insert-character key";
2669 case KEY_SLEFT:
2670 return "shifted left-arrow key";
2671 case KEY_SMESSAGE:
2672 return "shifted message key";
2673 case KEY_SMOVE:
2674 return "shifted move key";
2675 case KEY_SNEXT:
2676 return "shifted next key";
2677 case KEY_SOPTIONS:
2678 return "shifted options key";
2679 case KEY_SPREVIOUS:
2680 return "shifted previous key";
2681 case KEY_SPRINT:
2682 return "shifted print key";
2683 case KEY_SREDO:
2684 return "shifted redo key";
2685 case KEY_SREPLACE:
2686 return "shifted replace key";
2687 case KEY_SRIGHT:
2688 return "shifted right-arrow key";
2689 case KEY_SRSUME:
2690 return "shifted resume key";
2691 case KEY_SSAVE:
2692 return "shifted save key";
2693 case KEY_SSUSPEND:
2694 return "shifted suspend key";
2695 case KEY_SUNDO:
2696 return "shifted undo key";
2697 case KEY_SUSPEND:
2698 return "suspend key";
2699 case KEY_UNDO:
2700 return "undo key";
2701 case KEY_MOUSE:
2702 return "Mouse event has occurred";
2703 case KEY_RESIZE:
2704 return "Terminal resize event";
2705 #ifdef KEY_EVENT
2706 case KEY_EVENT:
2707 return "We were interrupted by an event";
2708 #endif
2709 case KEY_RETURN:
2710 return "return";
2711 case ' ':
2712 return "space";
2713 case '\t':
2714 return "tab";
2715 case KEY_ESCAPE:
2716 return "escape";
2717 default:
2718 if (llvm::isPrint(ch))
2719 snprintf(g_desc, sizeof(g_desc), "%c", ch);
2720 else
2721 snprintf(g_desc, sizeof(g_desc), "\\x%2.2x", ch);
2722 return g_desc;
2723 }
2724 return nullptr;
2725 }
2726
HelpDialogDelegate(const char * text,KeyHelp * key_help_array)2727 HelpDialogDelegate::HelpDialogDelegate(const char *text,
2728 KeyHelp *key_help_array)
2729 : m_text(), m_first_visible_line(0) {
2730 if (text && text[0]) {
2731 m_text.SplitIntoLines(text);
2732 m_text.AppendString("");
2733 }
2734 if (key_help_array) {
2735 for (KeyHelp *key = key_help_array; key->ch; ++key) {
2736 StreamString key_description;
2737 key_description.Printf("%10s - %s", CursesKeyToCString(key->ch),
2738 key->description);
2739 m_text.AppendString(key_description.GetString());
2740 }
2741 }
2742 }
2743
2744 HelpDialogDelegate::~HelpDialogDelegate() = default;
2745
WindowDelegateDraw(Window & window,bool force)2746 bool HelpDialogDelegate::WindowDelegateDraw(Window &window, bool force) {
2747 window.Erase();
2748 const int window_height = window.GetHeight();
2749 int x = 2;
2750 int y = 1;
2751 const int min_y = y;
2752 const int max_y = window_height - 1 - y;
2753 const size_t num_visible_lines = max_y - min_y + 1;
2754 const size_t num_lines = m_text.GetSize();
2755 const char *bottom_message;
2756 if (num_lines <= num_visible_lines)
2757 bottom_message = "Press any key to exit";
2758 else
2759 bottom_message = "Use arrows to scroll, any other key to exit";
2760 window.DrawTitleBox(window.GetName(), bottom_message);
2761 while (y <= max_y) {
2762 window.MoveCursor(x, y);
2763 window.PutCStringTruncated(
2764 m_text.GetStringAtIndex(m_first_visible_line + y - min_y), 1);
2765 ++y;
2766 }
2767 return true;
2768 }
2769
WindowDelegateHandleChar(Window & window,int key)2770 HandleCharResult HelpDialogDelegate::WindowDelegateHandleChar(Window &window,
2771 int key) {
2772 bool done = false;
2773 const size_t num_lines = m_text.GetSize();
2774 const size_t num_visible_lines = window.GetHeight() - 2;
2775
2776 if (num_lines <= num_visible_lines) {
2777 done = true;
2778 // If we have all lines visible and don't need scrolling, then any key
2779 // press will cause us to exit
2780 } else {
2781 switch (key) {
2782 case KEY_UP:
2783 if (m_first_visible_line > 0)
2784 --m_first_visible_line;
2785 break;
2786
2787 case KEY_DOWN:
2788 if (m_first_visible_line + num_visible_lines < num_lines)
2789 ++m_first_visible_line;
2790 break;
2791
2792 case KEY_PPAGE:
2793 case ',':
2794 if (m_first_visible_line > 0) {
2795 if (static_cast<size_t>(m_first_visible_line) >= num_visible_lines)
2796 m_first_visible_line -= num_visible_lines;
2797 else
2798 m_first_visible_line = 0;
2799 }
2800 break;
2801
2802 case KEY_NPAGE:
2803 case '.':
2804 if (m_first_visible_line + num_visible_lines < num_lines) {
2805 m_first_visible_line += num_visible_lines;
2806 if (static_cast<size_t>(m_first_visible_line) > num_lines)
2807 m_first_visible_line = num_lines - num_visible_lines;
2808 }
2809 break;
2810
2811 default:
2812 done = true;
2813 break;
2814 }
2815 }
2816 if (done)
2817 window.GetParent()->RemoveSubWindow(&window);
2818 return eKeyHandled;
2819 }
2820
2821 class ApplicationDelegate : public WindowDelegate, public MenuDelegate {
2822 public:
2823 enum {
2824 eMenuID_LLDB = 1,
2825 eMenuID_LLDBAbout,
2826 eMenuID_LLDBExit,
2827
2828 eMenuID_Target,
2829 eMenuID_TargetCreate,
2830 eMenuID_TargetDelete,
2831
2832 eMenuID_Process,
2833 eMenuID_ProcessAttach,
2834 eMenuID_ProcessDetach,
2835 eMenuID_ProcessLaunch,
2836 eMenuID_ProcessContinue,
2837 eMenuID_ProcessHalt,
2838 eMenuID_ProcessKill,
2839
2840 eMenuID_Thread,
2841 eMenuID_ThreadStepIn,
2842 eMenuID_ThreadStepOver,
2843 eMenuID_ThreadStepOut,
2844
2845 eMenuID_View,
2846 eMenuID_ViewBacktrace,
2847 eMenuID_ViewRegisters,
2848 eMenuID_ViewSource,
2849 eMenuID_ViewVariables,
2850
2851 eMenuID_Help,
2852 eMenuID_HelpGUIHelp
2853 };
2854
ApplicationDelegate(Application & app,Debugger & debugger)2855 ApplicationDelegate(Application &app, Debugger &debugger)
2856 : WindowDelegate(), MenuDelegate(), m_app(app), m_debugger(debugger) {}
2857
2858 ~ApplicationDelegate() override = default;
2859
WindowDelegateDraw(Window & window,bool force)2860 bool WindowDelegateDraw(Window &window, bool force) override {
2861 return false; // Drawing not handled, let standard window drawing happen
2862 }
2863
WindowDelegateHandleChar(Window & window,int key)2864 HandleCharResult WindowDelegateHandleChar(Window &window, int key) override {
2865 switch (key) {
2866 case '\t':
2867 window.SelectNextWindowAsActive();
2868 return eKeyHandled;
2869
2870 case 'h':
2871 window.CreateHelpSubwindow();
2872 return eKeyHandled;
2873
2874 case KEY_ESCAPE:
2875 return eQuitApplication;
2876
2877 default:
2878 break;
2879 }
2880 return eKeyNotHandled;
2881 }
2882
WindowDelegateGetHelpText()2883 const char *WindowDelegateGetHelpText() override {
2884 return "Welcome to the LLDB curses GUI.\n\n"
2885 "Press the TAB key to change the selected view.\n"
2886 "Each view has its own keyboard shortcuts, press 'h' to open a "
2887 "dialog to display them.\n\n"
2888 "Common key bindings for all views:";
2889 }
2890
WindowDelegateGetKeyHelp()2891 KeyHelp *WindowDelegateGetKeyHelp() override {
2892 static curses::KeyHelp g_source_view_key_help[] = {
2893 {'\t', "Select next view"},
2894 {'h', "Show help dialog with view specific key bindings"},
2895 {',', "Page up"},
2896 {'.', "Page down"},
2897 {KEY_UP, "Select previous"},
2898 {KEY_DOWN, "Select next"},
2899 {KEY_LEFT, "Unexpand or select parent"},
2900 {KEY_RIGHT, "Expand"},
2901 {KEY_PPAGE, "Page up"},
2902 {KEY_NPAGE, "Page down"},
2903 {'\0', nullptr}};
2904 return g_source_view_key_help;
2905 }
2906
MenuDelegateAction(Menu & menu)2907 MenuActionResult MenuDelegateAction(Menu &menu) override {
2908 switch (menu.GetIdentifier()) {
2909 case eMenuID_ThreadStepIn: {
2910 ExecutionContext exe_ctx =
2911 m_debugger.GetCommandInterpreter().GetExecutionContext();
2912 if (exe_ctx.HasThreadScope()) {
2913 Process *process = exe_ctx.GetProcessPtr();
2914 if (process && process->IsAlive() &&
2915 StateIsStoppedState(process->GetState(), true))
2916 exe_ctx.GetThreadRef().StepIn(true);
2917 }
2918 }
2919 return MenuActionResult::Handled;
2920
2921 case eMenuID_ThreadStepOut: {
2922 ExecutionContext exe_ctx =
2923 m_debugger.GetCommandInterpreter().GetExecutionContext();
2924 if (exe_ctx.HasThreadScope()) {
2925 Process *process = exe_ctx.GetProcessPtr();
2926 if (process && process->IsAlive() &&
2927 StateIsStoppedState(process->GetState(), true))
2928 exe_ctx.GetThreadRef().StepOut();
2929 }
2930 }
2931 return MenuActionResult::Handled;
2932
2933 case eMenuID_ThreadStepOver: {
2934 ExecutionContext exe_ctx =
2935 m_debugger.GetCommandInterpreter().GetExecutionContext();
2936 if (exe_ctx.HasThreadScope()) {
2937 Process *process = exe_ctx.GetProcessPtr();
2938 if (process && process->IsAlive() &&
2939 StateIsStoppedState(process->GetState(), true))
2940 exe_ctx.GetThreadRef().StepOver(true);
2941 }
2942 }
2943 return MenuActionResult::Handled;
2944
2945 case eMenuID_ProcessContinue: {
2946 ExecutionContext exe_ctx =
2947 m_debugger.GetCommandInterpreter().GetExecutionContext();
2948 if (exe_ctx.HasProcessScope()) {
2949 Process *process = exe_ctx.GetProcessPtr();
2950 if (process && process->IsAlive() &&
2951 StateIsStoppedState(process->GetState(), true))
2952 process->Resume();
2953 }
2954 }
2955 return MenuActionResult::Handled;
2956
2957 case eMenuID_ProcessKill: {
2958 ExecutionContext exe_ctx =
2959 m_debugger.GetCommandInterpreter().GetExecutionContext();
2960 if (exe_ctx.HasProcessScope()) {
2961 Process *process = exe_ctx.GetProcessPtr();
2962 if (process && process->IsAlive())
2963 process->Destroy(false);
2964 }
2965 }
2966 return MenuActionResult::Handled;
2967
2968 case eMenuID_ProcessHalt: {
2969 ExecutionContext exe_ctx =
2970 m_debugger.GetCommandInterpreter().GetExecutionContext();
2971 if (exe_ctx.HasProcessScope()) {
2972 Process *process = exe_ctx.GetProcessPtr();
2973 if (process && process->IsAlive())
2974 process->Halt();
2975 }
2976 }
2977 return MenuActionResult::Handled;
2978
2979 case eMenuID_ProcessDetach: {
2980 ExecutionContext exe_ctx =
2981 m_debugger.GetCommandInterpreter().GetExecutionContext();
2982 if (exe_ctx.HasProcessScope()) {
2983 Process *process = exe_ctx.GetProcessPtr();
2984 if (process && process->IsAlive())
2985 process->Detach(false);
2986 }
2987 }
2988 return MenuActionResult::Handled;
2989
2990 case eMenuID_Process: {
2991 // Populate the menu with all of the threads if the process is stopped
2992 // when the Process menu gets selected and is about to display its
2993 // submenu.
2994 Menus &submenus = menu.GetSubmenus();
2995 ExecutionContext exe_ctx =
2996 m_debugger.GetCommandInterpreter().GetExecutionContext();
2997 Process *process = exe_ctx.GetProcessPtr();
2998 if (process && process->IsAlive() &&
2999 StateIsStoppedState(process->GetState(), true)) {
3000 if (submenus.size() == 7)
3001 menu.AddSubmenu(MenuSP(new Menu(Menu::Type::Separator)));
3002 else if (submenus.size() > 8)
3003 submenus.erase(submenus.begin() + 8, submenus.end());
3004
3005 ThreadList &threads = process->GetThreadList();
3006 std::lock_guard<std::recursive_mutex> guard(threads.GetMutex());
3007 size_t num_threads = threads.GetSize();
3008 for (size_t i = 0; i < num_threads; ++i) {
3009 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
3010 char menu_char = '\0';
3011 if (i < 9)
3012 menu_char = '1' + i;
3013 StreamString thread_menu_title;
3014 thread_menu_title.Printf("Thread %u", thread_sp->GetIndexID());
3015 const char *thread_name = thread_sp->GetName();
3016 if (thread_name && thread_name[0])
3017 thread_menu_title.Printf(" %s", thread_name);
3018 else {
3019 const char *queue_name = thread_sp->GetQueueName();
3020 if (queue_name && queue_name[0])
3021 thread_menu_title.Printf(" %s", queue_name);
3022 }
3023 menu.AddSubmenu(
3024 MenuSP(new Menu(thread_menu_title.GetString().str().c_str(),
3025 nullptr, menu_char, thread_sp->GetID())));
3026 }
3027 } else if (submenus.size() > 7) {
3028 // Remove the separator and any other thread submenu items that were
3029 // previously added
3030 submenus.erase(submenus.begin() + 7, submenus.end());
3031 }
3032 // Since we are adding and removing items we need to recalculate the name
3033 // lengths
3034 menu.RecalculateNameLengths();
3035 }
3036 return MenuActionResult::Handled;
3037
3038 case eMenuID_ViewVariables: {
3039 WindowSP main_window_sp = m_app.GetMainWindow();
3040 WindowSP source_window_sp = main_window_sp->FindSubWindow("Source");
3041 WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables");
3042 WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers");
3043 const Rect source_bounds = source_window_sp->GetBounds();
3044
3045 if (variables_window_sp) {
3046 const Rect variables_bounds = variables_window_sp->GetBounds();
3047
3048 main_window_sp->RemoveSubWindow(variables_window_sp.get());
3049
3050 if (registers_window_sp) {
3051 // We have a registers window, so give all the area back to the
3052 // registers window
3053 Rect registers_bounds = variables_bounds;
3054 registers_bounds.size.width = source_bounds.size.width;
3055 registers_window_sp->SetBounds(registers_bounds);
3056 } else {
3057 // We have no registers window showing so give the bottom area back
3058 // to the source view
3059 source_window_sp->Resize(source_bounds.size.width,
3060 source_bounds.size.height +
3061 variables_bounds.size.height);
3062 }
3063 } else {
3064 Rect new_variables_rect;
3065 if (registers_window_sp) {
3066 // We have a registers window so split the area of the registers
3067 // window into two columns where the left hand side will be the
3068 // variables and the right hand side will be the registers
3069 const Rect variables_bounds = registers_window_sp->GetBounds();
3070 Rect new_registers_rect;
3071 variables_bounds.VerticalSplitPercentage(0.50, new_variables_rect,
3072 new_registers_rect);
3073 registers_window_sp->SetBounds(new_registers_rect);
3074 } else {
3075 // No variables window, grab the bottom part of the source window
3076 Rect new_source_rect;
3077 source_bounds.HorizontalSplitPercentage(0.70, new_source_rect,
3078 new_variables_rect);
3079 source_window_sp->SetBounds(new_source_rect);
3080 }
3081 WindowSP new_window_sp = main_window_sp->CreateSubWindow(
3082 "Variables", new_variables_rect, false);
3083 new_window_sp->SetDelegate(
3084 WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger)));
3085 }
3086 touchwin(stdscr);
3087 }
3088 return MenuActionResult::Handled;
3089
3090 case eMenuID_ViewRegisters: {
3091 WindowSP main_window_sp = m_app.GetMainWindow();
3092 WindowSP source_window_sp = main_window_sp->FindSubWindow("Source");
3093 WindowSP variables_window_sp = main_window_sp->FindSubWindow("Variables");
3094 WindowSP registers_window_sp = main_window_sp->FindSubWindow("Registers");
3095 const Rect source_bounds = source_window_sp->GetBounds();
3096
3097 if (registers_window_sp) {
3098 if (variables_window_sp) {
3099 const Rect variables_bounds = variables_window_sp->GetBounds();
3100
3101 // We have a variables window, so give all the area back to the
3102 // variables window
3103 variables_window_sp->Resize(variables_bounds.size.width +
3104 registers_window_sp->GetWidth(),
3105 variables_bounds.size.height);
3106 } else {
3107 // We have no variables window showing so give the bottom area back
3108 // to the source view
3109 source_window_sp->Resize(source_bounds.size.width,
3110 source_bounds.size.height +
3111 registers_window_sp->GetHeight());
3112 }
3113 main_window_sp->RemoveSubWindow(registers_window_sp.get());
3114 } else {
3115 Rect new_regs_rect;
3116 if (variables_window_sp) {
3117 // We have a variables window, split it into two columns where the
3118 // left hand side will be the variables and the right hand side will
3119 // be the registers
3120 const Rect variables_bounds = variables_window_sp->GetBounds();
3121 Rect new_vars_rect;
3122 variables_bounds.VerticalSplitPercentage(0.50, new_vars_rect,
3123 new_regs_rect);
3124 variables_window_sp->SetBounds(new_vars_rect);
3125 } else {
3126 // No registers window, grab the bottom part of the source window
3127 Rect new_source_rect;
3128 source_bounds.HorizontalSplitPercentage(0.70, new_source_rect,
3129 new_regs_rect);
3130 source_window_sp->SetBounds(new_source_rect);
3131 }
3132 WindowSP new_window_sp =
3133 main_window_sp->CreateSubWindow("Registers", new_regs_rect, false);
3134 new_window_sp->SetDelegate(
3135 WindowDelegateSP(new RegistersWindowDelegate(m_debugger)));
3136 }
3137 touchwin(stdscr);
3138 }
3139 return MenuActionResult::Handled;
3140
3141 case eMenuID_HelpGUIHelp:
3142 m_app.GetMainWindow()->CreateHelpSubwindow();
3143 return MenuActionResult::Handled;
3144
3145 default:
3146 break;
3147 }
3148
3149 return MenuActionResult::NotHandled;
3150 }
3151
3152 protected:
3153 Application &m_app;
3154 Debugger &m_debugger;
3155 };
3156
3157 class StatusBarWindowDelegate : public WindowDelegate {
3158 public:
StatusBarWindowDelegate(Debugger & debugger)3159 StatusBarWindowDelegate(Debugger &debugger) : m_debugger(debugger) {
3160 FormatEntity::Parse("Thread: ${thread.id%tid}", m_format);
3161 }
3162
3163 ~StatusBarWindowDelegate() override = default;
3164
WindowDelegateDraw(Window & window,bool force)3165 bool WindowDelegateDraw(Window &window, bool force) override {
3166 ExecutionContext exe_ctx =
3167 m_debugger.GetCommandInterpreter().GetExecutionContext();
3168 Process *process = exe_ctx.GetProcessPtr();
3169 Thread *thread = exe_ctx.GetThreadPtr();
3170 StackFrame *frame = exe_ctx.GetFramePtr();
3171 window.Erase();
3172 window.SetBackground(2);
3173 window.MoveCursor(0, 0);
3174 if (process) {
3175 const StateType state = process->GetState();
3176 window.Printf("Process: %5" PRIu64 " %10s", process->GetID(),
3177 StateAsCString(state));
3178
3179 if (StateIsStoppedState(state, true)) {
3180 StreamString strm;
3181 if (thread && FormatEntity::Format(m_format, strm, nullptr, &exe_ctx,
3182 nullptr, nullptr, false, false)) {
3183 window.MoveCursor(40, 0);
3184 window.PutCStringTruncated(strm.GetString().str().c_str(), 1);
3185 }
3186
3187 window.MoveCursor(60, 0);
3188 if (frame)
3189 window.Printf("Frame: %3u PC = 0x%16.16" PRIx64,
3190 frame->GetFrameIndex(),
3191 frame->GetFrameCodeAddress().GetOpcodeLoadAddress(
3192 exe_ctx.GetTargetPtr()));
3193 } else if (state == eStateExited) {
3194 const char *exit_desc = process->GetExitDescription();
3195 const int exit_status = process->GetExitStatus();
3196 if (exit_desc && exit_desc[0])
3197 window.Printf(" with status = %i (%s)", exit_status, exit_desc);
3198 else
3199 window.Printf(" with status = %i", exit_status);
3200 }
3201 }
3202 return true;
3203 }
3204
3205 protected:
3206 Debugger &m_debugger;
3207 FormatEntity::Entry m_format;
3208 };
3209
3210 class SourceFileWindowDelegate : public WindowDelegate {
3211 public:
SourceFileWindowDelegate(Debugger & debugger)3212 SourceFileWindowDelegate(Debugger &debugger)
3213 : WindowDelegate(), m_debugger(debugger), m_sc(), m_file_sp(),
3214 m_disassembly_scope(nullptr), m_disassembly_sp(), m_disassembly_range(),
3215 m_title(), m_line_width(4), m_selected_line(0), m_pc_line(0),
3216 m_stop_id(0), m_frame_idx(UINT32_MAX), m_first_visible_line(0),
3217 m_min_x(0), m_min_y(0), m_max_x(0), m_max_y(0) {}
3218
3219 ~SourceFileWindowDelegate() override = default;
3220
Update(const SymbolContext & sc)3221 void Update(const SymbolContext &sc) { m_sc = sc; }
3222
NumVisibleLines() const3223 uint32_t NumVisibleLines() const { return m_max_y - m_min_y; }
3224
WindowDelegateGetHelpText()3225 const char *WindowDelegateGetHelpText() override {
3226 return "Source/Disassembly window keyboard shortcuts:";
3227 }
3228
WindowDelegateGetKeyHelp()3229 KeyHelp *WindowDelegateGetKeyHelp() override {
3230 static curses::KeyHelp g_source_view_key_help[] = {
3231 {KEY_RETURN, "Run to selected line with one shot breakpoint"},
3232 {KEY_UP, "Select previous source line"},
3233 {KEY_DOWN, "Select next source line"},
3234 {KEY_PPAGE, "Page up"},
3235 {KEY_NPAGE, "Page down"},
3236 {'b', "Set breakpoint on selected source/disassembly line"},
3237 {'c', "Continue process"},
3238 {'d', "Detach and resume process"},
3239 {'D', "Detach with process suspended"},
3240 {'h', "Show help dialog"},
3241 {'k', "Kill process"},
3242 {'n', "Step over (source line)"},
3243 {'N', "Step over (single instruction)"},
3244 {'o', "Step out"},
3245 {'s', "Step in (source line)"},
3246 {'S', "Step in (single instruction)"},
3247 {',', "Page up"},
3248 {'.', "Page down"},
3249 {'\0', nullptr}};
3250 return g_source_view_key_help;
3251 }
3252
WindowDelegateDraw(Window & window,bool force)3253 bool WindowDelegateDraw(Window &window, bool force) override {
3254 ExecutionContext exe_ctx =
3255 m_debugger.GetCommandInterpreter().GetExecutionContext();
3256 Process *process = exe_ctx.GetProcessPtr();
3257 Thread *thread = nullptr;
3258
3259 bool update_location = false;
3260 if (process) {
3261 StateType state = process->GetState();
3262 if (StateIsStoppedState(state, true)) {
3263 // We are stopped, so it is ok to
3264 update_location = true;
3265 }
3266 }
3267
3268 m_min_x = 1;
3269 m_min_y = 2;
3270 m_max_x = window.GetMaxX() - 1;
3271 m_max_y = window.GetMaxY() - 1;
3272
3273 const uint32_t num_visible_lines = NumVisibleLines();
3274 StackFrameSP frame_sp;
3275 bool set_selected_line_to_pc = false;
3276
3277 if (update_location) {
3278 const bool process_alive = process ? process->IsAlive() : false;
3279 bool thread_changed = false;
3280 if (process_alive) {
3281 thread = exe_ctx.GetThreadPtr();
3282 if (thread) {
3283 frame_sp = thread->GetSelectedFrame();
3284 auto tid = thread->GetID();
3285 thread_changed = tid != m_tid;
3286 m_tid = tid;
3287 } else {
3288 if (m_tid != LLDB_INVALID_THREAD_ID) {
3289 thread_changed = true;
3290 m_tid = LLDB_INVALID_THREAD_ID;
3291 }
3292 }
3293 }
3294 const uint32_t stop_id = process ? process->GetStopID() : 0;
3295 const bool stop_id_changed = stop_id != m_stop_id;
3296 bool frame_changed = false;
3297 m_stop_id = stop_id;
3298 m_title.Clear();
3299 if (frame_sp) {
3300 m_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
3301 if (m_sc.module_sp) {
3302 m_title.Printf(
3303 "%s", m_sc.module_sp->GetFileSpec().GetFilename().GetCString());
3304 ConstString func_name = m_sc.GetFunctionName();
3305 if (func_name)
3306 m_title.Printf("`%s", func_name.GetCString());
3307 }
3308 const uint32_t frame_idx = frame_sp->GetFrameIndex();
3309 frame_changed = frame_idx != m_frame_idx;
3310 m_frame_idx = frame_idx;
3311 } else {
3312 m_sc.Clear(true);
3313 frame_changed = m_frame_idx != UINT32_MAX;
3314 m_frame_idx = UINT32_MAX;
3315 }
3316
3317 const bool context_changed =
3318 thread_changed || frame_changed || stop_id_changed;
3319
3320 if (process_alive) {
3321 if (m_sc.line_entry.IsValid()) {
3322 m_pc_line = m_sc.line_entry.line;
3323 if (m_pc_line != UINT32_MAX)
3324 --m_pc_line; // Convert to zero based line number...
3325 // Update the selected line if the stop ID changed...
3326 if (context_changed)
3327 m_selected_line = m_pc_line;
3328
3329 if (m_file_sp && m_file_sp->GetFileSpec() == m_sc.line_entry.file) {
3330 // Same file, nothing to do, we should either have the lines or not
3331 // (source file missing)
3332 if (m_selected_line >= static_cast<size_t>(m_first_visible_line)) {
3333 if (m_selected_line >= m_first_visible_line + num_visible_lines)
3334 m_first_visible_line = m_selected_line - 10;
3335 } else {
3336 if (m_selected_line > 10)
3337 m_first_visible_line = m_selected_line - 10;
3338 else
3339 m_first_visible_line = 0;
3340 }
3341 } else {
3342 // File changed, set selected line to the line with the PC
3343 m_selected_line = m_pc_line;
3344 m_file_sp =
3345 m_debugger.GetSourceManager().GetFile(m_sc.line_entry.file);
3346 if (m_file_sp) {
3347 const size_t num_lines = m_file_sp->GetNumLines();
3348 m_line_width = 1;
3349 for (size_t n = num_lines; n >= 10; n = n / 10)
3350 ++m_line_width;
3351
3352 if (num_lines < num_visible_lines ||
3353 m_selected_line < num_visible_lines)
3354 m_first_visible_line = 0;
3355 else
3356 m_first_visible_line = m_selected_line - 10;
3357 }
3358 }
3359 } else {
3360 m_file_sp.reset();
3361 }
3362
3363 if (!m_file_sp || m_file_sp->GetNumLines() == 0) {
3364 // Show disassembly
3365 bool prefer_file_cache = false;
3366 if (m_sc.function) {
3367 if (m_disassembly_scope != m_sc.function) {
3368 m_disassembly_scope = m_sc.function;
3369 m_disassembly_sp = m_sc.function->GetInstructions(
3370 exe_ctx, nullptr, prefer_file_cache);
3371 if (m_disassembly_sp) {
3372 set_selected_line_to_pc = true;
3373 m_disassembly_range = m_sc.function->GetAddressRange();
3374 } else {
3375 m_disassembly_range.Clear();
3376 }
3377 } else {
3378 set_selected_line_to_pc = context_changed;
3379 }
3380 } else if (m_sc.symbol) {
3381 if (m_disassembly_scope != m_sc.symbol) {
3382 m_disassembly_scope = m_sc.symbol;
3383 m_disassembly_sp = m_sc.symbol->GetInstructions(
3384 exe_ctx, nullptr, prefer_file_cache);
3385 if (m_disassembly_sp) {
3386 set_selected_line_to_pc = true;
3387 m_disassembly_range.GetBaseAddress() =
3388 m_sc.symbol->GetAddress();
3389 m_disassembly_range.SetByteSize(m_sc.symbol->GetByteSize());
3390 } else {
3391 m_disassembly_range.Clear();
3392 }
3393 } else {
3394 set_selected_line_to_pc = context_changed;
3395 }
3396 }
3397 }
3398 } else {
3399 m_pc_line = UINT32_MAX;
3400 }
3401 }
3402
3403 const int window_width = window.GetWidth();
3404 window.Erase();
3405 window.DrawTitleBox("Sources");
3406 if (!m_title.GetString().empty()) {
3407 window.AttributeOn(A_REVERSE);
3408 window.MoveCursor(1, 1);
3409 window.PutChar(' ');
3410 window.PutCStringTruncated(m_title.GetString().str().c_str(), 1);
3411 int x = window.GetCursorX();
3412 if (x < window_width - 1) {
3413 window.Printf("%*s", window_width - x - 1, "");
3414 }
3415 window.AttributeOff(A_REVERSE);
3416 }
3417
3418 Target *target = exe_ctx.GetTargetPtr();
3419 const size_t num_source_lines = GetNumSourceLines();
3420 if (num_source_lines > 0) {
3421 // Display source
3422 BreakpointLines bp_lines;
3423 if (target) {
3424 BreakpointList &bp_list = target->GetBreakpointList();
3425 const size_t num_bps = bp_list.GetSize();
3426 for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) {
3427 BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx);
3428 const size_t num_bps_locs = bp_sp->GetNumLocations();
3429 for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs; ++bp_loc_idx) {
3430 BreakpointLocationSP bp_loc_sp =
3431 bp_sp->GetLocationAtIndex(bp_loc_idx);
3432 LineEntry bp_loc_line_entry;
3433 if (bp_loc_sp->GetAddress().CalculateSymbolContextLineEntry(
3434 bp_loc_line_entry)) {
3435 if (m_file_sp->GetFileSpec() == bp_loc_line_entry.file) {
3436 bp_lines.insert(bp_loc_line_entry.line);
3437 }
3438 }
3439 }
3440 }
3441 }
3442
3443 const attr_t selected_highlight_attr = A_REVERSE;
3444 const attr_t pc_highlight_attr = COLOR_PAIR(1);
3445
3446 for (size_t i = 0; i < num_visible_lines; ++i) {
3447 const uint32_t curr_line = m_first_visible_line + i;
3448 if (curr_line < num_source_lines) {
3449 const int line_y = m_min_y + i;
3450 window.MoveCursor(1, line_y);
3451 const bool is_pc_line = curr_line == m_pc_line;
3452 const bool line_is_selected = m_selected_line == curr_line;
3453 // Highlight the line as the PC line first, then if the selected line
3454 // isn't the same as the PC line, highlight it differently
3455 attr_t highlight_attr = 0;
3456 attr_t bp_attr = 0;
3457 if (is_pc_line)
3458 highlight_attr = pc_highlight_attr;
3459 else if (line_is_selected)
3460 highlight_attr = selected_highlight_attr;
3461
3462 if (bp_lines.find(curr_line + 1) != bp_lines.end())
3463 bp_attr = COLOR_PAIR(2);
3464
3465 if (bp_attr)
3466 window.AttributeOn(bp_attr);
3467
3468 window.Printf(" %*u ", m_line_width, curr_line + 1);
3469
3470 if (bp_attr)
3471 window.AttributeOff(bp_attr);
3472
3473 window.PutChar(ACS_VLINE);
3474 // Mark the line with the PC with a diamond
3475 if (is_pc_line)
3476 window.PutChar(ACS_DIAMOND);
3477 else
3478 window.PutChar(' ');
3479
3480 if (highlight_attr)
3481 window.AttributeOn(highlight_attr);
3482 const uint32_t line_len =
3483 m_file_sp->GetLineLength(curr_line + 1, false);
3484 if (line_len > 0)
3485 window.PutCString(m_file_sp->PeekLineData(curr_line + 1), line_len);
3486
3487 if (is_pc_line && frame_sp &&
3488 frame_sp->GetConcreteFrameIndex() == 0) {
3489 StopInfoSP stop_info_sp;
3490 if (thread)
3491 stop_info_sp = thread->GetStopInfo();
3492 if (stop_info_sp) {
3493 const char *stop_description = stop_info_sp->GetDescription();
3494 if (stop_description && stop_description[0]) {
3495 size_t stop_description_len = strlen(stop_description);
3496 int desc_x = window_width - stop_description_len - 16;
3497 window.Printf("%*s", desc_x - window.GetCursorX(), "");
3498 // window.MoveCursor(window_width - stop_description_len - 15,
3499 // line_y);
3500 window.Printf("<<< Thread %u: %s ", thread->GetIndexID(),
3501 stop_description);
3502 }
3503 } else {
3504 window.Printf("%*s", window_width - window.GetCursorX() - 1, "");
3505 }
3506 }
3507 if (highlight_attr)
3508 window.AttributeOff(highlight_attr);
3509 } else {
3510 break;
3511 }
3512 }
3513 } else {
3514 size_t num_disassembly_lines = GetNumDisassemblyLines();
3515 if (num_disassembly_lines > 0) {
3516 // Display disassembly
3517 BreakpointAddrs bp_file_addrs;
3518 Target *target = exe_ctx.GetTargetPtr();
3519 if (target) {
3520 BreakpointList &bp_list = target->GetBreakpointList();
3521 const size_t num_bps = bp_list.GetSize();
3522 for (size_t bp_idx = 0; bp_idx < num_bps; ++bp_idx) {
3523 BreakpointSP bp_sp = bp_list.GetBreakpointAtIndex(bp_idx);
3524 const size_t num_bps_locs = bp_sp->GetNumLocations();
3525 for (size_t bp_loc_idx = 0; bp_loc_idx < num_bps_locs;
3526 ++bp_loc_idx) {
3527 BreakpointLocationSP bp_loc_sp =
3528 bp_sp->GetLocationAtIndex(bp_loc_idx);
3529 LineEntry bp_loc_line_entry;
3530 const lldb::addr_t file_addr =
3531 bp_loc_sp->GetAddress().GetFileAddress();
3532 if (file_addr != LLDB_INVALID_ADDRESS) {
3533 if (m_disassembly_range.ContainsFileAddress(file_addr))
3534 bp_file_addrs.insert(file_addr);
3535 }
3536 }
3537 }
3538 }
3539
3540 const attr_t selected_highlight_attr = A_REVERSE;
3541 const attr_t pc_highlight_attr = COLOR_PAIR(1);
3542
3543 StreamString strm;
3544
3545 InstructionList &insts = m_disassembly_sp->GetInstructionList();
3546 Address pc_address;
3547
3548 if (frame_sp)
3549 pc_address = frame_sp->GetFrameCodeAddress();
3550 const uint32_t pc_idx =
3551 pc_address.IsValid()
3552 ? insts.GetIndexOfInstructionAtAddress(pc_address)
3553 : UINT32_MAX;
3554 if (set_selected_line_to_pc) {
3555 m_selected_line = pc_idx;
3556 }
3557
3558 const uint32_t non_visible_pc_offset = (num_visible_lines / 5);
3559 if (static_cast<size_t>(m_first_visible_line) >= num_disassembly_lines)
3560 m_first_visible_line = 0;
3561
3562 if (pc_idx < num_disassembly_lines) {
3563 if (pc_idx < static_cast<uint32_t>(m_first_visible_line) ||
3564 pc_idx >= m_first_visible_line + num_visible_lines)
3565 m_first_visible_line = pc_idx - non_visible_pc_offset;
3566 }
3567
3568 for (size_t i = 0; i < num_visible_lines; ++i) {
3569 const uint32_t inst_idx = m_first_visible_line + i;
3570 Instruction *inst = insts.GetInstructionAtIndex(inst_idx).get();
3571 if (!inst)
3572 break;
3573
3574 const int line_y = m_min_y + i;
3575 window.MoveCursor(1, line_y);
3576 const bool is_pc_line = frame_sp && inst_idx == pc_idx;
3577 const bool line_is_selected = m_selected_line == inst_idx;
3578 // Highlight the line as the PC line first, then if the selected line
3579 // isn't the same as the PC line, highlight it differently
3580 attr_t highlight_attr = 0;
3581 attr_t bp_attr = 0;
3582 if (is_pc_line)
3583 highlight_attr = pc_highlight_attr;
3584 else if (line_is_selected)
3585 highlight_attr = selected_highlight_attr;
3586
3587 if (bp_file_addrs.find(inst->GetAddress().GetFileAddress()) !=
3588 bp_file_addrs.end())
3589 bp_attr = COLOR_PAIR(2);
3590
3591 if (bp_attr)
3592 window.AttributeOn(bp_attr);
3593
3594 window.Printf(" 0x%16.16llx ",
3595 static_cast<unsigned long long>(
3596 inst->GetAddress().GetLoadAddress(target)));
3597
3598 if (bp_attr)
3599 window.AttributeOff(bp_attr);
3600
3601 window.PutChar(ACS_VLINE);
3602 // Mark the line with the PC with a diamond
3603 if (is_pc_line)
3604 window.PutChar(ACS_DIAMOND);
3605 else
3606 window.PutChar(' ');
3607
3608 if (highlight_attr)
3609 window.AttributeOn(highlight_attr);
3610
3611 const char *mnemonic = inst->GetMnemonic(&exe_ctx);
3612 const char *operands = inst->GetOperands(&exe_ctx);
3613 const char *comment = inst->GetComment(&exe_ctx);
3614
3615 if (mnemonic != nullptr && mnemonic[0] == '\0')
3616 mnemonic = nullptr;
3617 if (operands != nullptr && operands[0] == '\0')
3618 operands = nullptr;
3619 if (comment != nullptr && comment[0] == '\0')
3620 comment = nullptr;
3621
3622 strm.Clear();
3623
3624 if (mnemonic != nullptr && operands != nullptr && comment != nullptr)
3625 strm.Printf("%-8s %-25s ; %s", mnemonic, operands, comment);
3626 else if (mnemonic != nullptr && operands != nullptr)
3627 strm.Printf("%-8s %s", mnemonic, operands);
3628 else if (mnemonic != nullptr)
3629 strm.Printf("%s", mnemonic);
3630
3631 int right_pad = 1;
3632 window.PutCStringTruncated(strm.GetData(), right_pad);
3633
3634 if (is_pc_line && frame_sp &&
3635 frame_sp->GetConcreteFrameIndex() == 0) {
3636 StopInfoSP stop_info_sp;
3637 if (thread)
3638 stop_info_sp = thread->GetStopInfo();
3639 if (stop_info_sp) {
3640 const char *stop_description = stop_info_sp->GetDescription();
3641 if (stop_description && stop_description[0]) {
3642 size_t stop_description_len = strlen(stop_description);
3643 int desc_x = window_width - stop_description_len - 16;
3644 window.Printf("%*s", desc_x - window.GetCursorX(), "");
3645 // window.MoveCursor(window_width - stop_description_len - 15,
3646 // line_y);
3647 window.Printf("<<< Thread %u: %s ", thread->GetIndexID(),
3648 stop_description);
3649 }
3650 } else {
3651 window.Printf("%*s", window_width - window.GetCursorX() - 1, "");
3652 }
3653 }
3654 if (highlight_attr)
3655 window.AttributeOff(highlight_attr);
3656 }
3657 }
3658 }
3659 return true; // Drawing handled
3660 }
3661
GetNumLines()3662 size_t GetNumLines() {
3663 size_t num_lines = GetNumSourceLines();
3664 if (num_lines == 0)
3665 num_lines = GetNumDisassemblyLines();
3666 return num_lines;
3667 }
3668
GetNumSourceLines() const3669 size_t GetNumSourceLines() const {
3670 if (m_file_sp)
3671 return m_file_sp->GetNumLines();
3672 return 0;
3673 }
3674
GetNumDisassemblyLines() const3675 size_t GetNumDisassemblyLines() const {
3676 if (m_disassembly_sp)
3677 return m_disassembly_sp->GetInstructionList().GetSize();
3678 return 0;
3679 }
3680
WindowDelegateHandleChar(Window & window,int c)3681 HandleCharResult WindowDelegateHandleChar(Window &window, int c) override {
3682 const uint32_t num_visible_lines = NumVisibleLines();
3683 const size_t num_lines = GetNumLines();
3684
3685 switch (c) {
3686 case ',':
3687 case KEY_PPAGE:
3688 // Page up key
3689 if (static_cast<uint32_t>(m_first_visible_line) > num_visible_lines)
3690 m_first_visible_line -= num_visible_lines;
3691 else
3692 m_first_visible_line = 0;
3693 m_selected_line = m_first_visible_line;
3694 return eKeyHandled;
3695
3696 case '.':
3697 case KEY_NPAGE:
3698 // Page down key
3699 {
3700 if (m_first_visible_line + num_visible_lines < num_lines)
3701 m_first_visible_line += num_visible_lines;
3702 else if (num_lines < num_visible_lines)
3703 m_first_visible_line = 0;
3704 else
3705 m_first_visible_line = num_lines - num_visible_lines;
3706 m_selected_line = m_first_visible_line;
3707 }
3708 return eKeyHandled;
3709
3710 case KEY_UP:
3711 if (m_selected_line > 0) {
3712 m_selected_line--;
3713 if (static_cast<size_t>(m_first_visible_line) > m_selected_line)
3714 m_first_visible_line = m_selected_line;
3715 }
3716 return eKeyHandled;
3717
3718 case KEY_DOWN:
3719 if (m_selected_line + 1 < num_lines) {
3720 m_selected_line++;
3721 if (m_first_visible_line + num_visible_lines < m_selected_line)
3722 m_first_visible_line++;
3723 }
3724 return eKeyHandled;
3725
3726 case '\r':
3727 case '\n':
3728 case KEY_ENTER:
3729 // Set a breakpoint and run to the line using a one shot breakpoint
3730 if (GetNumSourceLines() > 0) {
3731 ExecutionContext exe_ctx =
3732 m_debugger.GetCommandInterpreter().GetExecutionContext();
3733 if (exe_ctx.HasProcessScope() && exe_ctx.GetProcessRef().IsAlive()) {
3734 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
3735 nullptr, // Don't limit the breakpoint to certain modules
3736 m_file_sp->GetFileSpec(), // Source file
3737 m_selected_line +
3738 1, // Source line number (m_selected_line is zero based)
3739 0, // Unspecified column.
3740 0, // No offset
3741 eLazyBoolCalculate, // Check inlines using global setting
3742 eLazyBoolCalculate, // Skip prologue using global setting,
3743 false, // internal
3744 false, // request_hardware
3745 eLazyBoolCalculate); // move_to_nearest_code
3746 // Make breakpoint one shot
3747 bp_sp->GetOptions()->SetOneShot(true);
3748 exe_ctx.GetProcessRef().Resume();
3749 }
3750 } else if (m_selected_line < GetNumDisassemblyLines()) {
3751 const Instruction *inst = m_disassembly_sp->GetInstructionList()
3752 .GetInstructionAtIndex(m_selected_line)
3753 .get();
3754 ExecutionContext exe_ctx =
3755 m_debugger.GetCommandInterpreter().GetExecutionContext();
3756 if (exe_ctx.HasTargetScope()) {
3757 Address addr = inst->GetAddress();
3758 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
3759 addr, // lldb_private::Address
3760 false, // internal
3761 false); // request_hardware
3762 // Make breakpoint one shot
3763 bp_sp->GetOptions()->SetOneShot(true);
3764 exe_ctx.GetProcessRef().Resume();
3765 }
3766 }
3767 return eKeyHandled;
3768
3769 case 'b': // 'b' == toggle breakpoint on currently selected line
3770 if (m_selected_line < GetNumSourceLines()) {
3771 ExecutionContext exe_ctx =
3772 m_debugger.GetCommandInterpreter().GetExecutionContext();
3773 if (exe_ctx.HasTargetScope()) {
3774 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
3775 nullptr, // Don't limit the breakpoint to certain modules
3776 m_file_sp->GetFileSpec(), // Source file
3777 m_selected_line +
3778 1, // Source line number (m_selected_line is zero based)
3779 0, // No column specified.
3780 0, // No offset
3781 eLazyBoolCalculate, // Check inlines using global setting
3782 eLazyBoolCalculate, // Skip prologue using global setting,
3783 false, // internal
3784 false, // request_hardware
3785 eLazyBoolCalculate); // move_to_nearest_code
3786 }
3787 } else if (m_selected_line < GetNumDisassemblyLines()) {
3788 const Instruction *inst = m_disassembly_sp->GetInstructionList()
3789 .GetInstructionAtIndex(m_selected_line)
3790 .get();
3791 ExecutionContext exe_ctx =
3792 m_debugger.GetCommandInterpreter().GetExecutionContext();
3793 if (exe_ctx.HasTargetScope()) {
3794 Address addr = inst->GetAddress();
3795 BreakpointSP bp_sp = exe_ctx.GetTargetRef().CreateBreakpoint(
3796 addr, // lldb_private::Address
3797 false, // internal
3798 false); // request_hardware
3799 }
3800 }
3801 return eKeyHandled;
3802
3803 case 'd': // 'd' == detach and let run
3804 case 'D': // 'D' == detach and keep stopped
3805 {
3806 ExecutionContext exe_ctx =
3807 m_debugger.GetCommandInterpreter().GetExecutionContext();
3808 if (exe_ctx.HasProcessScope())
3809 exe_ctx.GetProcessRef().Detach(c == 'D');
3810 }
3811 return eKeyHandled;
3812
3813 case 'k':
3814 // 'k' == kill
3815 {
3816 ExecutionContext exe_ctx =
3817 m_debugger.GetCommandInterpreter().GetExecutionContext();
3818 if (exe_ctx.HasProcessScope())
3819 exe_ctx.GetProcessRef().Destroy(false);
3820 }
3821 return eKeyHandled;
3822
3823 case 'c':
3824 // 'c' == continue
3825 {
3826 ExecutionContext exe_ctx =
3827 m_debugger.GetCommandInterpreter().GetExecutionContext();
3828 if (exe_ctx.HasProcessScope())
3829 exe_ctx.GetProcessRef().Resume();
3830 }
3831 return eKeyHandled;
3832
3833 case 'o':
3834 // 'o' == step out
3835 {
3836 ExecutionContext exe_ctx =
3837 m_debugger.GetCommandInterpreter().GetExecutionContext();
3838 if (exe_ctx.HasThreadScope() &&
3839 StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) {
3840 exe_ctx.GetThreadRef().StepOut();
3841 }
3842 }
3843 return eKeyHandled;
3844
3845 case 'n': // 'n' == step over
3846 case 'N': // 'N' == step over instruction
3847 {
3848 ExecutionContext exe_ctx =
3849 m_debugger.GetCommandInterpreter().GetExecutionContext();
3850 if (exe_ctx.HasThreadScope() &&
3851 StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) {
3852 bool source_step = (c == 'n');
3853 exe_ctx.GetThreadRef().StepOver(source_step);
3854 }
3855 }
3856 return eKeyHandled;
3857
3858 case 's': // 's' == step into
3859 case 'S': // 'S' == step into instruction
3860 {
3861 ExecutionContext exe_ctx =
3862 m_debugger.GetCommandInterpreter().GetExecutionContext();
3863 if (exe_ctx.HasThreadScope() &&
3864 StateIsStoppedState(exe_ctx.GetProcessRef().GetState(), true)) {
3865 bool source_step = (c == 's');
3866 exe_ctx.GetThreadRef().StepIn(source_step);
3867 }
3868 }
3869 return eKeyHandled;
3870
3871 case 'h':
3872 window.CreateHelpSubwindow();
3873 return eKeyHandled;
3874
3875 default:
3876 break;
3877 }
3878 return eKeyNotHandled;
3879 }
3880
3881 protected:
3882 typedef std::set<uint32_t> BreakpointLines;
3883 typedef std::set<lldb::addr_t> BreakpointAddrs;
3884
3885 Debugger &m_debugger;
3886 SymbolContext m_sc;
3887 SourceManager::FileSP m_file_sp;
3888 SymbolContextScope *m_disassembly_scope;
3889 lldb::DisassemblerSP m_disassembly_sp;
3890 AddressRange m_disassembly_range;
3891 StreamString m_title;
3892 lldb::user_id_t m_tid;
3893 int m_line_width;
3894 uint32_t m_selected_line; // The selected line
3895 uint32_t m_pc_line; // The line with the PC
3896 uint32_t m_stop_id;
3897 uint32_t m_frame_idx;
3898 int m_first_visible_line;
3899 int m_min_x;
3900 int m_min_y;
3901 int m_max_x;
3902 int m_max_y;
3903 };
3904
3905 DisplayOptions ValueObjectListDelegate::g_options = {true};
3906
IOHandlerCursesGUI(Debugger & debugger)3907 IOHandlerCursesGUI::IOHandlerCursesGUI(Debugger &debugger)
3908 : IOHandler(debugger, IOHandler::Type::Curses) {}
3909
Activate()3910 void IOHandlerCursesGUI::Activate() {
3911 IOHandler::Activate();
3912 if (!m_app_ap) {
3913 m_app_ap = std::make_unique<Application>(GetInputFILE(), GetOutputFILE());
3914
3915 // This is both a window and a menu delegate
3916 std::shared_ptr<ApplicationDelegate> app_delegate_sp(
3917 new ApplicationDelegate(*m_app_ap, m_debugger));
3918
3919 MenuDelegateSP app_menu_delegate_sp =
3920 std::static_pointer_cast<MenuDelegate>(app_delegate_sp);
3921 MenuSP lldb_menu_sp(
3922 new Menu("LLDB", "F1", KEY_F(1), ApplicationDelegate::eMenuID_LLDB));
3923 MenuSP exit_menuitem_sp(
3924 new Menu("Exit", nullptr, 'x', ApplicationDelegate::eMenuID_LLDBExit));
3925 exit_menuitem_sp->SetCannedResult(MenuActionResult::Quit);
3926 lldb_menu_sp->AddSubmenu(MenuSP(new Menu(
3927 "About LLDB", nullptr, 'a', ApplicationDelegate::eMenuID_LLDBAbout)));
3928 lldb_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator)));
3929 lldb_menu_sp->AddSubmenu(exit_menuitem_sp);
3930
3931 MenuSP target_menu_sp(new Menu("Target", "F2", KEY_F(2),
3932 ApplicationDelegate::eMenuID_Target));
3933 target_menu_sp->AddSubmenu(MenuSP(new Menu(
3934 "Create", nullptr, 'c', ApplicationDelegate::eMenuID_TargetCreate)));
3935 target_menu_sp->AddSubmenu(MenuSP(new Menu(
3936 "Delete", nullptr, 'd', ApplicationDelegate::eMenuID_TargetDelete)));
3937
3938 MenuSP process_menu_sp(new Menu("Process", "F3", KEY_F(3),
3939 ApplicationDelegate::eMenuID_Process));
3940 process_menu_sp->AddSubmenu(MenuSP(new Menu(
3941 "Attach", nullptr, 'a', ApplicationDelegate::eMenuID_ProcessAttach)));
3942 process_menu_sp->AddSubmenu(MenuSP(new Menu(
3943 "Detach", nullptr, 'd', ApplicationDelegate::eMenuID_ProcessDetach)));
3944 process_menu_sp->AddSubmenu(MenuSP(new Menu(
3945 "Launch", nullptr, 'l', ApplicationDelegate::eMenuID_ProcessLaunch)));
3946 process_menu_sp->AddSubmenu(MenuSP(new Menu(Menu::Type::Separator)));
3947 process_menu_sp->AddSubmenu(
3948 MenuSP(new Menu("Continue", nullptr, 'c',
3949 ApplicationDelegate::eMenuID_ProcessContinue)));
3950 process_menu_sp->AddSubmenu(MenuSP(new Menu(
3951 "Halt", nullptr, 'h', ApplicationDelegate::eMenuID_ProcessHalt)));
3952 process_menu_sp->AddSubmenu(MenuSP(new Menu(
3953 "Kill", nullptr, 'k', ApplicationDelegate::eMenuID_ProcessKill)));
3954
3955 MenuSP thread_menu_sp(new Menu("Thread", "F4", KEY_F(4),
3956 ApplicationDelegate::eMenuID_Thread));
3957 thread_menu_sp->AddSubmenu(MenuSP(new Menu(
3958 "Step In", nullptr, 'i', ApplicationDelegate::eMenuID_ThreadStepIn)));
3959 thread_menu_sp->AddSubmenu(
3960 MenuSP(new Menu("Step Over", nullptr, 'v',
3961 ApplicationDelegate::eMenuID_ThreadStepOver)));
3962 thread_menu_sp->AddSubmenu(MenuSP(new Menu(
3963 "Step Out", nullptr, 'o', ApplicationDelegate::eMenuID_ThreadStepOut)));
3964
3965 MenuSP view_menu_sp(
3966 new Menu("View", "F5", KEY_F(5), ApplicationDelegate::eMenuID_View));
3967 view_menu_sp->AddSubmenu(
3968 MenuSP(new Menu("Backtrace", nullptr, 'b',
3969 ApplicationDelegate::eMenuID_ViewBacktrace)));
3970 view_menu_sp->AddSubmenu(
3971 MenuSP(new Menu("Registers", nullptr, 'r',
3972 ApplicationDelegate::eMenuID_ViewRegisters)));
3973 view_menu_sp->AddSubmenu(MenuSP(new Menu(
3974 "Source", nullptr, 's', ApplicationDelegate::eMenuID_ViewSource)));
3975 view_menu_sp->AddSubmenu(
3976 MenuSP(new Menu("Variables", nullptr, 'v',
3977 ApplicationDelegate::eMenuID_ViewVariables)));
3978
3979 MenuSP help_menu_sp(
3980 new Menu("Help", "F6", KEY_F(6), ApplicationDelegate::eMenuID_Help));
3981 help_menu_sp->AddSubmenu(MenuSP(new Menu(
3982 "GUI Help", nullptr, 'g', ApplicationDelegate::eMenuID_HelpGUIHelp)));
3983
3984 m_app_ap->Initialize();
3985 WindowSP &main_window_sp = m_app_ap->GetMainWindow();
3986
3987 MenuSP menubar_sp(new Menu(Menu::Type::Bar));
3988 menubar_sp->AddSubmenu(lldb_menu_sp);
3989 menubar_sp->AddSubmenu(target_menu_sp);
3990 menubar_sp->AddSubmenu(process_menu_sp);
3991 menubar_sp->AddSubmenu(thread_menu_sp);
3992 menubar_sp->AddSubmenu(view_menu_sp);
3993 menubar_sp->AddSubmenu(help_menu_sp);
3994 menubar_sp->SetDelegate(app_menu_delegate_sp);
3995
3996 Rect content_bounds = main_window_sp->GetFrame();
3997 Rect menubar_bounds = content_bounds.MakeMenuBar();
3998 Rect status_bounds = content_bounds.MakeStatusBar();
3999 Rect source_bounds;
4000 Rect variables_bounds;
4001 Rect threads_bounds;
4002 Rect source_variables_bounds;
4003 content_bounds.VerticalSplitPercentage(0.80, source_variables_bounds,
4004 threads_bounds);
4005 source_variables_bounds.HorizontalSplitPercentage(0.70, source_bounds,
4006 variables_bounds);
4007
4008 WindowSP menubar_window_sp =
4009 main_window_sp->CreateSubWindow("Menubar", menubar_bounds, false);
4010 // Let the menubar get keys if the active window doesn't handle the keys
4011 // that are typed so it can respond to menubar key presses.
4012 menubar_window_sp->SetCanBeActive(
4013 false); // Don't let the menubar become the active window
4014 menubar_window_sp->SetDelegate(menubar_sp);
4015
4016 WindowSP source_window_sp(
4017 main_window_sp->CreateSubWindow("Source", source_bounds, true));
4018 WindowSP variables_window_sp(
4019 main_window_sp->CreateSubWindow("Variables", variables_bounds, false));
4020 WindowSP threads_window_sp(
4021 main_window_sp->CreateSubWindow("Threads", threads_bounds, false));
4022 WindowSP status_window_sp(
4023 main_window_sp->CreateSubWindow("Status", status_bounds, false));
4024 status_window_sp->SetCanBeActive(
4025 false); // Don't let the status bar become the active window
4026 main_window_sp->SetDelegate(
4027 std::static_pointer_cast<WindowDelegate>(app_delegate_sp));
4028 source_window_sp->SetDelegate(
4029 WindowDelegateSP(new SourceFileWindowDelegate(m_debugger)));
4030 variables_window_sp->SetDelegate(
4031 WindowDelegateSP(new FrameVariablesWindowDelegate(m_debugger)));
4032 TreeDelegateSP thread_delegate_sp(new ThreadsTreeDelegate(m_debugger));
4033 threads_window_sp->SetDelegate(WindowDelegateSP(
4034 new TreeWindowDelegate(m_debugger, thread_delegate_sp)));
4035 status_window_sp->SetDelegate(
4036 WindowDelegateSP(new StatusBarWindowDelegate(m_debugger)));
4037
4038 // Show the main help window once the first time the curses GUI is launched
4039 static bool g_showed_help = false;
4040 if (!g_showed_help) {
4041 g_showed_help = true;
4042 main_window_sp->CreateHelpSubwindow();
4043 }
4044
4045 init_pair(1, COLOR_WHITE, COLOR_BLUE);
4046 init_pair(2, COLOR_BLACK, COLOR_WHITE);
4047 init_pair(3, COLOR_MAGENTA, COLOR_WHITE);
4048 init_pair(4, COLOR_MAGENTA, COLOR_BLACK);
4049 init_pair(5, COLOR_RED, COLOR_BLACK);
4050 }
4051 }
4052
Deactivate()4053 void IOHandlerCursesGUI::Deactivate() { m_app_ap->Terminate(); }
4054
Run()4055 void IOHandlerCursesGUI::Run() {
4056 m_app_ap->Run(m_debugger);
4057 SetIsDone(true);
4058 }
4059
4060 IOHandlerCursesGUI::~IOHandlerCursesGUI() = default;
4061
Cancel()4062 void IOHandlerCursesGUI::Cancel() {}
4063
Interrupt()4064 bool IOHandlerCursesGUI::Interrupt() { return false; }
4065
GotEOF()4066 void IOHandlerCursesGUI::GotEOF() {}
4067
4068 #endif // LLDB_ENABLE_CURSES
4069