Debugging CH32V103R with Visual Studio Code on Ubuntu #2

As I wrote in the previous post regarding debugging on the macOS environment, I figured out a way to avoid the Restart (Ctrl+Shift F5) and Disconnect (Shift+F5) operation issues I found in my past Visual Studio Code on Ubuntu post. So, I tested my finding on Ubuntu also.

At first, I edited the /etc/group file to add my Ubuntu account to the plugdev group (ncpin is my account name on Ubuntu).

/etc/group
[before]
plugdev:x:46:admin-user

[after]
plugdev:x:46:admin-user,ncpin

By doing this, I didn’t have to use the sudo command when I run the openocd command anymore. Since the Linux kernel sets the user group of the WCH-Link USB device to the plugdev group when the kernel detects the device according to the udev rule file /etc/udev/rules.d/50-wch.rules that I copied before, and if a user does not belong to the plugdev group, the user will need root privilege to access the WCH-Link USB device from a process like the openocd command.

I added the following line to the end of OpenOCD’s wch-riscv.cfg file.

$_TARGETNAME.0 configure -event gdb-detach { shutdown }

I replaced the contents of Visual Studio Code’s code-workspace JSON file as follows.

{
  "tasks": {
    "version": "2.0.0",
    "tasks": [
      {
        "label": "run_openocd",
        "type": "process",
        "isBackground": true,
        "command": "${workspaceRoot}/openocd",
        "args": ["-f", "${workspaceRoot}/wch-riscv.cfg"],
        "problemMatcher": [
          {
            "pattern": [
            {
              "regexp": ".",
              "file": 1,
              "location": 2,
              "message": 3
            }
            ],
            "background": {
            "activeOnStart": true,
            "beginsPattern": ".",
            "endsPattern": "."
            }
          }
          ]
      }
    ]
  },
  "folders": [
    {
      "path": "."
    }
  ],
  "launch": {
    "version": "0.2.0",
    "configurations": [
      {
        "name": "gdb-openocd",
        "type": "gdb",
        "request": "attach",
        "executable": "exiti0.elf",
        "remote": true,
        "target": ":3333",
        "cwd": "${workspaceRoot}",
        "gdbpath": "riscv32-unknown-elf-gdb",
        "preLaunchTask": "run_openocd",
        "autorun": [
          "set mem inaccessible-by-default off",
          "set architecture riscv:rv32",
          "set remotetimeout unlimited",
          "monitor reset halt",
          "load"
        ]
      }
    ]
  }
}

(Please note that this setting file assumes that both the openocd command and the wch-riscv.cfg file exists at the workspace root directory of the Visual Studio Code project)

With the above changes, I no longer needed to run the openocd command separately. When I started the debug operation, Visual Studio Code automatically ran the openocd command in the background, and the launched openocd command stopped when I chose the Restart (Ctrl+Shift F5) and Disconnect (Shift+F5) command. And I was able to start debugging again also, unlike before.

Debugging CH32V307V with Visual Studio Code on macOS

As the final testing of the CH32V series RISC-V MCU development environment on Mac, I tried whether I could debug a program running on WCH’s CH32V307RCT6 evaluation board (CH32V307V-EVT-R1) or not with Visual Studio Code in the same way as I did before on my Ubuntu 20.04 environment.

I tested Visual Studio Code using the same CH32V307 example as the previous post. This time, to generate debugging information, I added -g and -O0 to the GCC options in the Makefile (Here is the updated file) and rebuilt the example.

After installing Visual Studio Code to my MacBook Pro (intel, 13inch, 2020), I added the Native Debug extension by WebFreak.

I saved a workspace of Visual Studio Code into the ch32v307/EVT/EXAM/GPIO/GPIO_Toggle/User directory and added this directory to the workspace also. Then I created a launch.json file by clicking create a launch.json file(1), (2) and selecting the workplace (3) and GDB(4) items.

I replaced the contents of the created JSON file with the following.

{
	"tasks": {
		"version": "2.0.0",
		"tasks": [
			{
				"label": "run_openocd",
				"type": "process",
				"isBackground": true,
				"command": "${userHome}/csfs/openocd/openocd",
				"args": ["-f", "${userHome}/csfs/openocd/wch-riscv.cfg"],
				"problemMatcher": [
					{
					  "pattern": [
						{
						  "regexp": ".",
						  "file": 1,
						  "location": 2,
						  "message": 3
						}
					  ],
					  "background": {
						"activeOnStart": true,
						"beginsPattern": ".",
						"endsPattern": ".",
					  }
					}
				  ]
			}
		]
	},
	"folders": [
		{
			"path": "."
		}
	],
	"launch": {
		"version": "0.2.0",
		"configurations": [
			{
				"name": "gdb-openocd",
				"type": "gdb",
				"request": "attach",
				"executable": "gpio_toggle.elf",
				"remote": true,
				"target": ":3333",
				"cwd": "${workspaceRoot}",
				"gdbpath": "${userHome}/csfs/x-tools/riscv32-unknown-elf/bin/riscv32-unknown-elf-gdb",
				"preLaunchTask": "run_openocd",
				"autorun": [
					"set mem inaccessible-by-default off",
					"set architecture riscv:rv32",
					"set remotetimeout unlimited",
					"monitor reset halt",
					"load"
				]
			}
		]
	}
}

Before starting the debugging with Visual Studio Code, I mounted the disk image I made in a new Terminal window.

hdid -nomount csfs.sparseimage
mount -t hfs /dev/disk2s2 csfs
export PATH="$HOME/csfs/x-tools/riscv32-unknown-elf/bin:$HOME/csfs/openocd:$PATH"

Then I added the following line to the end of OpenOCD’s config file $HOME/csfs/openocd/wch-riscv.cfg to avoid the Restart and Disconnection issue I found when I tried to run Visual Studio Code on Ubuntu.

$_TARGETNAME.0 configure -event gdb-detach { shutdown }

I set a breakpoint in main.c and started debugging by selecting the Start Debugging (F5) item under the Run menu.

As far as I tested briefly, debugging on Visual Studio Code worked pretty well. This time I was able to figure out a way to avoid the Restart (Ctrl+Shift F5) and Disconnect (Shift+F5) operation issues that I found when I tried Visual Studio Code on Ubuntu by modifying OpenOCD’s config file and defining preLaunchTask to the Visual Studio Code setting.

[Added on 2022-07-08]
I uploaded my ch32v307/EVT/EXAM/GPIO/GPIO_Toggle/ directory as the tgz file just for reference. My Visual Studio Code project file (GPIO_Toggle.code-workspace) with the above setting is also included in the tgz file.

Building Toolchain for RISC-V on macOS

As a part of investigating the CH32V series RISC-V MCU development environment on Mac, I tried to build the cross-toolchain for RISC-V by using Crosstool-NG on my Mac basically in the same way I did before on the Ubuntu 20.04. I used the same MacBook Pro  (intel, 13inch, 2020), and the OS version was macOS Monterey (Version 12.3.1).

To build the Crosstool-NG, I added additional Homebrew packages at first.

brew install bash texinfo libtool libmpc zlib gawk bison flex gperf patchutils help2man ncurses dtc expat gnu-sed binutils xz curl wget python@3.8

I built and installed the Crosstool-NG as follows.

export PATH="/usr/local/opt/python@3.8/bin:/usr/local/opt/binutils/bin:/usr/local/opt/ncurses/bin:$PATH"
export LDFLAGS="-L/usr/local/opt/python@3.8/lib -L/usr/local/opt/ncurses/lib"
export CPPFLAGS="-I/usr/local/opt/ncurses/include"
export PKG_CONFIG_PATH="/usr/local/opt/python@3.8/lib/pkgconfig"

git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
./bootstrap
./configure
make
sudo make install
sudo ct-ng update-samples

As seen in the above procedure, the setting of the environment variables for the ncurses was necessary for building the Crosstool-NG. And also, without specifying the environment variables for the python 3.8, which the Homebrew installed, I could build the Crosstool-NG itself. However, the Crosstool-NG without the above python settings failed to build the GCC 12.1.0 by a Python-related error.

Unfortunately, it also turned out that the Crosstool-NG requires a case-sensitive file system to build the toolchain (There is a description about this on the official site). To prepare the case-sensitive file system, this time, I created a disk image formatted with the case-sensitive file system using the hdiutil command and mounted the disk image under my home directory by the hdid command and the mount command as follows.

cd ~
hdiutil create -type SPARSE -fs 'Case-sensitive Journaled HFS+' -size 32g -volname csfs csfs

mkdir csfs
hdid -nomount csfs.sparseimage
mount -t hfs /dev/disk2s2 csfs

The device filename of the disk image (/dev/disk2s2) might have a different name under a different environment. The command hdid outputs the device filename of the specified disk image.

After mounting the created disk image under the ~/csfs directory, I built the cross-toolchain using the Crosstool-NG as follows.

cd csfs
mkdir build
mkdir src
cd build

ct-ng riscv32-unknown-elf
ct-ng menuconfig

For the ct-ng menuconfig command, I changed the following options from the default.

  • In the Path and misc options menu, I changed the Local tar balls directory setting from ${HOME}/src to ${HOME}/csfs/src and inserted /csfs between ${HOME} and /x-tools in the Prefix directory setting.
  • In the Target options menu, I enabled the Build a multilib toolchain.
  • In the C-library menu, I selected the newlib as the C library.
  • In the Companion libraries menu, I selected the newlib-nano and enabled the Additionally install newlib-nano libs into TARGET dir option for the newlib-nano.
  • In the Debug facilities menu, I enabled the gdb menu item and disabled the python scripting option inside the gdb menu item.

After saving the changes to the .config file, I initiated the toolchain build by the following command.

ct-ng build

The toolchain build took about 50mins with my Mac, and I finally got the working toolchain binaries under ~/csfs/x-tools/riscv32-unknown-elf.

Debugging with Visual Studio Code

As part of testing GDB in the previous post, I checked to see if I could also debug the CH32V103R Mini Evaluation board with Visual Studio Code.

After installing Visual Studio Code, I added the Native Debug extension by WebFreak. This extension is mandatory for the following process.

At first, I saved a workspace of Visual Studio Code into the ch32v103/EVT/EXAM/EXTI/EXTI0/User/ directory that I used in the previous post and added this directory to the workspace also. Then I created a launch.json file by clicking create a launch.json file(1), (2) and selecting the GDB(3) item.

I replaced the contents of the created JSON file with the following.

{
	"folders": [],
	"launch": {
		"version": "0.2.0",
		"configurations": [
			{
				"name": "OpenOCD",
				"type": "gdb",
				"request": "attach",
				"executable": "exiti0.elf",
				"remote": true,
				"target": ":3333",
				"cwd": "${workspaceRoot}",
				"gdbpath": "riscv32-unknown-elf-gdb",
				"autorun": [
					"set mem inaccessible-by-default off",
					"set architecture riscv:rv32",
					"set remotetimeout unlimited",
					"interrupt",
					"monitor reset halt",
					"load"
				]
			}
		]
	}
}

Before starting the debugging with Visual Studio Code, I ran the openocd in a different terminal.

sudo ./openocd -f wch-riscv.cfg

I set a breakpoint in main.c and started debugging by selecting the Start Debugging (F5) item under the Run menu.

One thing I noticed is that Restart (Ctrl+Shift F5) and Disconnect (Shift+F5) didn’t work properly. I saw that openocd outputted libusb-related errors after those two commands. I was able to start debugging again by restarting the openocd process and selecting Start Debugging (F5). Other than those two it looked that debugging on Visual Studio Code worked as expected.

[Added on 2022-06-24]
I wrote a new blog that addressed how to solve Restart (Ctrl+Shift F5) and Disconnect (Shift+F5) operation issue in the above. Please check my new post in addition to this entry.

Testing the toolchain – GDB

As a final step of testing the toolchain, I tried GDB with the CH32V103R Mini Evaluation board. Unfortunately, the binaries that I built in this post didn’t include a binary of the GDB command. Therefore, I rebuilt the toolchain with the following revised ct-ng menuconfig options.

  • In the Target options menu, I enabled the Build a multilib toolchain.
  • In the C-library menu, I selected the newlib as the C library.
  • In the Companion libraries menu, I selected the newlib-nano and enabled the Additionally install newlib-nano libs into TARGET dir option for the newlib-nano.
  • In the Debug facilities menu, I enabled the gdb. (*New)

After removing the previous ${HOME}/x-tools directory, I built the toolchain that includes the GDB command.

sudo apt install python3-distutils python3-dev<br>ct-ng build

Please note that I installed additional python related packages to build GDB with Crosstool-NG.

I tested the riscv32-unknown-elf-gdb using the same CH32V103 example as the previous post. To generate debug information I added -g and -O0 to the GCC options in the Makefile (Here is the updated file).
I ran the openocd separately in a different terminal first as follows.

sudo ./openocd -f wch-riscv.cfg

Then I ran riscv32-unknown-elf-gdb and executed the following commands in the GDB (I typed in the bolded part).

nc-pin$ riscv32-unknown-elf-gdb
GNU gdb (crosstool-NG 1.25.0_rc2.1_7e21141) 11.2
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "--host=x86_64-build_pc-linux-gnu --target=riscv32-unknown-elf".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word".
(gdb) set mem inaccessible-by-default off
(gdb) set architecture riscv:rv32
The target architecture is set to "riscv:rv32".
(gdb) set remotetimeout unlimited
(gdb) file exiti0.elf
Reading symbols from exiti0.elf...
(gdb) target extended-remote :3333
Remote debugging using :3333
HardFault_Handler () at ch32v10x_it.c:40
40	    while(1)
(gdb) load exiti0.elf
Loading section .init, size 0x38 lma 0x0
Loading section .vector, size 0x108 lma 0x38
Loading section .text, size 0x2a60 lma 0x140
Loading section .data, size 0x84 lma 0x2ba0
Start address 0x00000000, load size 11300
Transfer rate: 4 KB/sec, 2825 bytes/write.
(gdb) 

Then I set a breakpoint at line 73 of the main.c and let the GDB continue to the breakpoint.

 (gdb) break main.c:73
Breakpoint 1 at 0x17f6: file main.c, line 73.
Note: automatically using hardware breakpoints for read-only addresses.
(gdb) cont
Continuing.

Breakpoint 1, main () at main.c:73
Python Exception <class 'UnicodeDecodeError'>: 'utf-8' codec can't decode byte 0xcd in position 449: invalid continuation byte
73	    printf("EXTI0 Test\r\n");
(gdb)

After inputting the cont command to the GDB, I saw the output of printf("SystemClk:%d\r\n", SystemCoreClock); at line 71 of the main.c on the UART connection from the CH32V103. I also tried several next commands.

(gdb) next
78	        Delay_Ms(1000);
(gdb) next
79	        printf("Run at main\r\n");
(gdb) next
78	        Delay_Ms(1000);
(gdb) next
79	        printf("Run at main\r\n");
(gdb) next
78	        Delay_Ms(1000);
(gdb)

This time I just tried the limited number of the GDB commands. However, it looked that the GDB I built was working as expected.