Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ptr_munge in the apple argument to main?

Tags:

c

macos

I was recently looking into additional arguments to main and I found that apart from argc, argv and envp on macOS there is also an extra char **apple option.

Obviously the first thing I did was quickly loop over it:

int main(int argc, char ** argv, char ** envp, char ** apple)
{
    puts("-----------------Apple-----------------");
    for(char **a = apple; *a != 0; a++)
    {
        printf("%s\n", *a);
    }
    return 0;
}

and see what was in there which was:

-----------------Apple-----------------
executable_path=bin/apple



ptr_munge=
main_stack=
executable_file=0x1901000004,0x2ea3d0
dyld_file=0x1901000004,0xab575

Assuming they're not totally misleading names I can guess what the rest of them are but I was a bit stumped by ptr_munge - what is that and what can be done with it? (Also what's all the extra whitespace there for?)

EDIT:

OK I found this file: kern_exec.c which contains this:

/*
 * libplatform needs a random pointer-obfuscation value when it is initialized.
 */
#define PTR_MUNGE_VALUES 1
#define PTR_MUNGE_KEY "ptr_munge="
...
/*
* Supply libpthread & libplatform with a random value to use for pointer
* obfuscation.
*/
error = exec_add_entropy_key(imgp, PTR_MUNGE_KEY, PTR_MUNGE_VALUES, FALSE);
if (error) {
    goto bad;
}
imgp->ip_applec++;

So I am still pretty unsure what that means in context (there's nothing in my one) but I can follow this thread.

like image 825
AsksStupidQuestions Avatar asked Mar 08 '19 21:03

AsksStupidQuestions


1 Answers

It appears that it's used to obfuscate the register values stored in jmp_buf by _setjmp() (and then to restore them in _longjmp()). It's presumably a security/data-privacy feature. It seems to have been introduced with 10.14. It isn't in the 10.13.x code.

See the code here, for example:

LEAF(__setjmp, 0)
    // %rdi is a jmp_buf (struct sigcontext *)

    // now build sigcontext
    movq    %rbx, JB_RBX(%rdi)
    movq    %rbp, %rax
    _OS_PTR_MUNGE(%rax)
    movq    %rax, JB_RBP(%rdi)
    movq    %r12, JB_R12(%rdi)
    movq    %r13, JB_R13(%rdi)
    movq    %r14, JB_R14(%rdi)
    movq    %r15, JB_R15(%rdi)

    // RIP is set to the frame return address value
    movq    (%rsp), %rax
    _OS_PTR_MUNGE(%rax)
    movq    %rax, JB_RIP(%rdi)
    // RSP is set to the frame return address plus 8
    leaq    8(%rsp), %rax
    _OS_PTR_MUNGE(%rax)
    movq    %rax, JB_RSP(%rdi)

    // save fp control word
    fnstcw  JB_FPCONTROL(%rdi)

    // save MXCSR
    stmxcsr JB_MXCSR(%rdi)

    // return 0
    xorl    %eax, %eax
    ret
like image 132
Ken Thomases Avatar answered Oct 20 '22 13:10

Ken Thomases