Solomon
Solomon

Reputation: 1

Questions on tls.offset calculation in musl libc

I am reading musl libc source code. In load_library function in ldso/dynlink.c, I noticed a formula calculating p->tls.offset, here is the snippet:

#ifdef TLS_ABOVE_TP
        p->tls.offset = tls_offset + ( (p->tls.align-1) &
            (-tls_offset + (uintptr_t)p->tls.image) );
        tls_offset = p->tls.offset + p->tls.size;
#else
        tls_offset += p->tls.size + p->tls.align - 1;
        tls_offset -= (tls_offset + (uintptr_t)p->tls.image)
            & (p->tls.align-1);
        p->tls.offset = tls_offset;
#endif

Macro TLS_ABOVE_TP is defined, so the actual calculation should be

p->tls.offset = tls_offset + ( (p->tls.align-1) &
            (-tls_offset + (uintptr_t)p->tls.image) );

I don't get the logic behind this formula. If it just make sure p->tls.offset is aligned with p->tls.align, why dont this formula?

p->tls.offset = (tls_offset + p->tls.align-1) & -p->tls.align;

I tried to google this kind of formula, but failed to find a answer. Could anybody help me understand it? Thanks

Upvotes: 0

Views: 38

Answers (0)

Related Questions