Thursday, September 25, 2014

Attaching debugger to running process (PyDev 3.8.0)

The latest PyDev 3.8.0 has just been released... along with a bunch of bugfixes, the major feature added is the possibility of attaching the debugger to a running process.

So, I thought about explaining a bit how to use it (and later a bit on how it was done).

The first thing is that the Debug perspective must be activated (as the attach to process menu is only shown by default in the Debug Perspective). Then, when on the debug perspective, select PyDev > Attach to Process (as the image below shows).



When that action is activated, a list with the active processes is shown so that the process we should attach to can be selected (as a note, by default only Python processes are filtered, but if you have an executable running Python under a different name, it's also possible to select it).


After selecting the executable, the user must provide a Python interpreter that's compatible with the interpreter we'll attach to (i.e.: if we're attaching to a 64 bit interpreter, the interpreter selected must also be a 64 bit process -- and likewise for 32 bits).


And if everything went right, we'll be connected with the process after that step (you can note in the screenshot below that in the Debug View we have a process running regularly and we connected to the process through the remote debugger) -- after it's connected, it's possible to pause the running process (through right-click process > suspend)


So, this was how to use it within PyDev... now, I'll explain a bit on the internals as I had a great time implementing that feature :)

The first thing to note is that we currently support (only) Windows and Linux... although the basic idea is the same on both cases (we get a dll loaded in the target process and then execute our attach code through it), the implementations are actually pretty different (as it's Open Source, it can be seen at: https://github.com/fabioz/PyDev.Debugger/tree/development/pydevd_attach_to_process)

So, let me start with the Windows implementation...

In the Windows world, I must thank a bunch of people that came before me in order to make it work:
First, Mario Vilas for Winappdbg: https://github.com/MarioVilas/winappdbg -- mostly, this is a Windows debugger written in Python. We use it to attach a dll to a target process. Then, after the dll is loaded, there's some hand-crafted shellcode created to execute a function from that dll (which is actually different for 32 bits and for 64 bits -- I did spend quite some time here since my assembly knowledge was mostly theoretical, so, it was nice to see it working in practice: that's the GenShellCodeHelper class in add_code_to_python_process.py and it's used in the run_python_code_windows function).

Ok, so, that gives us the basic hackery needed in order to execute some code in a different process (which Winappdbg does through the Windows CreateRemoteThread API) -- so, initially I had a simple version working which did (all in shellcode) an acquire of the Python GIL/run some hand-crafted Python code through PyRun_SimpleString/release GIL... but there are a number of problems with that simple approach: the first one is that although we'll execute some Python code there, we'll do it under a new thread, which under Python 3 meant that this would be no good since we have to initialize the Python threading if it still wasn't initialized. Also, to setup the Debugger we need to call sys.settrace on existing threads (while executing in that thread -- or at least making Python think we're at that thread as there's no API for that)... at that point I decided on having the dll (and not only shellcode).

So, here I must thank the PVTS guys (which actually have an attach to process on Windows which does mixed mode debugging), so, the attach.cpp file which generates our dll is adapted from PVTS to the PyDev use case. It goes through a number of hoops to initialize the threading facility in Python if it still wasn't initialized and does the sys.settrace while having all threads suspended and makes Python think we're actually at the proper thread to make that call... looking at it, I find it really strange that Python itself doesn't have an API for that (it should be easy to do on Python, but it's such a major hack on the debugger because that API is not available).

Now, on to Linux: in Linux the approach is simpler as we reuse a debugger that should be readily available for Linux developers: gdb. Also, because gdb stops threads for us and executes the code in an existing thread, things become much simpler... first, because we're executing in an existing thread, we don't have to start the threading if it's not started -- the only reason this is needed in Windows is because we're executing the code in a new thread in the process, created through CreateRemoteThread -- and also, as gdb has a way to script in Python were we can switch threads and execute something in it while having other threads stopped, we also don't need to do the trick on Python to make it think we're in a thread to execute a sys.settrace as if we were in a thread when in reality we weren't, as we can switch to a thread and really execute code on it.

So, all in all, it should be working properly, although there are a number of caveats... it may fail if we don't have permissions for the CreateRemoteThread on Windows or in Linux it could fail if the ptrace permissions are not set for us to attach with GDB -- and probably a bunch of other things I still didn't think of :)

Still, it's nice to see it working!

Also, the last thanks goes to JetBrains/PyCharm, which helped in sponsoring the work in the debugger -- as I mentioned earlier: http://pydev.blogspot.com.br/2014/08/pydev-370-pydevpycharm-debugger-merge.html the debugger in PyDev/PyCharm is now merged :)

Tuesday, August 26, 2014

PyDev 3.7.0, PyDev/PyCharm Debugger merge, Crowdfunding

PyDev 3.7.0 was just released.

There are some interesting things to talk about in this release...

The first is that the PyDev debugger was merged with the fork which was used in PyCharm. The final code for the debugger (and the interactive console) now lives at: https://github.com/fabioz/PyDev.Debugger. This effort was backed-up by Intellij, and from now on, work on the debugger from either front (PyDev or PyCharm) should benefit both -- pull requests are also very welcome :)

With this merge, PyDev users will gain GEvent debugging and breakpoints at Django templates (but note that the breakpoints can only be added through the LiClipse HTML/Django Templates editor), and in the interactive console front (which was also part of this merge), the asynchronous output and console interrupt are new.

This release also changed the default UI for the PyDev editor (and for LiClipse editors too), so, the minimap (which had a bunch of enhancements) is now turned on by default and the scrollbars are hidden by default -- those that prefer the old behavior must change the settings on the minimap preferences to match the old style.

Also noteworthy is that the code-completion for all letter chars is turned on by default (again, users that want the old behavior have to uncheck that setting from the code completion preferences page), and this release also has a bunch of bugfixes.

Now, I haven't talked about the crowdfunding for keeping the support on PyDev and a new profiler UI (https://sw-brainwy.rhcloud.com/support/pydev-2014) after it finished... well, it didn't reach its full goal -- in practice that means the profiler UI will still be done and users which supported it will receive a license to use it, but it won't be open source... all in all, it wasn't that bad either, it got halfway through its target and many people seemed to like the idea -- in the end I'll know if keeping it on even if not having the full target reached was a good idea or not only after it's commercially available (as the idea is that new licenses will be what will cover for its development expenses and will keep it going afterwards).

A note for profiler contributors is that I still haven't released an early-release version, but I'm working on it :)

As for PyDev, the outcome of the funding also means I have fewer resources to support it than I'd like, but given that LiClipse (http://brainwy.github.io/liclipse/) provides a share of its earnings to support PyDev and latecomers can still contribute through http://pydev.org/, I still hope that I won't need to lower its support (which'd mean taking on other projects in the time I currently have for PyDev), and I think it'll still be possible to do the things outlined in the crowdfunding regarding it.




Thursday, July 10, 2014

New Python profiler UI

So, I wanted to show what I have so far on the profiler front.

Below is its main UI (on a dark palette -- kudos to Qt which makes this pretty easy to do):



The tree shows the attached processes and the CPU tab shows data for the CPU from the process which is being analyzed.

Based on that, it's possible to select a timeframe where stack info is shown (in this case the profiler is analyzing itself). Clicking on a stack opens an internal editor (which can only view the file so far) at the proper place (but the idea is that in the future it'll open the editor in your preferred editor/IDE).

It's possible to start/stop the sampling and the stacks can be grouped either by line or by methods.

Another thing (which is also still incomplete) is provide a view which will show a profile session view graphically... Below is a snapshot of the work on that front so far.



The work is still very much in the beginning, but the sampling view should be usable already -- the plan is to release  the first builds some days after the crowdfunding finishes... thank you to all who are helping to make this possible: https://sw-brainwy.rhcloud.com/support/pydev-2014

Tuesday, June 24, 2014

PyDev 3.6.0 released

PyDev 3.6.0 was just released.

The really major change in this release is that PyDev updated its internal Jython to the latest version, which also allowed PyDev to update its support to the latest pep8.py.

Also, following this, autopep8.py was also integrated (although it seems there's still an issue dealing with non-ascii files -- see: https://sw-brainwy.rhcloud.com/tracker/PyDev/402 for a workaround). Note that unlike pep8.py, autopep8.py doesn't really use the internal Jython (it runs based on the default configured Python interpreter). This is mostly because Jython was too slow when running it (annoyingly so in this use-case), so, there's only the option of running autopep8.py externally.

Also, some 'nice to have' features were added:

Shift+F9 will run the current editor directly in debug mode -- so, no need to Alt+R+G, 1-4 for that anymore :)

Also, when selecting a unit-test to run (Ctrl+F9), if Shift is pressed when the test(s) to run is selected, it'll also run in debug mode (previously it was almost mandatory to create a regular run selecting the tests, killing it and pressing F11 just to re-run the last test in debug mode).

Besides this, there were some bug-fixes (and for those using LiClipse: http://brainwy.github.io/liclipse, it's already updated with the latest PyDev version -- and now it supports launching for other languages and Julia support was added).

Enjoy!

p.s.:  Thank you for all that are supporting the PyDev crowdfunding: https://sw-brainwy.rhcloud.com/support/pydev-2014/

Tuesday, May 20, 2014

PyDev 3.5.0 released

PyDev 3.5.0 is now available...

The main feature in this release relates to improvements to work with py.test (note: those that want to use it have to enable it in the PyUnit preferences -- besides having to install it properly in the used Python installation).

Mainly, the integration was changed so that the py.test xdist plugin can be properly used and module/session scoped fixtures should also work properly. The PyUnit UI in the preferences was also changed to show the preferences related to py.test when it's shown.

Still, there are other improvements: the Model.objects from django 1.7 is now available on code-completion again (as the static analyzer couldn't cope with it there are workarounds in the code), private attributes (those starting with '__') are now shown when hovering over it on the debugger and there's a bunch of other bug-fixes and minor features available (see http://pydev.org for details).

Also, for those that don't know, there's an ongoing crowdfunding to keep PyDev support going on: http://tiny.cc/pydev-2014...

Thursday, May 15, 2014

Crowdfunding for PyDev and new Python profiler UI (for any IDE)

Ok, I just started a crowdfunding project (at http://tiny.cc/pydev-2014) for the continued development of PyDev and the creation of a new profiler UI.

This is actually the 2nd crowdfunding for PyDev after Appcelerator stopped supporting it. Last year a similar crowdfunding allowed me to keep on developing PyDev until now, as well as creating a new PyDev/Eclipse bundle called LiClipse, which added lightweight support for several languages as well a dark theme inside Eclipse.


So, now I'm reaching out again for the PyDev community to allow me to keep on developing PyDev and shaping the Python landscape.


This year when planning what to do and filtering on existing requests, one of the things that stood up was providing proper support for profiling in PyDev.


After tinkering with the idea a bit and trying to find out how I think would be the best way for this workflow, I've settled on creating a separate tool and then integrating it properly in PyDev... not only this approach will allow Pythonistas that don't use PyDev to have a nice profiling companion, but I think it'll also yield better results than doing it all inside of Eclipse -- besides, I'll be able to do it all in Python!


So, this is the main feature I've planned for this year, but there are others too which are more focused on PyDev itself, such as having preferences per-project, migrating to a new workspace, validating docstrings for its type on a test run, external pep8 linter, vertical lines for indentation, attach debugger to running process -- besides the usual bugfixing and support.


So, please help in funding (and sharing) at http://tiny.cc/pydev-2014 to help in making the new profiler UI a reality and to keep PyDev going strong!



Friday, March 28, 2014

Mastering writing code on PyDev

One of these days I was pair coding with a friend -- which was also using PyDev -- and upon looking him code I realized that there are some simple things which everyone should know when writing code on PyDev:

1. Want to write a new line? Use Shift+Enter: This is what I almost always use in PyDev instead of the plain enter to enter a new line.

How it works: It'll emulate moving to the end of the line and pressing enter there.

Tip: It can be used when there's a completion to avoid applying it while going to the next line (as Enter is also used to apply a completion if you don't use Shift+Enter you have to press ESC before to avoid applying it if you use a plain Enter).

2. Want to copy or move some lines? Ctrl+Alt+Up will copy the lines up and Ctrl+Alt+Down will copy them down and then Alt+Up or Alt+Down can be used to move them up or down (so, it's a line-oriented copy/paste which is really handy).

3. Is there a string or comment which is too big and you want to wrap it? Use Ctrl+2, W and it'll wrap it for you (using the number of columns assigned in the print margin preferences).

4. Want to create a docstring for the parameters of a method? Ctrl+1 -> Make Docstring (in a line with the method declaration).

5. Assign parameters to variables? Ctrl+1 -> Assign parameters to attributes (in a line with the method declaration in a class). Alternatively use Ctrl+2, A.

6. Want to select the current word? Shift+Alt+Up will select the current word for you (and if you keep using Shift+Alt+Up it'll then select the enclosing context and Shift+Alt+Down will deselect it again).

7. Rectangular selection: Shift+Alt+A.

8. Want to rename a local token? To do that use Ctrl+2, R (note that for renaming a token in multiple modules you'd use Shift+Alt+R or a package/module in the PyDev Package Explorer would be renamed with F2).

9. To rename something that's not a token (such as a comma) -- if you're in LiClipse (which adds this feature) -- you can do Ctrl+K (or Ctrl+Shift+K to go backwards) multiple times to mark the places you want to rename and then go on to rename it (as a note, Ctrl+Alt+K will unlink one of the occurrences). This can also be used for a substring -- or any character combination for that matter.

10. Do you have some code with multiple tokens that are not found and need to be imported? Ctrl+Shift+O can be used to resolve the multiple missing tokens. Alternatively you could also use Ctrl+1 on a line with a missing import to get the suggestion to add it (if it wasn't already added in a code-completion which added it for you automatically).

11. Like TDD coding? i.e.: write the test first and do the code later. If so, you can usually write the test and use Ctrl+1 to provide a suggestion to create the missing method, module or attribute.

12. PyDev doesn't automatically re-analyze dependent modules when one module changes, so, I've seen people just add some space and save the file again just to force a new code analysis... while this works, there's a specific keybinding: Ctrl+2, C which will force a code-analysis in the current module.

13. When there are many contiguous lines commented and you want to uncomment them, do you see yourself selecting all those lines to uncomment it? Did you know that Ctrl+5 does that promptly for you from any line of that block?

14. Just edited something but don't remember where it was? Ctrl+Q can be used to go to the last place you edited some code.

15. Do you have some code you just copied from somewhere and want to create a module with it? Go to the PyDev package explorer and just paste the code there to create a new module with those contents.

16. Do you have some method call or variable that you want to add to another local variable or field? Use Ctrl+1 (on a line that still doesn't have an assign) and choose assign to local or assign to field.

Besides those tips, print the bindings from: http://pydev.org/manual_adv_keybindings.html and leave it by your side until you don't master them :)