- Как установить gdb (debugger) в Mac OSX El Capitan?
- 8 ответов
- Вариант 1: подписания бинарными
- Альтернатива 2: Используйте устаревшую опцию для taskgated
- GDB Installation on Mac OS X
- Installing GDB
- Creating a Certificate
- Signing GDB
- Configuring Eclipse
- Install Gdb Mac Setup gdb on macOS in 2020
- Table of Contents
- Install gdb
- Generate a certificate
- Sign certificate for gdb
- Create a gdb command file
- Generating builds
Как установить gdb (debugger) в Mac OSX El Capitan?
Как установить gdb (отладчик) в Mac OSX El Capitan ? Я попытался установить gdb, но потерпел неудачу пару раз.
я следовал этому URL:http://ntraft.com/installing-gdb-on-os-x-mavericks/, MAC не позволяет устанавливать MacPorts.
может ли кто-нибудь помочь мне в этом отношении.
8 ответов
существует два решения проблемы, и они оба упомянуты в других ответах на этот вопрос и как заставить gdb работать с помощью macports под OSX 10.11 El Capitan?, но чтобы прояснить некоторую путаницу, вот мое резюме (как ответ, так как он получил немного длинный комментарий):
какая альтернатива более безопасна, я думаю, сводится к выбору между 1) доверяя самозаверяющим сертификатам и 2) предоставляя пользователям больше преференции.
Вариант 1: подписания бинарными
если используется альтернатива подписи, отключение SIP для добавления опции-p в taskgated не требуется.
обратите внимание, что с этой альтернативой, отладка разрешена только для пользователей _developer группа.
использование codesign для подписи с помощью сертификата с именем gdb-cert :
codesign -s gdb-cert /opt/local/bin/ggdb
(используя MacPorts стандартный путь, принять по мере необходимости)
обратите внимание, что вы нужно перезапустить приложение keychain и служба taskgated во время и после процесса (самый простой способ — перезагрузить.)
Альтернатива 2: Используйте устаревшую опцию для taskgated
в соответствии с ответом @user14241, отключив SIP и добавив опцию-p в taskgated вариант. Обратите внимание, что при использовании этой опции, подписание двоичного файла не требуется, а также обходит диалог проверки подлинности в качестве члена группы инструментов разработчика ( _developer ).
после добавления опции-p (разрешить группы procmod и procview) в taskgated вам также необходимо добавьте пользователей, которым должно быть разрешено использовать gdb в группу procmod.
перезагрузить в режиме восстановления, откройте терминал и выполните команду csrutil disable
перезагрузите машину и отредактируйте /System/Library/LaunchDaemons/com.apple.taskgated.plist , добавив the -p opion:
перезагрузка в режиме восстановления для повторного использования SIP ( csrutil enable )
перезагрузите машину и добавьте пользователя USERNAME для группа procmod :
sudo dseditgroup -o edit -a USERNAME -t user procmod
альтернатива это не включает добавление пользователей в группы-это сделайте исполняемый файл setgid procmod, что составляет procmod эффективный идентификатор группы любого пользователя, выполняющего двоичный файл setgid (предлагается в https://apple.stackexchange.com/a/112132)
Сначала установите Homebrew:
/usr/bin/ruby -e «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)»
запустите этого : brew install gdb
Это не обязательно решает вопрос, но если вы используете Mac OS X, то вы, вероятно, можете использовать lldb Домашняя страница LLDB . Это очень похоже на gdb и даже руководство по использованию команд, которые вы используете на gdb .
вот сообщение в блоге объясняет это очень хорошо:
и то, как я заставляю его работать:
создайте сертификат подписи кодирования через Открыть Брелок:
1.1 в меню выберите связка > сертификат помощника > создать сертификат.
1.2 следуйте указаниям мастера, чтобы создать сертификат и назовем его gdb.cert тип личности Самоподписанный Корень, а тип сертификата —Подписывание Кода и выберите Let Me override defaults.
1.3 нажмите несколько раз на Далее, пока не дойдете до укажите местоположение для экрана сертификата, затем установите брелок to система.
установить gdb через Homebrew: brew install gdb
перезагрузка taskgated : sudo killall taskgated && exit
откройте окно терминала и введите sudo codesign -vfs gdb.cert /usr/local/bin/gdb
на моем Mac OS X El Capitan я использую homebrew для установки gdb:
затем я следую инструкции здесь:https://sourceware.org/gdb/wiki/BuildingOnDarwin, в разделе 2.1. Метод для Mac OS X 10.5 (Leopard) и более поздних версий.
как только вы получите версию macports gdb установлен вам нужно будет отключить SIP, чтобы сделать правильные изменения в /System/Library/LaunchDaemons/com.apple.taskgated.plist . Чтобы отключить SIP, необходимо перезагрузиться в режиме восстановления и выполнить следующую команду:
перезагрузите. Затем вам нужно будет отредактировать нижнюю часть com.apple.taskgated.plist такой:
тогда вам придется перезапустить, чтобы изменения вступили в силу. Тогда вы должны reenable глоток. The для установка macports на самом деле ggdb . Вам нужно будет код sign ggdb следуя инструкциям здесь:
единственный способ заставить подпись кода работать-это запустить ggdb С sudo . Удачи!
кажется, что MacPorts может быть установлен в El Capitan прямо сейчас: https://www.macports.org/install.php Тогда вы, вероятно, можете установить gdb по ссылке, которую вы упомянули.
просто потратил несколько дней, пытаясь заставить это работать на High Sierra 10.13.1. Версия gdb 8.1 от homebrew не будет работать независимо от того, что я пытался. Закончилась установка gdb 8.0.1 через macports, и это чудесным образом сработало (после прыжка через все другие необходимые обручи, связанные с кодовым дизайном и т. д.).
одна дополнительная проблема заключается в том, что в Eclipse вы получите посторонние одинарные кавычки вокруг всех ваших аргументов программы, которые можно обойти, предоставив споры внутри .вместо этого gdbinit.
Источник
GDB Installation on Mac OS X
If you work on a Mac OS X 10.9 Mavericks or later, you will run into the problem of Eclipse refusing to interactively debug problems that otherwise build and run fine: An attempt to start a debugging session by selecting Run
Debug from the menu will result in Eclipse complaining that an Error with command: gdb —version has occurred.
The problem is caused by Apple switching away from GDB, the GNU debugger, to LLDB, the LLVM debugger, in their Xcode toolchain (along with the transition from GCC to Clang). Unfortunately, Eclipse is not capable of communicating with any debugger other than GDB (yet). Here is a step-by-step guide for installing and configuring GDB.
Installing GDB
As with GCC, the easiest way to install GDB is through Homebrew. In a Terminal window, run the command brew install gdb , and wait for it to complete. (As usual, it may ask for your password.)
Now, we need to code-sign the GDB executable, so it will be allowed to control other processes, as necessary for a debugger. For that, we will first create a new certificate in Keychain.
Creating a Certificate
Open the Keychain Access application (can be found in Applications/Utilities directory or through Spotlight). Select Certificate Assistant
Create a Certificate in the application menu ( Keychain Access ). An assistant window will appear for guiding you through the process.
- First, you will be asked for the name and type of the certificate. You may choose the name arbitrarily, but to simplify its future use in command line, prefer names without spaces or other fancy characters, e.g., gdbcert .
- Make sure that Identity Type is set to Self Signed Root , change Certificate Type to Code Signing , check the Let me override defaults checkbox, and click Continue . Click Continue again in the popup prompt warning about the certificate being self-signed.
- On the next page, leave Security Number to be 1, and set Validity Period to a large enough number of days to cover the duration of the class or more, say, 365. (Certificates cannot last forever; the maximum validity period is 20 years.)
- Then click Continue once again, and keep doing so to skip the next six screens until you see the one entitled Specify a Location For The Certificate . For the only property, Keychain , choose System from the drop-down list. Lastly, click Create , type in your password, if prompted, and click Done .
- Back in the main window, choose the System keychain in the sidebar on the left, and select the newly created certificate from the list. Open the context menu and select Get Info . In the information window that will appear, expand the Trust section and set the Code Signing property to Always Trust . Close this window (you may be asked for your password), and quit Keychain Access.
Signing GDB
Our new certificate is now ready to be used. In order to make it immediately available for signing, we need to restart the Taskgate access-control service. You can use Activity Monitor to do this (also found in Applications/Utilities). Open it and filter the list of processes by typing taskgated in the search field in the toolbar. (If you cannot find it, make sure the menu item View
All Processes is checked.)
There should be exactly one process left in the list. Highlight it, then select View
Quit Process from the menu, and click Quit in the popup prompt. The Taskgate process will be terminated and, consequently, should disappear from the list. In a few seconds, it will be restarted by the system and should reappear in the list. Please wait for this to happen (it may take up to a minute or two, at worst).
Finally, in a Terminal window, run codesign -s gdbcert /usr/local/bin/gdb (if you named your certificate differently, replace gdbcert with its name here). Once again, you will be prompted for you username and password. If the command does not produce any output, then GDB is successfully signed.
Configuring Eclipse
The only thing left to do is to point Eclipse to the GDB executable. Open Eclipse
Preferences from the main menu (not to be confused with Project Preferences ). In the tree of options listed in the sidebar, navigate to C/C++
Debug
GDB , and set the GDB debugger field to /usr/local/bin/gdb .
If there is no GDB section in the C/C++
Debug subtree, close the preferences window, and try to first start a debugging session for any project that you can already run without problems. You can do it by either clicking the Debug button on the toolbar, or selecting Run
Debug from the main menu. This attempt will, of course, fail with an error message about the gdb command, but it will force the said C/C++
Debug
GDB settings to appear in the preferences.
This will change the GDB executable for new projects; for all existing ones (that you are going to use debugging for), you will need to manually update their debug configurations. To do that, select Run
Debug Configurations from the menu. In the window that appears, one after another, select every project under the C++ Application section in the sidebar. For each of them, open the Debugger tab, set the GDB debugger field to the same path /usr/local/bin/gdb , and click the Apply button. After repeating this change for all listed projects, click Close .
If the above steps do not solve the issue on your machine, or you encounter a problem while following them, please do not hesitate to come to one of the upcoming common labs for help.
Источник
Install Gdb Mac Setup gdb on macOS in 2020
Beginning with Mavericks (macOS 10.9) Xcode stopped supporting the gdb debugger. Below are steps to walk you through solving this not-so-straightforward problem.
Table of Contents
Install gdb
Open the Terminal app, Applications > Utilities > Terminal. This guide uses the Terminal throughout, so it’s best to leave it open until you have finished all of the steps.
If you don’t already have gdb on your system, then you’ll need to install it. I’m going to show you how to install gdb by using Homebrew.
Start by verifying whether you already have gdb installed on your system. Type the following in Terminal:
Exit fullscreen mode
If you have gdb on your system already, you can skip to the Generate a certificate step. If you received an error, then you’ll need to install gdb using Homebrew.
Verify whether or not you have Homebrew by typing:
Exit fullscreen mode
If Homebrew isn’t already installed on your system, you’ll need to install it. Using Terminal, type (or copy and paste) the following command:
Exit fullscreen mode
Once Homebrew is installed, you can install gdb. The current version of gdb as of this writing is 9.2, which is confirmed working on Catalina as of Sept. 2020.
In order to install gdb type the command:
Exit fullscreen mode
You can confirm whether gdb is installed properly by running:
Exit fullscreen mode
If everything went well then you’re ready to move on to the next step!
Generate a certificate
If it was as simple as installing gdb, I wouldn’t have made this guide! If you attempt to debug a file now, you will get errors and unexpected behavior because the Darwin kernel does not allow gdb to control another process without having special rights. Fortunately the rest of this guide walks you through all of the steps you’ll need in order to use gdb effectively on your Mac.
In order to give gdb the permissions it needs, you’ll need to generate a self-signed certificate.
Here are the steps:
- Launch Keychain Access application: Applications > Utilities > Keychain Access.
- From the Keychains list on the left, right-click on the System item and select Unlock Keychain «System».
- From the toolbar, go to Keychain Access > Certificate Assistant > Create a Certificate.
- Choose a name (e.g. gdb-cert).
- Set Identity Type to Self Signed Root.
- Set Certificate Type to Code Signing.
- Check the Let me override defaults checkbox.
- At this point, you can go on with the installation process until you get the Specify a Location For The Certificate dialogue box. Here you need to set Keychain to System. Finally, you can click on the Create button.
- After these steps, you can see the new certificate under System keychains. From the contextual menu of the newly created certificate (right-click on it) select the Get info option. In the dialogue box, expand the Trust item and set Code signing to Always Trust.
- Then, from the Keychains list on the left, right-click on the System item and select Lock Keychain «System».
- Finally, reboot your system.
Sign certificate for gdb
Now you’ll need to sign the certificate. Create a file called gdb-entitlement.xml. This allows macOS to trust gdb operations for debugging. Type the following into the xml file you just created, and save it:
Exit fullscreen mode
Now back in the Terminal app, navigate to the directory where you saved the xml file.
*note. in the following command is your path to gdb. It will be something like
/usr/local/Cellar/gdb/version/bin/gdb
or
/usr/local/bin/gdb.
You can find out for sure by typing the following in the terminal:
Exit fullscreen mode
Replace with your path to gdb.
Exit fullscreen mode
where gdb-cert is the name of the certificate you created earlier, and gdbPath is the full path to your gdb binary file.
Create a gdb command file
For this step, do one of the following.
Either:
- In the home directory, create a new file called .gdbinit. Write the following command into it and save:
Exit fullscreen mode
- Type the following into the Terminal:
Exit fullscreen mode
Generating builds
We’re almost there! If you tried debugging with gdb now, you would likely receive a «No symbol table is loaded» error. In order to solve this, you’ll need to compile programs with the -ggdb option, as in the following example:
Exit fullscreen mode
At this point you should be able to successfully debug your programs on Mac using gdb. Do a test by running (for example):
Exit fullscreen mode
and then from the gdb prompt, try creating a breakpoint:
Exit fullscreen mode
You should see something like the following:
Exit fullscreen mode
I hope you’re seeing the results you expected! Leave a comment and let me know how it goes!
Источник