/* =============================================================================
 * psem.c -- implementation of the portable semaphore (see psem.h for the why)
 * =============================================================================
 */
#include "psem.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int psem_init(psem_t *s, unsigned value)
{
#ifdef __APPLE__
    /* macOS: sem_init() exists but always fails with ENOSYS. Use a NAMED
       semaphore instead, with a name unique to this process and this call. */
    static int counter = 0;
    char name[64];
    snprintf(name, sizeof(name), "/psem.%d.%d", (int)getpid(), counter++);

    /* O_EXCL so we never silently adopt a stale semaphore left by a crash. */
    s->sp = sem_open(name, O_CREAT | O_EXCL, 0600, value);
    if (s->sp == SEM_FAILED) {
        fprintf(stderr, "psem_init: sem_open(%s): %s\n", name, strerror(errno));
        return -1;
    }

    /* Unlink the NAME at once. Our open handle keeps working (POSIX: the
       semaphore survives until every holder closes it), but it is no longer
       visible system-wide, so it cannot leak or collide -- exactly the
       behaviour of an unnamed semaphore. */
    if (sem_unlink(name) != 0)
        fprintf(stderr, "psem_init: sem_unlink(%s): %s\n", name, strerror(errno));
    return 0;
#else
    /* Everywhere else: the ordinary unnamed semaphore CS:APP uses.
       The middle argument 0 means "shared between threads of one process". */
    if (sem_init(&s->storage, 0, value) != 0) {
        fprintf(stderr, "psem_init: sem_init: %s\n", strerror(errno));
        return -1;
    }
    s->sp = &s->storage;
    return 0;
#endif
}

void psem_P(psem_t *s)
{
    /* [Edge cases] sem_wait can return -1 with EINTR if a signal arrives
       (Lecture 17). "Interrupted" is not "acquired", so we must retry --
       returning here would let the caller into the critical section without
       holding the semaphore. */
    while (sem_wait(s->sp) != 0) {
        if (errno == EINTR)
            continue;
        perror("psem_P: sem_wait");
        exit(1);
    }
}

void psem_V(psem_t *s)
{
    if (sem_post(s->sp) != 0) {
        perror("psem_V: sem_post");
        exit(1);
    }
}

void psem_destroy(psem_t *s)
{
#ifdef __APPLE__
    sem_close(s->sp);           /* the name is already unlinked */
#else
    sem_destroy(&s->storage);
#endif
    s->sp = NULL;
}

const char *psem_backend(void)
{
#ifdef __APPLE__
    return "named POSIX semaphores (sem_open + immediate sem_unlink); "
           "macOS sem_init() is a stub that fails with ENOSYS";
#else
    return "unnamed POSIX semaphores (sem_init), as in CS:APP";
#endif
}
