Data-CountMinSketch-Shared

 view release on metacpan or  search on metacpan

cms.h  view on Meta::CPAN

    CmsHeader *hdr = (CmsHeader *)base;
    CmsHandle *h = (CmsHandle *)calloc(1, sizeof(CmsHandle));
    if (!h) {
        munmap(base, map_size);
        if (backing_fd >= 0) close(backing_fd);
        return NULL;
    }
    h->hdr          = hdr;
    h->base         = base;
    /* Derive reader_slots from the trusted fixed layout, not the stored
     * (shared-segment, attacker-mutable) reader_slots_off. validate_header
     * requires reader_slots_off to equal this for any file we open, so this is
     * identical for valid data and never trusts a poisoned offset. */
    h->reader_slots = (CmsReaderSlot *)((uint8_t *)base + cms_layout().reader_slots);
    h->occ          = (uint64_t *)((uint8_t *)base + cms_layout().occ);        /* trusted layout offset */
    h->mmap_size    = map_size;
    h->path         = path ? strdup(path) : NULL;
    h->backing_fd   = backing_fd;
    h->my_slot_idx  = UINT32_MAX;
    return h;
}

/* Validate a mapped header (shared by cms_create reopen and cms_open_fd). */
static inline int cms_validate_header(const CmsHeader *hdr, uint64_t file_size) {
    if (hdr->magic != CMS_MAGIC) return 0;
    if (hdr->version != CMS_VERSION) return 0;
    if (hdr->d < CMS_MIN_D || hdr->d > CMS_MAX_D) return 0;
    if (hdr->w < CMS_MIN_W || hdr->w > CMS_MAX_W) return 0;
    if ((hdr->w & (hdr->w - 1)) != 0) return 0;             /* power of two */
    if (hdr->mask != hdr->w - 1) return 0;
    if (hdr->total_size != file_size) return 0;
    if (hdr->total_size != cms_total_size(hdr->w, hdr->d)) return 0;
    CmsLayout L = cms_layout();
    if (hdr->reader_slots_off != L.reader_slots) return 0;
    if (hdr->counters_off != L.counters) return 0;
    return 1;
}

/* validate args + compute the geometry (w, d).
 *   w = next_pow2(ceil(M_E / epsilon)), floor CMS_MIN_W, cap CMS_MAX_W
 *   d = ceil(log(1 / delta)) clamped to [1, 32] */
static int cms_validate_create_args(double epsilon, double delta,
                                    uint64_t *w_out, uint32_t *d_out, char *errbuf) {
    if (errbuf) errbuf[0] = '\0';
    if (!(epsilon > 0.0 && epsilon < 1.0)) { CMS_ERR("epsilon must be between 0 and 1 (exclusive)"); return 0; }
    if (!(delta > 0.0 && delta < 1.0))     { CMS_ERR("delta must be between 0 and 1 (exclusive)"); return 0; }

    /* w = next_pow2(ceil(e / epsilon)), floor CMS_MIN_W. Reject (don't silently
       clamp) an epsilon so small the column count would exceed the cap, else the
       achieved error bound would be worse than requested (and the mapping huge). */
    double w_opt_d = ceil(M_E / epsilon);
    if (w_opt_d > (double)CMS_MAX_W) { CMS_ERR("epsilon too small for the column cap"); return 0; }
    uint64_t w = cms_next_pow2_u64((uint64_t)w_opt_d);

    /* d = ceil(log(1/delta)) clamped to [1, 32].  Clamp in DOUBLE before the cast:
       a delta below 1/DBL_MAX (~5.6e-309) makes 1.0/delta overflow to +inf, and
       (long)inf is undefined -- on x86-64 it yields INT64_MIN, which the lower
       clamp would then raise to depth 1, handing the caller who asked for the
       STRONGEST guarantee the weakest possible sketch (and differing by
       architecture, since aarch64 saturates the other way). The comparison is
       false for NaN, which therefore also lands on the maximum. */
    double d_d = ceil(log(1.0 / delta));
    long dl = (d_d < (double)CMS_MAX_D) ? (long)d_d : (long)CMS_MAX_D;
    if (dl < CMS_MIN_D) dl = CMS_MIN_D;
    uint32_t d = (uint32_t)dl;

    *w_out = w;
    *d_out = d;
    return 1;
}

/* Securely obtain a fd: create exclusively (O_CREAT|O_EXCL|O_NOFOLLOW at mode,
 * default 0600), or attach an existing file (O_RDWR|O_NOFOLLOW, no O_CREAT). */
static int cms_secure_open(const char *path, mode_t mode, char *errbuf) {
    for (int attempt = 0; attempt < 100; attempt++) {
        int fd = open(path, O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, mode);
        if (fd >= 0) { (void)fchmod(fd, mode); return fd; }   /* exact mode: umask narrowed the O_EXCL create */
        if (errno != EEXIST) { CMS_ERR("create %s: %s", path, strerror(errno)); return -1; }
        fd = open(path, O_RDWR|O_NOFOLLOW|O_CLOEXEC);
        if (fd >= 0) return fd;
        if (errno == ENOENT) continue;   /* creator unlinked between our two opens; retry */
        CMS_ERR("open %s: %s", path, strerror(errno));  /* ELOOP => symlink rejected */
        return -1;
    }
    CMS_ERR("open %s: create/attach kept racing", path);
    return -1;
}

/* True iff the whole file is zero -- what an abandoned mid-init
   creator leaves.  Lets recovery re-init only a provably-empty file, never
   one that merely starts with a zero word.  Cold path, so a byte scan is
   fine.  Read, not mapped: a read fault on a tmpfs hole allocates the page. */
static int cms_file_is_zero(int fd, uint64_t size) {
    char buf[16384];
    for (uint64_t off = 0; off < size; ) {
        ssize_t n = pread(fd, buf, size - off < sizeof buf ? (size_t)(size - off) : sizeof buf, (off_t)off);
        if (n <= 0) return 0;
        for (ssize_t i = 0; i < n; i++) if (buf[i]) return 0;
        off += (uint64_t)n;
    }
    return 1;
}

/* Opt-in (DATA_COUNTMINSKETCH_SHARED_SPARSE=0): reserving commits memory this module otherwise fills lazily. */
static int cms_reserve(int fd, uint64_t size) {
    const char *sp = getenv("DATA_COUNTMINSKETCH_SHARED_SPARSE");
    if (!sp || strcmp(sp, "0")) return 0;
    /* Before Linux 6.11 tmpfs gives up at any pending signal and undoes the allocation, so a
     * periodic one could keep it from ever completing; SIGSTOP cannot be blocked. */
    sigset_t all, old;
    sigfillset(&all);
    sigprocmask(SIG_BLOCK, &all, &old);
    int e;
    do e = posix_fallocate(fd, 0, (off_t)size); while (e == EINTR);
    sigprocmask(SIG_SETMASK, &old, NULL);
    if (e == 0 || e == EOPNOTSUPP || e == EINVAL) return 0;
    errno = e;
    return -1;
}

static CmsHandle *cms_create(const char *path, double epsilon, double delta, mode_t mode, char *errbuf) {



( run in 1.563 second using v1.01-cache-2.11-cpan-60884a8df76 )