As usual, attention to detail was the issue. I saw that g++ --version reported clang, but I didn’t think about it enough. I had assumed that GDB was the problem, not my compiler. I’m not sure why Apple linked g++ to clang++, since that’s quite misleading. This little oversight made me spend 8 months writing C++ on my phone (vi on a 60-character wide display is not my ideal IDE).

What I did to get real g++:

  1. Install gcc with Homebrew

  2. Soft-link (ln -s) gcc-11 and g++-11 from /usr/local/Cellar/ to /usr/local/bin/

  3. unhash (at least in zsh) gcc and g++, or else gcc will continue to expand to /usr/bin/clang

GDB is working great now.

Answer from tjcaul on Stack Exchange
Top answer
1 of 2
1

The compilers on macOS are confusing. Apple supplies the LLVM compiler as part of Xcode, but it provides a stub at /usr/bin/g++ which leads people to believe they are using GCC, i.e. the GNU Compiler Collection. They then try to use gdb, i.e. the GNU Debugger with the LLVM-produced executables and find it doesn't work.

IMHO, you either need to use wholly Apple-supplied tools, or wholly GNU-supplied tools.


So, let's look at the first option - using Apple tools. In this case you compile with:

/usr/bin/g++ -g main.cpp -o main

and debug with:

/usr/bin/lldb ./main

and the debugger commands seem pretty similar to GDB.


The second option is using GCC and GDB which are normally best installed using homebrew. The installation commands are:

brew install gcc
brew install gdb

Then you will compile with something like:

/usr/local/bin/g++-8 -g main.cpp -o main

and debug with something like:

/usr/local/bin/gdb ./main

However, I cannot get this to work on macOS Mojave for the moment! I read here that GDB v8.1 doesn't work on macOS and you need to install v8.0.1 instead but cannot seem to do that with homebrew.

2 of 2
0

you can build binutils by yourself

git clone https://sourceware.org/git/binutils-gdb.git

and then use homebrew to install gcc

brew install gcc

remind to use gcc to build it

export PATH=/opt/homebrew/Cellar/gcc/13.2.0/bin:$PATH
export CC=gcc-13
export CXX=g++-13
export LDFLAGS=-Wl,ld_classic

make sure to use this ld_classic flags, dont know the exact reason, but it works on Macos Sonoma.

🌐
UCI ICS
ics.uci.edu › ~pattis › common › handouts › macmingweclipse › allexperimental › mac-gdb-install.html
ICS 46: GDB Installation on Mac OS X
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).
🌐
GitHub
gist.github.com › mike-myers-tob › 9a6013124bad7ff074d3297db2c98247
Steps to get GDB actually working in April 2021 on macOS (Intel x86-64 only) · GitHub
Do not report this issue to Homebrew/brew or Homebrew/homebrew-core! These open issues may also help: gdb start two threads and the former has to be sent SIGINT(Ctrl + C) domq/homebrew-gdb#3 · (Edit: and yeah i know that apple and homebrew dropped macos 11 support a long long time ago, but I don't have any alternative devices at the moment and it would be fine if i could launch gdb debugger on my old macos.)
🌐
Super User
superuser.com › questions › 1662649 › gdb-hangs-after-new-thread-on-macos
mac - GDB Hangs after “New Thread” on macOS - Super User
Kill and re-run gdb repeatedly. Try different binaries. ... Add more breakpoints. ... I do not get taskgated / Mach Port errors; only the New Thread message. I realize that this is a near-duplicate of this, but I didn't see a working answer ...
Top answer
1 of 2
7

Are you positive you are in the Developer Tools group?

Try running this command

sudo dscl . append /Groups/_developer GroupMembership <username>

That should add your user account to the group.

2 of 2
2

I had the same problem, it wouldn't run, except as root/sudo, which meant I couldn't use it with eclipse, which meant I lost 5 working hours debugging the problem. Here are my results.

Firstly, gdb generated a similar error message when executed under my user account.

Unable to find Mach task port for process-id 4667: (os/kern) failure (0x5).
 (please check gdb is codesigned - see taskgated(8))

I tried code signing it by creating a certificate using Keychain, then marking the certificate as trusted for code signing. Then applying it to the executable from the command line.

codesign -s gdb-cert /usr/local/Cellar/gdb/7.6.1/bin/gdb
codesign --verify --verbose  /usr/local/Cellar/gdb/7.6.1/bin/gdb
codesign -d --verbose  /usr/local/Cellar/gdb/7.6.1/bin/gdb

That didn’t work

I tried adding my user account to the procview, procmod, and _developer groups (probably insecure, but I only deploy my code to github, and don't use the machine for personal use, so I can live with that)

sudo dscl . append /Groups/procmod GroupMembership bryanhunt

sudo dscl . append /Groups/procview GroupMembership bryanhunt

sudo dscl . append /Groups/_developer GroupMembership bryanhunt

That didn't work

Finally, I tried changing the executable's group and group sticky bit.

sudo chgrp procmod /usr/local/Cellar/gdb/7.6.1/bin/gdb
sudo chmod g+s /usr/local/Cellar/gdb/7.6.1/bin/gdb

That worked

🌐
GitHub
gist.github.com › danisfermi › 17d6c0078a2fd4c6ee818c954d2de13c
Setup gdb on Mac OS Sierra/High Sierra · GitHub
Explanation: This is due to dyld cache. When system libraries are loaded from cache, their segments are split in groups: first all __TEXT segments, then all __DATA segments, etc (this can be seen in vmmap --interleaved).
🌐
Reddit
reddit.com › r/c_programming › online gdb doesn't work as expected?
r/C_Programming on Reddit: Online GDB doesn't work as expected?
December 2, 2021 -

I am posting this both on r/Assembly_Language and here. I think the topic involves both fairly strongly.

So, I am going to do a presentation involving buffer overflows and I learned some basic Assembly because of that (more specifically the function prologue). I plan on learning Assembly for real and have installed SASM, but for now I just know basic C. I need help reading something.

In one of my sources (https://www.tenouk.com/Bufferoverflowc/Bufferoverflow4.html), this guy does disass in his vulnerable function in order to show that sub has allocated more space than he declared (4 vs 20).

This is his code:

#include <unistd.h>

 

void Test()

{

   char buff[4];

   printf("Some input: ");

   gets(buff);

   puts(buff);

}

 

int main(int argc, char *argv[ ])

{

   Test();

   return 0;

}

And this is the output of disass Test:

0x080483d0 <Test+0>:    push   %ebp

0x080483d1 <Test+1>:    mov    %esp, %ebp

0x080483d3 <Test+3>:    sub    $0x8, %esp

0x080483d6 <Test+6>:    sub    $0xc, %esp

Buff is 4 bytes and 20 bytes are "freed" on the stack. But when I try to do the same with a relatively more complicated function (I hope commentary is enough for the language gap):

#include <stdio.h>
#include <string.h>
#include <locale.h>     
#include <stdlib.h>        

void senha(){      
 char senha[10];           
    char senhareal[10]="dddddd";      
    int teste = 0;    
    char resposta[3]; 
    
    printf("\n\n\n\n-----------------------------SISTEMA NUCLEAR DA OTAN------------------------------------ \n\n\n\n");     
    
    
    printf("DIGITE SUA SENHA: ");
    gets(senha);


    if(0 == strncmp(senha, senhareal, 20))
    {
         printf ("\nSenha correta! \n");
         teste = 1;    
    }
    
    
    else
    {
        printf ("\nSENHA INCORRETA! \n");
    }


    if(teste)
    {
        printf ("\nO usuário agora controla a instalação! Deseja destruir o Brasil? \n");     
        gets(resposta); 
    }
            }

int main(){               
    system("color 03");
	setlocale(LC_ALL, "Portuguese"); 
    senha();  

    return 0;
}

I get this:

0x0000555555555209 <+0>: endbr64
0x000055555555520d <+4>: push %rbp
0x000055555555520e <+5>: mov %rsp,%rbp
0x0000555555555211 <+8>: sub $0x30,%rsp
0x0000555555555215 <+12>: mov %fs:0x28,%rax
0x000055555555521e <+21>: mov %rax,-0x8(%rbp)

No matter my input. So why does Online GDB consistently subtract 48 bytes? What are the instructions following sub and do they apply at all to what I am trying to do? Is it possible to know what's going on in that specific platform? Finally, am I unable to replicate what this person did with my code?

I tested the code of my source in Online GDB as well. It consistently subtracts 16 bytes.

Find elsewhere
🌐
Reddit
reddit.com › r/c_programming › does installing gdb on a mac usually take a while? or is it only me?
r/C_Programming on Reddit: Does installing GDB on a mac usually take a while? or is it only me?
April 13, 2024 - Otherwise, use lldb of the default tools… however, other IDEs do not seem to all be ready to operate with it Continue this thread Continue this thread ... Thanks for the info. I am using LLDB. It is working well! ... It takes forever for Apple Silicon users unless you install JetBrains CLion and harvest the gdb build from there. It's ridiculous it took all these years to get it. ... Don't buy mac if you want to do anything beyond browsing the web and doing some basic video editing - a big fuckin' waste of money for us, coding apes ....
🌐
Reddit
reddit.com › r/cpp_questions › gdb not working
r/cpp_questions on Reddit: gdb not working
November 20, 2020 -

I recently downloaded cygwin and the gdb and gdb-debuginfo packages (ver. 9.2-1) contained there. When I run gdb --version I only get a blank line in the terminal. Using cygcheck gdb says the status is okay and the version is correct. Trying something like g++ --version outputs the correct version. Trying to run gdb, even without arguments, it freezes and I have to kill the process. Any ideas how to get gdb working?

Top answer
1 of 2
3

Whoops you have an infinite loop here

//This creates a LCV for the do loop below and sets it equal to 0.

int y = 0;

//This do loop generates the random number.
do
{
    //This generates a random time seed.
    srand(time(0));

    //This generates a random number between 1 and 99.
    ran = rand() % 100;

    //This while controls the do loop.
}while (y != 9);

y is initialized to 0 and you are looping while y!=9. And that is just the first error, there might be more.


Bug #2

int z = 1;
//This makes the program only create a random number the first pass through the loop.
if (z < 2)
{
    //This runs the random number generator function.
    return randomgen();

    //This sets the result of the function as the random number.
    randnum = randomgen();

    //This sets the random number to the current number.
    num = randnum;
}

After fixing infinite loop in randomgen(), You are immediately returning...

2 of 2
1

you have two problems in your code: the first one is that you have infinite loop in randomgen() function the condition in check against y - y != 9 but the value never update

int randomgen() 
{
    //This creates a variable to store the random number.
    int ran;

    //This creates a LCV for the do loop below and sets it equal to 0.
    int y = 0;

    //This do loop generates the random number.
    do
    {
        //This generates a random time seed.
        srand(time(0));

        //This generates a random number between 1 and 99.
        ran = rand() % 100;

        //This while controls the do loop.
    }while (y != 9);

    //This returns the random number for use in the rest of the program.
    return ran;
}

and the second one is even if you pass the loop in the function you exit main right away because the call to the function randomgen() is with return

if (z < 2)
{
    //This runs the random number generator function.
    return randomgen(); <-- **second problome**

    //This sets the result of the function as the random number.
    randnum = randomgen();

    //This sets the random number to the current number.
    num = randnum;
}
🌐
GitHub
github.com › microsoft › vscode-cpptools › issues › 5256
GDB not working on OSX Mojave · Issue #5256 · microsoft/vscode-cpptools
"configurations": [ { "name": "(GDB) Launch Mac", "type": "cppdbg", "request": "launch", "program": "/Users/sam/Documents/my_examples/GDB/objs/ShapeType_publisher", "osx": { "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "setupCommands": [ { "ignoreFailures": true } ] }, } ]
🌐
Stack Overflow
stackoverflow.com › questions › 30395373 › cant-seem-to-get-gdb-working-on-my-mac
macos - Can't seem to get gdb working on my mac - Stack Overflow
(gdb) r Starting program: /Users/home/CTCI-C/Chapter1/1.1/src warning: Could not open OSO archive file "/BinaryCache/corecrypto/corecrypto-233.1.2~26/Symbols/BuiltProducts/libcorecrypto_static.a" warning: `/BinaryCache/coreTLS/coreTLS-35.20.2~10/Objects/coretls.build/coretls.build/Objects-normal/x86_64/system_coretls_vers.o': can't open to read symbols: No such file or directory. warning: Could not open OSO archive file "/BinaryCache/coreTLS/coreTLS-35.20.2~10/Symbols/BuiltProducts/libcoretls_ciphersuites.a" warning: Could not open OSO archive file "/BinaryCache/coreTLS/coreTLS-35.20.2~10/Symb
🌐
Cohost
cohost.org › sdave-b › post › 1560910-how-to-get-gdb-to-wo
cohost! - "How to get GDB to work on macOS Ventura"
May 26, 2023 - Every time I want to use the 'classic' GNU Debugger on macOS, I always run into the same hurdle, where the system security does not allow a userspace process to inspect the memory of another running user-space process. Each and every time the binary gets updated by homebrew, I have to do some internet searching to figure out the magical incantation to codesign gdb ...
🌐
Medium
medium.com › @AI_and_Blockchain › how-to-get-gdb-running-on-macos-with-arm-chips-using-qemu-ff9041d6f380
How to Get GDB Running on macOS with ARM Chips Using QEMU | by AI_and_Blockchain | Medium
December 13, 2023 - Unfortunately, GDB doesn’t run natively on macOS with these chips, and LLDB, the default debugger on macOS, doesn’t support the 32-bit RISC-V architecture. Don’t worry, though! There’s a workaround using QEMU, a machine emulator and virtualizer.
🌐
Apple Community
discussions.apple.com › thread › 253272158
gdb compiler - Apple Community
I’d expect gdb to install with gcc, so (if this is not already what you are trying) try installing gcc:
🌐
GitHub
github.com › Homebrew › homebrew-core › issues › 108309
gdb installation does not work on Mac M1 machines. · Issue #108309 · Homebrew/homebrew-core
May 4, 2022 - brew gist-logs link OR brew config AND brew doctor output $ brew config HOMEBREW_VERSION: 3.5.9 ORIGIN: https://github.com/Homebrew/brew HEAD: 3748bed378401ed75abdf32bcb3d2674d854a6...
Published   Aug 17, 2022