Search code examples
csystemd

Why call a __pure__ function but not use the answer?


For a side project I'm reading some of the systemd source code. I found the usage of the __pure__ function endswith inside of cg_get_root_path confusing. Specifically, why does the variable e exist in the cg_get_root_path function at all? It stores the results of endswith but never seems to actually be used, and the function endswith has no side-effects that I can see.

char *endswith(const char *s, const char *postfix) _pure_;

int cg_get_root_path(char **path) {
        char *p, *e;
        int r;

        assert(path);

        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
        if (r < 0)
                return r;

        e = endswith(p, "/" SPECIAL_INIT_SCOPE);
        if (!e)
                e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
        if (!e)
                e = endswith(p, "/system"); /* even more legacy */
        if (e)
                *e = 0;

        *path = p;
        return 0;
}

char* endswith(const char *s, const char *postfix) {
        size_t sl, pl;

        assert(s);
        assert(postfix);

        sl = strlen(s);
        pl = strlen(postfix);

        if (pl == 0)
                return (char*) s + sl;

        if (sl < pl)
                return NULL;

        if (memcmp(s + sl - pl, postfix, pl) != 0)
                return NULL;

        return (char*) s + sl - pl;
}

Solution

  • Ultimately there's one line where e is used: *e = 0 writes to memory (to an address that endswith has returned).