id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
1
./reptyr/reptyr.c
/* * Copyright (C) 2011 by Nelson Elhage * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/select.h> #include <sys/ioctl.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stdarg.h> #include <termios.h> #include <signal.h> #include "reptyr.h" #ifndef __linux__ #error reptyr is currently Linux-only. #endif static int verbose = 0; void _debug(const char *pfx, const char *msg, va_list ap) { if (pfx) fprintf(stderr, "%s", pfx); vfprintf(stderr, msg, ap); fprintf(stderr, "\n"); } void die(const char *msg, ...) { va_list ap; va_start(ap, msg); _debug("[!] ", msg, ap); va_end(ap); exit(1); } void debug(const char *msg, ...) { va_list ap; if (!verbose) return; va_start(ap, msg); _debug("[+] ", msg, ap); va_end(ap); } void error(const char *msg, ...) { va_list ap; va_start(ap, msg); _debug("[-] ", msg, ap); va_end(ap); } void setup_raw(struct termios *save) { struct termios set; if (tcgetattr(0, save) < 0) die("Unable to read terminal attributes: %m"); set = *save; cfmakeraw(&set); if (tcsetattr(0, TCSANOW, &set) < 0) die("Unable to set terminal attributes: %m"); } void resize_pty(int pty) { struct winsize sz; if (ioctl(0, TIOCGWINSZ, &sz) < 0) return; ioctl(pty, TIOCSWINSZ, &sz); } int writeall(int fd, const void *buf, ssize_t count) { ssize_t rv; while (count > 0) { rv = write(fd, buf, count); if (rv < 0) { if (errno == EINTR) continue; return rv; } count -= rv; buf += rv; } return 0; } volatile sig_atomic_t winch_happened = 0; void do_winch(int signal) { winch_happened = 1; } void do_proxy(int pty) { char buf[4096]; ssize_t count; fd_set set; while (1) { if (winch_happened) { winch_happened = 0; /* * FIXME: If a signal comes in after this point but before * select(), the resize will be delayed until we get more * input. signalfd() is probably the cleanest solution. */ resize_pty(pty); } FD_ZERO(&set); FD_SET(0, &set); FD_SET(pty, &set); if (select(pty+1, &set, NULL, NULL, NULL) < 0) { if (errno == EINTR) continue; fprintf(stderr, "select: %m"); return; } if (FD_ISSET(0, &set)) { count = read(0, buf, sizeof buf); if (count < 0) return; writeall(pty, buf, count); } if (FD_ISSET(pty, &set)) { count = read(pty, buf, sizeof buf); if (count < 0) return; writeall(1, buf, count); } } } void usage(char *me) { fprintf(stderr, "Usage: %s [-s] PID\n", me); fprintf(stderr, " %s -l|-L [COMMAND [ARGS]]\n", me); fprintf(stderr, " -l Create a new pty pair and print the name of the slave.\n"); fprintf(stderr, " if there are command-line arguments after -l\n"); fprintf(stderr, " they are executed with REPTYR_PTY set to path of pty.\n"); fprintf(stderr, " -L Like '-l', but also redirect the child's stdio to the slave.\n"); fprintf(stderr, " -s Attach fds 0-2 on the target, even if it is not attached to a tty.\n"); fprintf(stderr, " -h Print this help message and exit.\n"); fprintf(stderr, " -v Print the version number and exit.\n"); fprintf(stderr, " -V Print verbose debug output.\n"); } void check_yama_ptrace_scope(void) { int fd = open("/proc/sys/kernel/yama/ptrace_scope", O_RDONLY); if (fd >= 0) { char buf[256]; int n; n = read(fd, buf, sizeof buf); close(fd); if (n > 0) { if (!atoi(buf)) { return; } } } else if (errno == ENOENT) return; fprintf(stderr, "The kernel denied permission while attaching. If your uid matches\n"); fprintf(stderr, "the target's, check the value of /proc/sys/kernel/yama/ptrace_scope.\n"); fprintf(stderr, "For more information, see /etc/sysctl.d/10-ptrace.conf\n"); } int main(int argc, char **argv) { struct termios saved_termios; struct sigaction act; int pty; int arg = 1; int do_attach = 1; int force_stdio = 0; int unattached_script_redirection = 0; if (argc < 2) { usage(argv[0]); return 2; } if (argv[arg][0] == '-') { switch(argv[arg][1]) { case 'h': usage(argv[0]); return 0; case 'l': do_attach = 0; break; case 'L': do_attach = 0; unattached_script_redirection = 1; break; case 's': arg++; force_stdio = 1; break; case 'v': printf("This is reptyr version %s.\n", REPTYR_VERSION); printf(" by Nelson Elhage <[email protected]>\n"); printf("http://github.com/nelhage/reptyr/\n"); return 0; case 'V': arg++; verbose = 1; break; default: usage(argv[0]); return 1; } } if (do_attach && arg >= argc) { fprintf(stderr, "%s: No pid specified to attach\n", argv[0]); usage(argv[0]); return 1; } if ((pty = open("/dev/ptmx", O_RDWR|O_NOCTTY)) < 0) die("Unable to open /dev/ptmx: %m"); if (unlockpt(pty) < 0) die("Unable to unlockpt: %m"); if (grantpt(pty) < 0) die("Unable to grantpt: %m"); if (do_attach) { pid_t child = atoi(argv[arg]); int err; if ((err = attach_child(child, ptsname(pty), force_stdio))) { fprintf(stderr, "Unable to attach to pid %d: %s\n", child, strerror(err)); if (err == EPERM) { check_yama_ptrace_scope(); } return 1; } } else { printf("Opened a new pty: %s\n", ptsname(pty)); fflush(stdout); if (argc > 2) { if(!fork()) { setenv("REPTYR_PTY", ptsname(pty), 1); if (unattached_script_redirection) { int f; setpgid(0, getppid()); setsid(); f = open(ptsname(pty), O_RDONLY, 0); dup2(f, 0); close(f); f = open(ptsname(pty), O_WRONLY, 0); dup2(f, 1); dup2(f,2); close(f); } close(pty); execvp(argv[2], argv+2); exit(1); } } } setup_raw(&saved_termios); memset(&act, 0, sizeof act); act.sa_handler = do_winch; act.sa_flags = 0; sigaction(SIGWINCH, &act, NULL); resize_pty(pty); do_proxy(pty); tcsetattr(0, TCSANOW, &saved_termios); return 0; }
2
./reptyr/attach.c
/* * Copyright (C) 2011 by Nelson Elhage * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <sys/types.h> #include <dirent.h> #include <sys/syscall.h> #include <sys/mman.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <signal.h> #include <limits.h> #include <time.h> #include <sys/time.h> #include <sys/stat.h> #include "ptrace.h" #include "reptyr.h" #define TASK_COMM_LENGTH 16 struct proc_stat { pid_t pid; char comm[TASK_COMM_LENGTH+1]; char state; pid_t ppid, sid, pgid; dev_t ctty; }; #define do_syscall(child, name, a0, a1, a2, a3, a4, a5) \ ptrace_remote_syscall((child), ptrace_syscall_numbers((child))->nr_##name, \ a0, a1, a2, a3, a4, a5) int parse_proc_stat(int statfd, struct proc_stat *out) { char buf[1024]; int n; unsigned dev; lseek(statfd, 0, SEEK_SET); if (read(statfd, buf, sizeof buf) < 0) return errno; n = sscanf(buf, "%d (%16[^)]) %c %d %d %d %u", &out->pid, out->comm, &out->state, &out->ppid, &out->sid, &out->pgid, &dev); if (n == EOF) return errno; if (n != 7) { return EINVAL; } out->ctty = dev; return 0; } int read_proc_stat(pid_t pid, struct proc_stat *out) { char stat_path[PATH_MAX]; int statfd; int err; snprintf(stat_path, sizeof stat_path, "/proc/%d/stat", pid); statfd = open(stat_path, O_RDONLY); if (statfd < 0) { error("Unable to open %s: %s", stat_path, strerror(errno)); return -statfd; } err = parse_proc_stat(statfd, out); close(statfd); return err; } static void do_unmap(struct ptrace_child *child, child_addr_t addr, unsigned long len) { if (addr == (unsigned long)-1) return; do_syscall(child, munmap, addr, len, 0, 0, 0, 0); } int *get_child_tty_fds(struct ptrace_child *child, int statfd, int *count) { struct proc_stat child_status; struct stat tty_st, st; char buf[PATH_MAX]; int n = 0, allocated = 0; int *fds = NULL; DIR *dir; struct dirent *d; int *tmp = NULL; debug("Looking up fds for tty in child."); if ((child->error = parse_proc_stat(statfd, &child_status))) return NULL; debug("Resolved child tty: %x", (unsigned)child_status.ctty); if (stat("/dev/tty", &tty_st) < 0) { child->error = errno; error("Unable to stat /dev/tty"); return NULL; } snprintf(buf, sizeof buf, "/proc/%d/fd/", child->pid); if ((dir = opendir(buf)) == NULL) return NULL; while ((d = readdir(dir)) != NULL) { if (d->d_name[0] == '.') continue; snprintf(buf, sizeof buf, "/proc/%d/fd/%s", child->pid, d->d_name); if (stat(buf, &st) < 0) continue; if (st.st_rdev == child_status.ctty || st.st_rdev == tty_st.st_rdev) { if (n == allocated) { allocated = allocated ? 2 * allocated : 2; tmp = realloc(fds, allocated * sizeof *tmp); if (tmp == NULL) { child->error = errno; error("Unable to allocate memory for fd array."); free(fds); fds = NULL; goto out; } fds = tmp; } debug("Found an alias for the tty: %s", d->d_name); fds[n++] = atoi(d->d_name); } } out: *count = n; closedir(dir); return fds; } void move_process_group(struct ptrace_child *child, pid_t from, pid_t to) { DIR *dir; struct dirent *d; pid_t pid; char *p; int err; if ((dir = opendir("/proc/")) == NULL) return; while ((d = readdir(dir)) != NULL) { if (d->d_name[0] == '.') continue; pid = strtol(d->d_name, &p, 10); if (*p) continue; if (getpgid(pid) == from) { debug("Change pgid for pid %d", pid); err = do_syscall(child, setpgid, pid, to, 0, 0, 0, 0); if (err < 0) error(" failed: %s", strerror(-err)); } } closedir(dir); } int do_setsid(struct ptrace_child *child) { int err = 0; struct ptrace_child dummy; err = do_syscall(child, fork, 0, 0, 0, 0, 0, 0); if (err < 0) return err; debug("Forked a child: %ld", child->forked_pid); err = ptrace_finish_attach(&dummy, child->forked_pid); if (err < 0) goto out_kill; dummy.state = ptrace_after_syscall; memcpy(&dummy.user, &child->user, sizeof child->user); if (ptrace_restore_regs(&dummy)) { err = dummy.error; goto out_kill; } err = do_syscall(&dummy, setpgid, 0, 0, 0, 0, 0, 0); if (err < 0) { error("Failed to setpgid: %s", strerror(-err)); goto out_kill; } move_process_group(child, child->pid, dummy.pid); err = do_syscall(child, setsid, 0, 0, 0, 0, 0, 0); if (err < 0) { error("Failed to setsid: %s", strerror(-err)); move_process_group(child, dummy.pid, child->pid); goto out_kill; } debug("Did setsid()"); out_kill: kill(dummy.pid, SIGKILL); ptrace_detach_child(&dummy); ptrace_wait(&dummy); do_syscall(child, wait4, dummy.pid, 0, WNOHANG, 0, 0, 0); return err; } int ignore_hup(struct ptrace_child *child, unsigned long scratch_page) { int err; if (ptrace_syscall_numbers(child)->nr_signal != -1) { err = do_syscall(child, signal, SIGHUP, (unsigned long)SIG_IGN, 0, 0, 0, 0); } else { struct sigaction act = { .sa_handler = SIG_IGN, }; err = ptrace_memcpy_to_child(child, scratch_page, &act, sizeof act); if (err < 0) return err; err = do_syscall(child, rt_sigaction, SIGHUP, scratch_page, 0, 8, 0, 0); } return err; } /* * Wait for the specific pid to enter state 'T', or stopped. We have to pull the * /proc file rather than attaching with ptrace() and doing a wait() because * half the point of this exercise is for the process's real parent (the shell) * to see the TSTP. * * In case the process is masking or ignoring SIGTSTP, we time out after a * second and continue with the attach -- it'll still work mostly right, you * just won't get the old shell back. */ void wait_for_stop(pid_t pid, int fd) { struct timeval start, now; struct timespec sleep; struct proc_stat st; gettimeofday(&start, NULL); while (1) { gettimeofday(&now, NULL); if ((now.tv_sec > start.tv_sec && now.tv_usec > start.tv_usec) || (now.tv_sec - start.tv_sec > 1)) { error("Timed out waiting for child stop."); break; } /* * If anything goes wrong reading or parsing the stat node, just give * up. */ if (parse_proc_stat(fd, &st)) break; if (st.state == 'T') break; sleep.tv_sec = 0; sleep.tv_nsec = 10000000; nanosleep(&sleep, NULL); } } int copy_tty_state(pid_t pid, const char *pty) { char buf[PATH_MAX]; int fd, err = EINVAL; struct termios tio; int i; for (i = 0; i < 3 && err; i++) { err = 0; snprintf(buf, sizeof buf, "/proc/%d/fd/%d", pid, i); if ((fd = open(buf, O_RDONLY)) < 0) { err = -fd; continue; } if (!isatty(fd)) { err = ENOTTY; goto retry; } if (tcgetattr(fd, &tio) < 0) { err = -errno; } retry: close(fd); } if (err) return err; if ((fd = open(pty, O_RDONLY)) < 0) return -errno; if (tcsetattr(fd, TCSANOW, &tio) < 0) err = errno; close(fd); return -err; } int check_pgroup(pid_t target) { pid_t pg; DIR *dir; struct dirent *d; pid_t pid; char *p; int err = 0; struct proc_stat pid_stat; debug("Checking for problematic process group members..."); pg = getpgid(target); if (pg < 0) { error("Unable to get pgid (does process %d exist?)", (int)target); return pg; } if ((dir = opendir("/proc/")) == NULL) return errno; while ((d = readdir(dir)) != NULL) { if (d->d_name[0] == '.') continue; pid = strtol(d->d_name, &p, 10); if (*p) continue; if (pid == target) continue; if (getpgid(pid) == pg) { /* * We are actually being somewhat overly-conservative here * -- if pid is a child of target, and has not yet called * execve(), reptyr's setpgid() strategy may suffice. That * is a fairly rare case, and annoying to check for, so * for now let's just bail out. */ if ((err = read_proc_stat(pid, &pid_stat))) { memcpy(pid_stat.comm, "???", 4); } error("Process %d (%.*s) shares %d's process group. Unable to attach.\n" "(This most commonly means that %d has a suprocesses).", (int)pid, TASK_COMM_LENGTH, pid_stat.comm, (int)target, (int)target); err = EINVAL; goto out; } } out: closedir(dir); return err; } int attach_child(pid_t pid, const char *pty, int force_stdio) { struct ptrace_child child; unsigned long scratch_page = -1; int *child_tty_fds = NULL, n_fds, child_fd, statfd; int i; int err = 0; long page_size = sysconf(_SC_PAGE_SIZE); char stat_path[PATH_MAX]; long mmap_syscall; if ((err = check_pgroup(pid))) { return err; } if ((err = copy_tty_state(pid, pty))) { if (err == ENOTTY && !force_stdio) { error("Target is not connected to a terminal.\n" " Use -s to force attaching anyways."); return err; } } snprintf(stat_path, sizeof stat_path, "/proc/%d/stat", pid); statfd = open(stat_path, O_RDONLY); if (statfd < 0) { error("Unable to open %s: %s", stat_path, strerror(errno)); return -statfd; } kill(pid, SIGTSTP); wait_for_stop(pid, statfd); if (ptrace_attach_child(&child, pid)) { err = child.error; goto out_cont; } if (ptrace_advance_to_state(&child, ptrace_at_syscall)) { err = child.error; goto out_detach; } if (ptrace_save_regs(&child)) { err = child.error; goto out_detach; } mmap_syscall = ptrace_syscall_numbers(&child)->nr_mmap2; if (mmap_syscall == -1) mmap_syscall = ptrace_syscall_numbers(&child)->nr_mmap; scratch_page = ptrace_remote_syscall(&child, mmap_syscall, 0, page_size, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, 0, 0); if (scratch_page > (unsigned long)-1000) { err = -(signed long)scratch_page; goto out_unmap; } debug("Allocated scratch page: %lx", scratch_page); if (force_stdio) { child_tty_fds = malloc(3 * sizeof(int)); if (!child_tty_fds) { err = ENOMEM; goto out_unmap; } n_fds = 3; child_tty_fds[0] = 0; child_tty_fds[1] = 1; child_tty_fds[2] = 2; } else { child_tty_fds = get_child_tty_fds(&child, statfd, &n_fds); if (!child_tty_fds) { err = child.error; goto out_unmap; } } if (ptrace_memcpy_to_child(&child, scratch_page, pty, strlen(pty)+1)) { err = child.error; error("Unable to memcpy the pty path to child."); goto out_free_fds; } child_fd = do_syscall(&child, open, scratch_page, O_RDWR|O_NOCTTY, 0, 0, 0, 0); if (child_fd < 0) { err = child_fd; error("Unable to open the tty in the child."); goto out_free_fds; } debug("Opened the new tty in the child: %d", child_fd); err = ignore_hup(&child, scratch_page); if (err < 0) goto out_close; err = do_syscall(&child, getsid, 0, 0, 0, 0, 0, 0); if (err != child.pid) { debug("Target is not a session leader, attempting to setsid."); err = do_setsid(&child); } else { do_syscall(&child, ioctl, child_tty_fds[0], TIOCNOTTY, 0, 0, 0, 0); } if (err < 0) goto out_close; err = do_syscall(&child, ioctl, child_fd, TIOCSCTTY, 0, 0, 0, 0); if (err < 0) { error("Unable to set controlling terminal."); goto out_close; } debug("Set the controlling tty"); for (i = 0; i < n_fds; i++) do_syscall(&child, dup2, child_fd, child_tty_fds[i], 0, 0, 0, 0); err = 0; out_close: do_syscall(&child, close, child_fd, 0, 0, 0, 0, 0); out_free_fds: free(child_tty_fds); out_unmap: do_unmap(&child, scratch_page, page_size); ptrace_restore_regs(&child); out_detach: ptrace_detach_child(&child); if (err == 0) { kill(child.pid, SIGSTOP); wait_for_stop(child.pid, statfd); } kill(child.pid, SIGWINCH); out_cont: kill(child.pid, SIGCONT); close(statfd); return err < 0 ? -err : err; }
3
./reptyr/ptrace.c
/* * Copyright (C) 2011 by Nelson Elhage * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <sys/ptrace.h> #include <asm/ptrace.h> #include <sys/types.h> #include <sys/user.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/syscall.h> #include <sys/mman.h> #include <assert.h> #include <stddef.h> #include "ptrace.h" /* * RHEL 5's kernel supports these flags, but their libc doesn't ship a ptrace.h * that defines them. Define them here, and if our kernel doesn't support them, * we'll find out when PTRACE_SETOPTIONS fails. */ #ifndef PTRACE_O_TRACESYSGOOD #define PTRACE_O_TRACESYSGOOD 0x00000001 #endif #ifndef PTRACE_O_TRACEFORK #define PTRACE_O_TRACEFORK 0x00000002 #endif #ifndef PTRACE_EVENT_FORK #define PTRACE_EVENT_FORK 1 #endif #define min(x, y) ({ \ typeof(x) _min1 = (x); \ typeof(y) _min2 = (y); \ _min1 < _min2 ? _min1 : _min2; }) static long __ptrace_command(struct ptrace_child *child, enum __ptrace_request req, void *, void*); #define ptrace_command(cld, req, ...) _ptrace_command(cld, req, ## __VA_ARGS__, NULL, NULL) #define _ptrace_command(cld, req, addr, data, ...) __ptrace_command((cld), (req), (void*)(addr), (void*)(data)) struct ptrace_personality { size_t syscall_rv; size_t syscall_arg0; size_t syscall_arg1; size_t syscall_arg2; size_t syscall_arg3; size_t syscall_arg4; size_t syscall_arg5; size_t reg_ip; }; static struct ptrace_personality *personality(struct ptrace_child *child); #if defined(__amd64__) #include "arch/amd64.h" #elif defined(__i386__) #include "arch/i386.h" #elif defined(__arm__) #include "arch/arm.h" #else #error Unsupported architecture. #endif #ifndef ARCH_HAVE_MULTIPLE_PERSONALITIES int arch_get_personality(struct ptrace_child *child) { return 0; } struct syscall_numbers arch_syscall_numbers[] = { #include "arch/default-syscalls.h" }; #endif static struct ptrace_personality *personality(struct ptrace_child *child) { return &arch_personality[child->personality]; } struct syscall_numbers *ptrace_syscall_numbers(struct ptrace_child *child) { return &arch_syscall_numbers[child->personality]; } int ptrace_attach_child(struct ptrace_child *child, pid_t pid) { memset(child, 0, sizeof *child); child->pid = pid; if (ptrace_command(child, PTRACE_ATTACH) < 0) return -1; return ptrace_finish_attach(child, pid); } int ptrace_finish_attach(struct ptrace_child *child, pid_t pid) { memset(child, 0, sizeof *child); child->pid = pid; kill(pid, SIGCONT); if (ptrace_wait(child) < 0) goto detach; if (arch_get_personality(child)) goto detach; if (ptrace_command(child, PTRACE_SETOPTIONS, 0, PTRACE_O_TRACESYSGOOD|PTRACE_O_TRACEFORK) < 0) goto detach; return 0; detach: /* Don't clobber child->error */ ptrace(PTRACE_DETACH, child->pid, 0, 0); return -1; } int ptrace_detach_child(struct ptrace_child *child) { if (ptrace_command(child, PTRACE_DETACH, 0, 0) < 0) return -1; child->state = ptrace_detached; return 0; } int ptrace_wait(struct ptrace_child *child) { if (waitpid(child->pid, &child->status, 0) < 0) { child->error = errno; return -1; } if (WIFEXITED(child->status) || WIFSIGNALED(child->status)) { child->state = ptrace_exited; } else if (WIFSTOPPED(child->status)) { int sig = WSTOPSIG(child->status); if (sig & 0x80) { child->state = (child->state == ptrace_at_syscall) ? ptrace_after_syscall : ptrace_at_syscall; } else { if (sig == SIGTRAP && (((child->status >> 8) & PTRACE_EVENT_FORK) == PTRACE_EVENT_FORK)) ptrace_command(child, PTRACE_GETEVENTMSG, 0, &child->forked_pid); if (child->state != ptrace_at_syscall) child->state = ptrace_stopped; } } else { child->error = EINVAL; return -1; } return 0; } int ptrace_advance_to_state(struct ptrace_child *child, enum child_state desired) { int err; while (child->state != desired) { switch(desired) { case ptrace_after_syscall: case ptrace_at_syscall: if (WIFSTOPPED(child->status) && WSTOPSIG(child->status) == SIGSEGV) { child->error = EAGAIN; return -1; } err = ptrace_command(child, PTRACE_SYSCALL, 0, 0); break; case ptrace_running: return ptrace_command(child, PTRACE_CONT, 0, 0); case ptrace_stopped: err = kill(child->pid, SIGSTOP); if (err < 0) child->error = errno; break; default: child->error = EINVAL; return -1; } if (err < 0) return err; if (ptrace_wait(child) < 0) return -1; } return 0; } int ptrace_save_regs(struct ptrace_child *child) { if (ptrace_advance_to_state(child, ptrace_at_syscall) < 0) return -1; if (ptrace_command(child, PTRACE_GETREGS, 0, &child->user) < 0) return -1; arch_fixup_regs(child); if (arch_save_syscall(child) < 0) return -1; return 0; } int ptrace_restore_regs(struct ptrace_child *child) { int err; err = ptrace_command(child, PTRACE_SETREGS, 0, &child->user); if (err < 0) return err; return arch_restore_syscall(child); } unsigned long ptrace_remote_syscall(struct ptrace_child *child, unsigned long sysno, unsigned long p0, unsigned long p1, unsigned long p2, unsigned long p3, unsigned long p4, unsigned long p5) { unsigned long rv; if (ptrace_advance_to_state(child, ptrace_at_syscall) < 0) return -1; #define setreg(r, v) do { \ if (ptrace_command(child, PTRACE_POKEUSER, \ personality(child)->r, \ (v)) < 0) \ return -1; \ } while (0) if (arch_set_syscall(child, sysno) < 0) return -1; setreg(syscall_arg0, p0); setreg(syscall_arg1, p1); setreg(syscall_arg2, p2); setreg(syscall_arg3, p3); setreg(syscall_arg4, p4); setreg(syscall_arg5, p5); if (ptrace_advance_to_state(child, ptrace_after_syscall) < 0) return -1; rv = ptrace_command(child, PTRACE_PEEKUSER, personality(child)->syscall_rv); if (child->error) return -1; setreg(reg_ip, *(unsigned long*)((void*)&child->user + personality(child)->reg_ip)); #undef setreg return rv; } int ptrace_memcpy_to_child(struct ptrace_child *child, child_addr_t dst, const void *src, size_t n) { unsigned long scratch; while (n >= sizeof(unsigned long)) { if (ptrace_command(child, PTRACE_POKEDATA, dst, *((unsigned long*)src)) < 0) return -1; dst += sizeof(unsigned long); src += sizeof(unsigned long); n -= sizeof(unsigned long); } if (n) { scratch = ptrace_command(child, PTRACE_PEEKDATA, dst); if (child->error) return -1; memcpy(&scratch, src, n); if (ptrace_command(child, PTRACE_POKEDATA, dst, scratch) < 0) return -1; } return 0; } int ptrace_memcpy_from_child(struct ptrace_child *child, void *dst, child_addr_t src, size_t n) { unsigned long scratch; while (n) { scratch = ptrace_command(child, PTRACE_PEEKDATA, src); if (child->error) return -1; memcpy(dst, &scratch, min(n, sizeof(unsigned long))); dst += sizeof(unsigned long); src += sizeof(unsigned long); if (n >= sizeof(unsigned long)) n -= sizeof(unsigned long); else n = 0; } return 0; } static long __ptrace_command(struct ptrace_child *child, enum __ptrace_request req, void *addr, void *data) { long rv; errno = 0; rv = ptrace(req, child->pid, addr, data); child->error = errno; return rv; } #ifdef BUILD_PTRACE_MAIN int main(int argc, char **argv) { struct ptrace_child child; pid_t pid; if (argc < 2) { printf("Usage: %s pid\n", argv[0]); return 1; } pid = atoi(argv[1]); assert(!ptrace_attach_child(&child, pid)); assert(!ptrace_save_regs(&child)); printf("mmap = %lx\n", ptrace_remote_syscall(&child, mmap_syscall, 0, 4096, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, 0, 0)); reset_user_struct(&child.user); assert(!ptrace_restore_regs(&child)); assert(!ptrace_detach_child(&child)); return 0; } #endif
4
./pgmp/sandbox/hello/hello.c
/* A test program to study the mpz_t structure. * * Copyright (C) 2011 Daniele Varrazzo */ #include <stdio.h> #include <gmp.h> int main(int argc, char **argv) { mpz_t z1, z2; mpz_init_set_ui(z1, ~((unsigned long int)0)); mpz_init(z2); mpz_add_ui(z2, z1, 1); mpz_out_str(stdout, 10, z2); printf("\n"); return 0; }
5
./pgmp/src/pgmp_utils.c
/* pgmp_utils -- misc utility module * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pgmp_utils.h" #if PG_VERSION_NUM < 90000 #include "nodes/nodes.h" /* for IsA */ #include "nodes/execnodes.h" /* for AggState */ /* * AggCheckCallContext - test if a SQL function is being called as an aggregate * * The function is available from PG 9.0. This allows compatibility with * previous versions. */ int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext) { if (fcinfo->context && IsA(fcinfo->context, AggState)) { if (aggcontext) { *aggcontext = ((AggState *) fcinfo->context)->aggcontext; } return AGG_CONTEXT_AGGREGATE; } #if PG_VERSION_NUM >= 80400 if (fcinfo->context && IsA(fcinfo->context, WindowAggState)) { if (aggcontext) { /* different from PG 9.0: in PG 8.4 there is no aggcontext */ *aggcontext = ((WindowAggState *) fcinfo->context)->wincontext; } return AGG_CONTEXT_WINDOW; } #endif /* this is just to prevent "uninitialized variable" warnings */ if (aggcontext) { *aggcontext = NULL; } return 0; } #endif
6
./pgmp/src/pmpz_agg.c
/* pmpz_agg -- mpz aggregation functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp_utils.h" /* for AggCheckCallContext on PG < 9.0 */ #include "pgmp-impl.h" #include "fmgr.h" /* Convert an inplace accumulator into a pmpz structure. * * This function is strict, so don't care about NULLs */ PGMP_PG_FUNCTION(_pmpz_from_agg) { mpz_t *a; a = (mpz_t *)PG_GETARG_POINTER(0); PGMP_RETURN_MPZ(*a); } /* Macro to create an accumulation function from a gmp operator. * * This function can't be strict because the internal state is not compatible * with the base type. */ #define PMPZ_AGG(op, BLOCK, rel) \ \ PGMP_PG_FUNCTION(_pmpz_agg_ ## op) \ { \ mpz_t *a; \ const mpz_t z; \ MemoryContext oldctx; \ MemoryContext aggctx; \ \ if (UNLIKELY(!AggCheckCallContext(fcinfo, &aggctx))) \ { \ ereport(ERROR, \ (errcode(ERRCODE_DATA_EXCEPTION), \ errmsg("_mpz_agg_" #op " can only be called in accumulation"))); \ } \ \ if (PG_ARGISNULL(1)) { \ if (PG_ARGISNULL(0)) { \ PG_RETURN_NULL(); \ } \ else { \ PG_RETURN_POINTER(PG_GETARG_POINTER(0)); \ } \ } \ \ PGMP_GETARG_MPZ(z, 1); \ \ oldctx = MemoryContextSwitchTo(aggctx); \ \ if (LIKELY(!PG_ARGISNULL(0))) { \ a = (mpz_t *)PG_GETARG_POINTER(0); \ BLOCK(op, rel); \ } \ else { /* uninitialized */ \ a = (mpz_t *)palloc(sizeof(mpz_t)); \ mpz_init_set(*a, z); \ } \ \ MemoryContextSwitchTo(oldctx); \ \ PG_RETURN_POINTER(a); \ } #define PMPZ_AGG_OP(op, rel) \ mpz_ ## op (*a, *a, z) PMPZ_AGG(add, PMPZ_AGG_OP, 0) PMPZ_AGG(mul, PMPZ_AGG_OP, 0) PMPZ_AGG(and, PMPZ_AGG_OP, 0) PMPZ_AGG(ior, PMPZ_AGG_OP, 0) PMPZ_AGG(xor, PMPZ_AGG_OP, 0) #define PMPZ_AGG_REL(op, rel) \ do { \ if (mpz_cmp(*a, z) rel 0) { \ mpz_set(*a, z); \ } \ } while (0) PMPZ_AGG(min, PMPZ_AGG_REL, >) PMPZ_AGG(max, PMPZ_AGG_REL, <)
7
./pgmp/src/pmpq_io.c
/* pmpq_io -- mpq Input/Output functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpq.h" #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "utils/builtins.h" /* for numeric_out */ #include <string.h> /* * Input/Output functions */ PGMP_PG_FUNCTION(pmpq_in) { char *str; mpq_t q; str = PG_GETARG_CSTRING(0); mpq_init(q); if (0 != mpq_set_str(q, str, 0)) { ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input syntax for mpq: \"%s\"", str))); } ERROR_IF_DENOM_ZERO(mpq_denref(q)); mpq_canonicalize(q); PGMP_RETURN_MPQ(q); } PGMP_PG_FUNCTION(pmpq_in_base) { int base; char *str; mpq_t q; base = PG_GETARG_INT32(1); if (!(base == 0 || (2 <= base && base <= PGMP_MAXBASE_IO))) { ereport(ERROR, ( errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid base for mpq input: %d", base), errhint("base should be between 2 and %d", PGMP_MAXBASE_IO))); } str = TextDatumGetCString(PG_GETARG_POINTER(0)); mpq_init(q); if (0 != mpq_set_str(q, str, base)) { const char *ell; const int maxchars = 50; ell = (strlen(str) > maxchars) ? "..." : ""; ereport(ERROR, ( errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input for mpq base %d: \"%.*s%s\"", base, 50, str, ell))); } ERROR_IF_DENOM_ZERO(mpq_denref(q)); mpq_canonicalize(q); PGMP_RETURN_MPQ(q); } PGMP_PG_FUNCTION(pmpq_out) { const mpq_t q; char *buf; PGMP_GETARG_MPQ(q, 0); /* Allocate the output buffer manually - see mpmz_out to know why */ buf = palloc(3 /* add sign, slash and null */ + mpz_sizeinbase(mpq_numref(q), 10) + mpz_sizeinbase(mpq_denref(q), 10)); PG_RETURN_CSTRING(mpq_get_str(buf, 10, q)); } PGMP_PG_FUNCTION(pmpq_out_base) { const mpq_t q; int base; char *buf; PGMP_GETARG_MPQ(q, 0); base = PG_GETARG_INT32(1); if (!((-36 <= base && base <= -2) || (2 <= base && base <= PGMP_MAXBASE_IO))) { ereport(ERROR, ( errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid base for mpq output: %d", base), errhint("base should be between -36 and -2 or between 2 and %d", PGMP_MAXBASE_IO))); } /* Allocate the output buffer manually - see mpmz_out to know why */ buf = palloc(3 /* add sign, slash and null */ + mpz_sizeinbase(mpq_numref(q), ABS(base)) + mpz_sizeinbase(mpq_denref(q), ABS(base))); PG_RETURN_CSTRING(mpq_get_str(buf, base, q)); } /* * Cast functions */ static Datum _pmpq_from_long(long in); PGMP_PG_FUNCTION(pmpq_from_int2) { int16 in = PG_GETARG_INT16(0); return _pmpq_from_long(in); } PGMP_PG_FUNCTION(pmpq_from_int4) { int32 in = PG_GETARG_INT32(0); return _pmpq_from_long(in); } static Datum _pmpq_from_long(long in) { mpq_t q; mpz_init_set_si(mpq_numref(q), in); mpz_init_set_si(mpq_denref(q), 1L); PGMP_RETURN_MPQ(q); } static Datum _pmpq_from_double(double in); PGMP_PG_FUNCTION(pmpq_from_float4) { double in = (double)PG_GETARG_FLOAT4(0); return _pmpq_from_double(in); } PGMP_PG_FUNCTION(pmpq_from_float8) { double in = PG_GETARG_FLOAT8(0); return _pmpq_from_double(in); } static Datum _pmpq_from_double(double in) { mpq_t q; mpq_init(q); mpq_set_d(q, in); PGMP_RETURN_MPQ(q); } /* to convert from int8 we piggyback all the mess we've made for mpz */ Datum pmpz_from_int8(PG_FUNCTION_ARGS); PGMP_PG_FUNCTION(pmpq_from_int8) { mpq_t q; mpz_t tmp; mpz_from_pmpz(tmp, (pmpz *)DirectFunctionCall1(pmpz_from_int8, PG_GETARG_DATUM(0))); /* Make a copy of the num as MPQ will try to realloc on it */ mpz_init_set(mpq_numref(q), tmp); mpz_init_set_si(mpq_denref(q), 1L); PGMP_RETURN_MPQ(q); } /* To convert from numeric we convert the numeric in str, then work on that */ PGMP_PG_FUNCTION(pmpq_from_numeric) { mpq_t q; char *sn, *pn; sn = DatumGetCString(DirectFunctionCall1(numeric_out, PG_GETARG_DATUM(0))); if ((pn = strchr(sn, '.'))) { char *sd, *pd; /* Convert "123.45" into "12345" and produce "100" in the process. */ pd = sd = (char *)palloc(strlen(sn)); *pd++ = '1'; while (pn[1]) { pn[0] = pn[1]; ++pn; *pd++ = '0'; } *pd = *pn = '\0'; if (0 != mpz_init_set_str(mpq_numref(q), sn, 10)) { goto error; } mpz_init_set_str(mpq_denref(q), sd, 10); mpq_canonicalize(q); } else { /* just an integer */ if (0 != mpz_init_set_str(mpq_numref(q), sn, 10)) { goto error; } mpz_init_set_si(mpq_denref(q), 1L); } PGMP_RETURN_MPQ(q); error: ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("can't convert numeric value to mpq: \"%s\"", sn))); PG_RETURN_NULL(); } PGMP_PG_FUNCTION(pmpq_from_mpz) { mpq_t q; mpz_t tmp; /* Make a copy of the num as MPQ will try to realloc on it */ PGMP_GETARG_MPZ(tmp, 0); mpz_init_set(mpq_numref(q), tmp); mpz_init_set_si(mpq_denref(q), 1L); PGMP_RETURN_MPQ(q); } PGMP_PG_FUNCTION(pmpq_to_mpz) { const mpq_t q; mpz_t z; PGMP_GETARG_MPQ(q, 0); mpz_init(z); mpz_set_q(z, q); PGMP_RETURN_MPZ(z); } #define PMPQ_TO_INT(type) \ \ Datum pmpz_to_ ## type (PG_FUNCTION_ARGS); \ \ PGMP_PG_FUNCTION(pmpq_to_ ## type) \ { \ const mpq_t q; \ mpz_t z; \ \ PGMP_GETARG_MPQ(q, 0); \ \ mpz_init(z); \ mpz_set_q(z, q); \ \ return DirectFunctionCall1(pmpz_to_ ## type, (Datum)pmpz_from_mpz(z)); \ } PMPQ_TO_INT(int2) PMPQ_TO_INT(int4) PMPQ_TO_INT(int8) PGMP_PG_FUNCTION(pmpq_to_float4) { const mpq_t q; PGMP_GETARG_MPQ(q, 0); PG_RETURN_FLOAT4((float4)mpq_get_d(q)); } PGMP_PG_FUNCTION(pmpq_to_float8) { const mpq_t q; PGMP_GETARG_MPQ(q, 0); PG_RETURN_FLOAT8((float8)mpq_get_d(q)); } PGMP_PG_FUNCTION(pmpq_to_numeric) { const mpq_t q; int32 typmod; unsigned long scale; mpz_t z; char *buf; int sbuf, snum; PGMP_GETARG_MPQ(q, 0); typmod = PG_GETARG_INT32(1); /* Parse precision and scale from the type modifier */ if (typmod >= VARHDRSZ) { scale = (typmod - VARHDRSZ) & 0xffff; } else { scale = 15; } if (scale) { /* Convert q into a scaled z */ char *cmult; mpz_t mult; /* create 10000... with as many 0s as the scale */ cmult = (char *)palloc(scale + 2); memset(cmult + 1, '0', scale); cmult[0] = '1'; cmult[scale + 1] = '\0'; mpz_init_set_str(mult, cmult, 10); pfree(cmult); mpz_init(z); mpz_mul(z, mpq_numref(q), mult); sbuf = mpz_sizeinbase(z, 10); /* size of the output buffer */ mpz_tdiv_q(z, z, mpq_denref(q)); snum = mpz_sizeinbase(z, 10); /* size of the number */ } else { /* Just truncate q into an integer */ mpz_init(z); mpz_set_q(z, q); sbuf = snum = mpz_sizeinbase(z, 10); } /* If the numer is 0, everything is a special case: bail out */ if (mpz_cmp_si(z, 0) == 0) { return DirectFunctionCall3(numeric_in, CStringGetDatum("0"), ObjectIdGetDatum(0), /* unused 2nd value */ Int32GetDatum(typmod)); } /* convert z into a string */ buf = palloc(sbuf + 3); /* add sign, point and null */ mpz_get_str(buf, 10, z); if (scale) { char *end, *p; /* Left pad with 0s the number if smaller than the buffer */ if (snum < sbuf) { char *num0 = buf + (buf[0] == '-'); /* start of the num w/o sign */ memmove(num0 + (sbuf - snum), num0, snum + 1); memset(num0, '0', sbuf - snum); } end = buf + strlen(buf); /* Add the decimal point in the right place */ memmove(end - scale + 1, end - scale, scale + 1); end[-scale] = '.'; /* delete trailing 0s or they will be used to add extra precision */ if (typmod < VARHDRSZ) { /* scale was not specified */ for (p = end; p > (end - scale) && *p == '0'; --p) { *p = '\0'; } /* Don't leave a traliling point */ if (*p == '.') { *p = '\0'; } } } /* use numeric_in to build the value from the string and to apply the * typemod (which may result in overflow) */ return DirectFunctionCall3(numeric_in, CStringGetDatum(buf), ObjectIdGetDatum(0), /* unused 2nd value */ Int32GetDatum(typmod)); } /* * Constructor and accessors to num and den */ PGMP_PG_FUNCTION(pmpq_mpz_mpz) { const mpz_t num; const mpz_t den; mpq_t q; /* We must take a copy of num and den because they may be modified by * canonicalize */ PGMP_GETARG_MPZ(num, 0); PGMP_GETARG_MPZ(den, 1); ERROR_IF_DENOM_ZERO(den); /* Put together the input and canonicalize */ mpz_init_set(mpq_numref(q), num); mpz_init_set(mpq_denref(q), den); mpq_canonicalize(q); PGMP_RETURN_MPQ(q); } PGMP_PG_FUNCTION(pmpq_int4_int4) { int32 num = PG_GETARG_INT32(0); int32 den = PG_GETARG_INT32(1); mpq_t q; /* Put together the input and canonicalize */ mpz_init_set_si(mpq_numref(q), (long)num); mpz_init_set_si(mpq_denref(q), (long)den); ERROR_IF_DENOM_ZERO(mpq_denref(q)); mpq_canonicalize(q); PGMP_RETURN_MPQ(q); } PGMP_PG_FUNCTION(pmpq_numeric_numeric) { char *sn; char *sd; mpq_t q; sn = DatumGetCString(DirectFunctionCall1(numeric_out, PG_GETARG_DATUM(0))); if (0 != mpz_init_set_str(mpq_numref(q), sn, 10)) { ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("can't handle numeric value at numerator: %s", sn), errhint("the mpq components should be integers"))); } sd = DatumGetCString(DirectFunctionCall1(numeric_out, PG_GETARG_DATUM(1))); if (0 != mpz_init_set_str(mpq_denref(q), sd, 10)) { ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("can't handle numeric value at denominator: %s", sd), errhint("the mpq components should be integers"))); } ERROR_IF_DENOM_ZERO(mpq_denref(q)); mpq_canonicalize(q); PGMP_RETURN_MPQ(q); } PGMP_PG_FUNCTION(pmpq_num) { const mpq_t q; mpz_t z; PGMP_GETARG_MPQ(q, 0); mpz_init_set(z, mpq_numref(q)); PGMP_RETURN_MPZ(z); } PGMP_PG_FUNCTION(pmpq_den) { const mpq_t q; mpz_t z; PGMP_GETARG_MPQ(q, 0); mpz_init_set(z, mpq_denref(q)); PGMP_RETURN_MPZ(z); }
8
./pgmp/src/pmpz_roots.c
/* pmpz_roots -- root extraction functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "funcapi.h" #if PG_VERSION_NUM >= 90300 #include <access/htup_details.h> /* for heap_form_tuple */ #endif /* Functions with a more generic signature are defined in pmpz.arith.c */ #if __GMP_MP_RELEASE >= 40200 PGMP_PG_FUNCTION(pmpz_rootrem) { const mpz_t z1; mpz_t zroot; mpz_t zrem; unsigned long n; PGMP_GETARG_MPZ(z1, 0); PMPZ_CHECK_NONEG(z1); PGMP_GETARG_ULONG(n, 1); PMPZ_CHECK_LONG_POS(n); mpz_init(zroot); mpz_init(zrem); mpz_rootrem (zroot, zrem, z1, n); PGMP_RETURN_MPZ_MPZ(zroot, zrem); } #endif PGMP_PG_FUNCTION(pmpz_sqrtrem) { const mpz_t z1; mpz_t zroot; mpz_t zrem; PGMP_GETARG_MPZ(z1, 0); mpz_init(zroot); mpz_init(zrem); mpz_sqrtrem(zroot, zrem, z1); PGMP_RETURN_MPZ_MPZ(zroot, zrem); }
9
./pgmp/src/pgmp.c
/* pgmp -- PostgreSQL GMP module * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include <gmp.h> #include "postgres.h" #include "fmgr.h" #include "pgmp-impl.h" PG_MODULE_MAGIC; void _PG_init(void); void _PG_fini(void); static void *_pgmp_alloc(size_t alloc_size); static void *_pgmp_realloc(void *ptr, size_t old_size, size_t new_size); static void _pgmp_free(void *ptr, size_t size); /* A couple of constant limbs used to create constant mp? data * from the content of varlena data */ const mp_limb_t _pgmp_limb_0 = 0; const mp_limb_t _pgmp_limb_1 = 1; /* * Module initialization and cleanup */ void _PG_init(void) { /* A vow to the gods of the memory allocation */ mp_set_memory_functions( _pgmp_alloc, _pgmp_realloc, _pgmp_free); } void _PG_fini(void) { } /* * GMP custom allocation functions using PostgreSQL memory management. * * In order to store data into the database, the structure must be contiguous * in memory. GMP instead allocated the limbs dynamically. This means that to * convert from mpz_p to the varlena a memcpy would be required. * * But we don't like memcpy... So we allocate enough space to add the varlena * header and we return an offsetted pointer to GMP, so that we can always * scrubble a varlena header in front of the limbs and just ask the database * to store the result. */ static void * _pgmp_alloc(size_t size) { return PGMP_MAX_HDRSIZE + (char *)palloc(size + PGMP_MAX_HDRSIZE); } static void * _pgmp_realloc(void *ptr, size_t old_size, size_t new_size) { return PGMP_MAX_HDRSIZE + (char *)repalloc( (char *)ptr - PGMP_MAX_HDRSIZE, new_size + PGMP_MAX_HDRSIZE); } static void _pgmp_free(void *ptr, size_t size) { pfree((char *)ptr - PGMP_MAX_HDRSIZE); } /* Return the version of the library as an integer * * Parse the format from the variable gmp_version instead of using the macro * __GNU_PG_VERSION* in order to detect the runtime version instead of the * version pgmp was compiled against (although if I'm not entirely sure it is * working as expected). */ PGMP_PG_FUNCTION(pgmp_gmp_version) { int maj = 0, min = 0, patch = 0; const char *p; /* Parse both A.B.C and A.B formats. */ maj = atoi(gmp_version); if (NULL == (p = strchr(gmp_version, '.'))) { goto end; } min = atoi(p + 1); if (NULL == (p = strchr(p + 1, '.'))) { goto end; } patch = atoi(p + 1); end: PG_RETURN_INT32(maj * 10000 + min * 100 + patch); }
10
./pgmp/src/pmpq_arith.c
/* pmpq_arith -- mpq arithmetic functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpq.h" #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "access/hash.h" /* for hash_any */ /* * Unary operators */ PGMP_PG_FUNCTION(pmpq_uplus) { const pmpq *pq1; pmpq *res; pq1 = PGMP_GETARG_PMPQ(0); res = (pmpq *)palloc(VARSIZE(pq1)); memcpy(res, pq1, VARSIZE(pq1)); PG_RETURN_POINTER(res); } #define PMPQ_UN(op, CHECK) \ \ PGMP_PG_FUNCTION(pmpq_ ## op) \ { \ const mpq_t q; \ mpq_t qf; \ \ PGMP_GETARG_MPQ(q, 0); \ CHECK(q); \ \ mpq_init(qf); \ mpq_ ## op (qf, q); \ \ PGMP_RETURN_MPQ(qf); \ } PMPQ_UN(neg, PMPQ_NO_CHECK) PMPQ_UN(abs, PMPQ_NO_CHECK) PMPQ_UN(inv, PMPQ_CHECK_DIV0) /* * Binary operators */ /* Template to generate binary operators */ #define PMPQ_OP(op, CHECK2) \ \ PGMP_PG_FUNCTION(pmpq_ ## op) \ { \ const mpq_t q1; \ const mpq_t q2; \ mpq_t qf; \ \ PGMP_GETARG_MPQ(q1, 0); \ PGMP_GETARG_MPQ(q2, 1); \ CHECK2(q2); \ \ mpq_init(qf); \ mpq_ ## op (qf, q1, q2); \ \ PGMP_RETURN_MPQ(qf); \ } PMPQ_OP(add, PMPQ_NO_CHECK) PMPQ_OP(sub, PMPQ_NO_CHECK) PMPQ_OP(mul, PMPQ_NO_CHECK) PMPQ_OP(div, PMPQ_CHECK_DIV0) /* Functions defined on bit count */ #define PMPQ_BIT(op) \ \ PGMP_PG_FUNCTION(pmpq_ ## op) \ { \ const mpq_t q; \ unsigned long b; \ mpq_t qf; \ \ PGMP_GETARG_MPQ(q, 0); \ PGMP_GETARG_ULONG(b, 1); \ \ mpq_init(qf); \ mpq_ ## op (qf, q, b); \ \ PGMP_RETURN_MPQ(qf); \ } PMPQ_BIT(mul_2exp) PMPQ_BIT(div_2exp) /* * Comparison operators */ PGMP_PG_FUNCTION(pmpq_cmp) { const mpq_t q1; const mpq_t q2; PGMP_GETARG_MPQ(q1, 0); PGMP_GETARG_MPQ(q2, 1); PG_RETURN_INT32(mpq_cmp(q1, q2)); } #define PMPQ_CMP_EQ(op, rel) \ \ PGMP_PG_FUNCTION(pmpq_ ## op) \ { \ const mpq_t q1; \ const mpq_t q2; \ \ PGMP_GETARG_MPQ(q1, 0); \ PGMP_GETARG_MPQ(q2, 1); \ \ PG_RETURN_BOOL(mpq_equal(q1, q2) rel 0); \ } PMPQ_CMP_EQ(eq, !=) /* note that the operators are reversed */ PMPQ_CMP_EQ(ne, ==) #define PMPQ_CMP(op, rel) \ \ PGMP_PG_FUNCTION(pmpq_ ## op) \ { \ const mpq_t q1; \ const mpq_t q2; \ \ PGMP_GETARG_MPQ(q1, 0); \ PGMP_GETARG_MPQ(q2, 1); \ \ PG_RETURN_BOOL(mpq_cmp(q1, q2) rel 0); \ } PMPQ_CMP(gt, >) PMPQ_CMP(ge, >=) PMPQ_CMP(lt, <) PMPQ_CMP(le, <=) /* The hash of an integer mpq is the same of the same number as mpz. * This allows cross-type hash joins with mpz and builtins. */ PGMP_PG_FUNCTION(pmpq_hash) { const mpq_t q; Datum nhash; PGMP_GETARG_MPQ(q, 0); nhash = pmpz_get_hash(mpq_numref(q)); if (mpz_cmp_si(mpq_denref(q), 1L) == 0) { return nhash; } PG_RETURN_INT32( DatumGetInt32(nhash) ^ hash_any( (unsigned char *)LIMBS(mpq_denref(q)), NLIMBS(mpq_denref(q)) * sizeof(mp_limb_t))); } /* limit_den */ static void limit_den(mpq_ptr q_out, mpq_srcptr q_in, mpz_srcptr max_den); PGMP_PG_FUNCTION(pmpq_limit_den) { const mpq_t q_in; const mpz_t max_den; mpq_t q_out; PGMP_GETARG_MPQ(q_in, 0); if (PG_NARGS() >= 2) { PGMP_GETARG_MPZ(max_den, 1); } else { mpz_init_set_si((mpz_ptr)max_den, 1000000); } if (mpz_cmp_si(max_den, 1) < 0) { ereport(ERROR, ( \ errcode(ERRCODE_INVALID_PARAMETER_VALUE), \ errmsg("max_den should be at least 1"))); \ } mpq_init(q_out); limit_den(q_out, q_in, max_den); PGMP_RETURN_MPQ(q_out); } /* * Set q_out to the closest fraction to q_in with denominator at most max_den * * Ported from Python library: see * http://hg.python.org/cpython/file/v2.7/Lib/fractions.py#l206 * for implementation notes. */ static void limit_den(mpq_ptr q_out, mpq_srcptr q_in, mpz_srcptr max_den) { mpz_t p0, q0, p1, q1; mpz_t n, d; mpz_t a, q2; mpz_t k; mpq_t b1, b2; mpq_t ab1, ab2; if (mpz_cmp(mpq_denref(q_in), max_den) <= 0) { mpq_set(q_out, q_in); return; } /* p0, q0, p1, q1 = 0, 1, 1, 0 */ mpz_init_set_si(p0, 0); mpz_init_set_si(q0, 1); mpz_init_set_si(p1, 1); mpz_init_set_si(q1, 0); /* n, d = self._numerator, self._denominator */ mpz_init_set(n, mpq_numref(q_in)); mpz_init_set(d, mpq_denref(q_in)); mpz_init(a); mpz_init(q2); for (;;) { /* a = n // d */ mpz_tdiv_q(a, n, d); /* q2 = q0+a*q1 */ mpz_set(q2, q0); mpz_addmul(q2, a, q1); if (mpz_cmp(q2, max_den) > 0) { break; } /* p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 */ mpz_swap(p0, p1); mpz_addmul(p1, a, p0); mpz_swap(q0, q1); mpz_swap(q1, q2); /* n, d = d, n-a*d */ mpz_swap(n, d); mpz_submul(d, a, n); } /* k = (max_denominator - q0) // q1 */ mpz_init(k); mpz_sub(k, max_den, q0); mpz_tdiv_q(k, k, q1); /* bound1 = Fraction(p0+k*p1, q0+k*q1) */ mpq_init(b1); mpz_addmul(p0, k, p1); mpz_set(mpq_numref(b1), p0); mpz_addmul(q0, k, q1); mpz_set(mpq_denref(b1), q0); mpq_canonicalize(b1); /* bound2 = Fraction(p1, q1) */ mpq_init(b2); mpz_set(mpq_numref(b2), p1); mpz_set(mpq_denref(b2), q1); mpq_canonicalize(b2); /* if abs(bound2 - self) <= abs(bound1 - self): */ mpq_init(ab1); mpq_sub(ab1, b1, q_in); mpq_abs(ab1, ab1); mpq_init(ab2); mpq_sub(ab2, b2, q_in); mpq_abs(ab2, ab2); if (mpq_cmp(ab2, ab1) <= 0) { /* return bound2 */ mpq_set(q_out, b2); } else { /* return bound1 */ mpq_set(q_out, b1); } }
11
./pgmp/src/pmpz_rand.c
/* pmpz_rand -- mpz random numbers * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "utils/memutils.h" /* for TopMemoryContext */ /* The state of the random number generator. * * Currently this variable is reset when the library is loaded: this means at * every session but would break if the library starts being preloaded. So, * TODO: check if there is a way to explicitly allocate this structure per * session. */ gmp_randstate_t *pgmp_randstate; /* Clear the random state if set * * This macro should be invoked with the TopMemoryContext set as current * memory context */ #define PGMP_CLEAR_RANDSTATE \ do { \ if (pgmp_randstate) { \ gmp_randclear(*pgmp_randstate); \ pfree(pgmp_randstate); \ pgmp_randstate = NULL; \ } \ } while (0) /* Exit with an error if the random state is not set */ #define PGMP_CHECK_RANDSTATE \ do { \ if (!pgmp_randstate) { \ ereport(ERROR, ( \ errcode(ERRCODE_INVALID_PARAMETER_VALUE), \ errmsg("random state not initialized") )); \ } \ } while (0) /* * Random state initialization */ #define PGMP_RANDINIT(f, INIT) \ \ PGMP_PG_FUNCTION(pgmp_ ## f) \ { \ gmp_randstate_t *state; \ MemoryContext oldctx; \ \ /* palloc and init of the global variable should happen */ \ /* in the global memory context. */ \ oldctx = MemoryContextSwitchTo(TopMemoryContext); \ \ state = palloc(sizeof(gmp_randstate_t)); \ INIT(f); \ \ /* set the global variable to the initialized state */ \ PGMP_CLEAR_RANDSTATE; \ pgmp_randstate = state; \ \ MemoryContextSwitchTo(oldctx); \ \ PG_RETURN_NULL(); \ } #define PGMP_RANDINIT_NOARG(f) gmp_ ## f (*state) PGMP_RANDINIT(randinit_default, PGMP_RANDINIT_NOARG) #if __GMP_MP_RELEASE >= 40200 PGMP_RANDINIT(randinit_mt, PGMP_RANDINIT_NOARG) #endif #define PGMP_RANDINIT_ACE(f) \ do { \ const mpz_t a; \ unsigned long c; \ mp_bitcnt_t e; \ \ PGMP_GETARG_MPZ(a, 0); \ PGMP_GETARG_ULONG(c, 1); \ PGMP_GETARG_ULONG(e, 2); \ \ gmp_ ## f (*state, a, c, e); \ } while (0) PGMP_RANDINIT(randinit_lc_2exp, PGMP_RANDINIT_ACE) #define PGMP_RANDINIT_SIZE(f) \ do { \ mp_bitcnt_t size; \ \ PGMP_GETARG_ULONG(size, 0); \ \ if (!gmp_ ## f (*state, size)) { \ ereport(ERROR, ( \ errcode(ERRCODE_INVALID_PARAMETER_VALUE), \ errmsg("failed to initialized random state with size %lu", \ size) )); \ } \ } while (0) PGMP_RANDINIT(randinit_lc_2exp_size, PGMP_RANDINIT_SIZE) PGMP_PG_FUNCTION(pgmp_randseed) { const mpz_t seed; MemoryContext oldctx; PGMP_CHECK_RANDSTATE; PGMP_GETARG_MPZ(seed, 0); /* Switch to the global memory cx in case gmp_randseed allocates */ oldctx = MemoryContextSwitchTo(TopMemoryContext); gmp_randseed(*pgmp_randstate, seed); MemoryContextSwitchTo(oldctx); PG_RETURN_NULL(); } /* * Random numbers functions */ #define PMPZ_RAND_BITCNT(f) \ \ PGMP_PG_FUNCTION(pmpz_ ## f) \ { \ unsigned long n; \ mpz_t ret; \ \ PGMP_CHECK_RANDSTATE; \ \ PGMP_GETARG_ULONG(n, 0); \ \ mpz_init(ret); \ mpz_ ## f (ret, *pgmp_randstate, n); \ \ PGMP_RETURN_MPZ(ret); \ } PMPZ_RAND_BITCNT(urandomb) PMPZ_RAND_BITCNT(rrandomb) PGMP_PG_FUNCTION(pmpz_urandomm) { const mpz_t n; mpz_t ret; PGMP_CHECK_RANDSTATE; PGMP_GETARG_MPZ(n, 0); mpz_init(ret); mpz_urandomm(ret, *pgmp_randstate, n); PGMP_RETURN_MPZ(ret); }
12
./pgmp/src/pmpz_arith.c
/* pmpz_arith -- mpz arithmetic functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "funcapi.h" #include "access/hash.h" /* for hash_any */ #if PG_VERSION_NUM >= 90300 #include <access/htup_details.h> /* for heap_form_tuple */ #endif /* * Unary operators */ PGMP_PG_FUNCTION(pmpz_uplus) { const pmpz *pz1; pmpz *res; pz1 = PGMP_GETARG_PMPZ(0); res = (pmpz *)palloc(VARSIZE(pz1)); memcpy(res, pz1, VARSIZE(pz1)); PG_RETURN_POINTER(res); } /* Template to generate unary functions */ #define PMPZ_UN(op, CHECK) \ \ PGMP_PG_FUNCTION(pmpz_ ## op) \ { \ const mpz_t z1; \ mpz_t zf; \ \ PGMP_GETARG_MPZ(z1, 0); \ CHECK(z1); \ \ mpz_init(zf); \ mpz_ ## op (zf, z1); \ \ PGMP_RETURN_MPZ(zf); \ } PMPZ_UN(neg, PMPZ_NO_CHECK) PMPZ_UN(abs, PMPZ_NO_CHECK) PMPZ_UN(sqrt, PMPZ_CHECK_NONEG) PMPZ_UN(com, PMPZ_NO_CHECK) /* * Binary operators */ /* Operators defined (mpz, mpz) -> mpz. * * CHECK2 is a check performed on the 2nd argument. */ #define PMPZ_OP(op, CHECK2) \ \ PGMP_PG_FUNCTION(pmpz_ ## op) \ { \ const mpz_t z1; \ const mpz_t z2; \ mpz_t zf; \ \ PGMP_GETARG_MPZ(z1, 0); \ PGMP_GETARG_MPZ(z2, 1); \ CHECK2(z2); \ \ mpz_init(zf); \ mpz_ ## op (zf, z1, z2); \ \ PGMP_RETURN_MPZ(zf); \ } PMPZ_OP(add, PMPZ_NO_CHECK) PMPZ_OP(sub, PMPZ_NO_CHECK) PMPZ_OP(mul, PMPZ_NO_CHECK) PMPZ_OP(tdiv_q, PMPZ_CHECK_DIV0) PMPZ_OP(tdiv_r, PMPZ_CHECK_DIV0) PMPZ_OP(cdiv_q, PMPZ_CHECK_DIV0) PMPZ_OP(cdiv_r, PMPZ_CHECK_DIV0) PMPZ_OP(fdiv_q, PMPZ_CHECK_DIV0) PMPZ_OP(fdiv_r, PMPZ_CHECK_DIV0) PMPZ_OP(divexact, PMPZ_CHECK_DIV0) PMPZ_OP(and, PMPZ_NO_CHECK) PMPZ_OP(ior, PMPZ_NO_CHECK) PMPZ_OP(xor, PMPZ_NO_CHECK) PMPZ_OP(gcd, PMPZ_NO_CHECK) PMPZ_OP(lcm, PMPZ_NO_CHECK) PMPZ_OP(remove, PMPZ_NO_CHECK) /* TODO: return value not returned */ /* Operators defined (mpz, mpz) -> (mpz, mpz). */ #define PMPZ_OP2(op, CHECK2) \ \ PGMP_PG_FUNCTION(pmpz_ ## op) \ { \ const mpz_t z1; \ const mpz_t z2; \ mpz_t zf1; \ mpz_t zf2; \ \ PGMP_GETARG_MPZ(z1, 0); \ PGMP_GETARG_MPZ(z2, 1); \ CHECK2(z2); \ \ mpz_init(zf1); \ mpz_init(zf2); \ mpz_ ## op (zf1, zf2, z1, z2); \ \ PGMP_RETURN_MPZ_MPZ(zf1, zf2); \ } PMPZ_OP2(tdiv_qr, PMPZ_CHECK_DIV0) PMPZ_OP2(cdiv_qr, PMPZ_CHECK_DIV0) PMPZ_OP2(fdiv_qr, PMPZ_CHECK_DIV0) /* Functions defined on unsigned long */ #define PMPZ_OP_UL(op, CHECK1, CHECK2) \ \ PGMP_PG_FUNCTION(pmpz_ ## op) \ { \ const mpz_t z; \ unsigned long b; \ mpz_t zf; \ \ PGMP_GETARG_MPZ(z, 0); \ CHECK1(z); \ \ PGMP_GETARG_ULONG(b, 1); \ CHECK2(b); \ \ mpz_init(zf); \ mpz_ ## op (zf, z, b); \ \ PGMP_RETURN_MPZ(zf); \ } PMPZ_OP_UL(pow_ui, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_UL(root, PMPZ_CHECK_NONEG, PMPZ_CHECK_LONG_POS) PMPZ_OP_UL(bin_ui, PMPZ_NO_CHECK, PMPZ_CHECK_LONG_NONEG) /* Functions defined on bit count * * mp_bitcnt_t is defined as unsigned long. */ #define PMPZ_OP_BITCNT PMPZ_OP_UL PMPZ_OP_BITCNT(mul_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_BITCNT(tdiv_q_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_BITCNT(tdiv_r_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_BITCNT(cdiv_q_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_BITCNT(cdiv_r_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_BITCNT(fdiv_q_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) PMPZ_OP_BITCNT(fdiv_r_2exp, PMPZ_NO_CHECK, PMPZ_NO_CHECK) /* Unary predicates */ #define PMPZ_PRED(pred) \ \ PGMP_PG_FUNCTION(pmpz_ ## pred) \ { \ const mpz_t op; \ \ PGMP_GETARG_MPZ(op, 0); \ \ PG_RETURN_BOOL(mpz_ ## pred ## _p(op)); \ } PMPZ_PRED(even) PMPZ_PRED(odd) PMPZ_PRED(perfect_power) PMPZ_PRED(perfect_square) /* * Comparison operators */ PGMP_PG_FUNCTION(pmpz_cmp) { const mpz_t z1; const mpz_t z2; PGMP_GETARG_MPZ(z1, 0); PGMP_GETARG_MPZ(z2, 1); PG_RETURN_INT32(mpz_cmp(z1, z2)); } #define PMPZ_CMP(op, rel) \ \ PGMP_PG_FUNCTION(pmpz_ ## op) \ { \ const mpz_t z1; \ const mpz_t z2; \ \ PGMP_GETARG_MPZ(z1, 0); \ PGMP_GETARG_MPZ(z2, 1); \ \ PG_RETURN_BOOL(mpz_cmp(z1, z2) rel 0); \ } PMPZ_CMP(eq, ==) PMPZ_CMP(ne, !=) PMPZ_CMP(gt, >) PMPZ_CMP(ge, >=) PMPZ_CMP(lt, <) PMPZ_CMP(le, <=) /* The hash of an mpz fitting into a int64 is the same of the PG builtin. * This allows cross-type hash joins int2/int4/int8. */ PGMP_PG_FUNCTION(pmpz_hash) { const mpz_t z; PGMP_GETARG_MPZ(z, 0); return pmpz_get_hash(z); } Datum pmpz_get_hash(mpz_srcptr z) { int64 z64; if (0 == pmpz_get_int64(z, &z64)) { return DirectFunctionCall1(hashint8, Int64GetDatumFast(z64)); } PG_RETURN_INT32(hash_any( (unsigned char *)LIMBS(z), NLIMBS(z) * sizeof(mp_limb_t))); } /* * Misc functions... each one has its own signature, sigh. */ PGMP_PG_FUNCTION(pmpz_sgn) { const mpz_t n; PGMP_GETARG_MPZ(n, 0); PG_RETURN_INT32(mpz_sgn(n)); } PGMP_PG_FUNCTION(pmpz_divisible) { const mpz_t n; const mpz_t d; PGMP_GETARG_MPZ(n, 0); PGMP_GETARG_MPZ(d, 1); /* GMP 4.1 doesn't guard for zero */ #if __GMP_MP_RELEASE < 40200 if (UNLIKELY(MPZ_IS_ZERO(d))) { PG_RETURN_BOOL(MPZ_IS_ZERO(n)); } #endif PG_RETURN_BOOL(mpz_divisible_p(n, d)); } PGMP_PG_FUNCTION(pmpz_divisible_2exp) { const mpz_t n; mp_bitcnt_t b; PGMP_GETARG_MPZ(n, 0); PGMP_GETARG_ULONG(b, 1); PG_RETURN_BOOL(mpz_divisible_2exp_p(n, b)); } PGMP_PG_FUNCTION(pmpz_congruent) { const mpz_t n; const mpz_t c; const mpz_t d; PGMP_GETARG_MPZ(n, 0); PGMP_GETARG_MPZ(c, 1); PGMP_GETARG_MPZ(d, 2); /* GMP 4.1 doesn't guard for zero */ #if __GMP_MP_RELEASE < 40200 if (UNLIKELY(MPZ_IS_ZERO(d))) { PG_RETURN_BOOL(0 == mpz_cmp(n, c)); } #endif PG_RETURN_BOOL(mpz_congruent_p(n, c, d)); } PGMP_PG_FUNCTION(pmpz_congruent_2exp) { const mpz_t n; const mpz_t c; mp_bitcnt_t b; PGMP_GETARG_MPZ(n, 0); PGMP_GETARG_MPZ(c, 1); PGMP_GETARG_ULONG(b, 2); PG_RETURN_BOOL(mpz_congruent_2exp_p(n, c, b)); } PGMP_PG_FUNCTION(pmpz_powm) { const mpz_t base; const mpz_t exp; const mpz_t mod; mpz_t zf; PGMP_GETARG_MPZ(base, 0); PGMP_GETARG_MPZ(exp, 1); PMPZ_CHECK_NONEG(exp); PGMP_GETARG_MPZ(mod, 2); PMPZ_CHECK_DIV0(mod); mpz_init(zf); mpz_powm(zf, base, exp, mod); PGMP_RETURN_MPZ(zf); }
13
./pgmp/src/pmpz.c
/* pmpz -- PostgreSQL data type for GMP mpz * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" /* To be referred to to represent the zero */ extern const mp_limb_t _pgmp_limb_0; /* * Create a pmpz structure from the content of a mpz. * * The function relies on the limbs being allocated using the GMP custom * allocator: such allocator leaves PGMP_MAX_HDRSIZE bytes *before* the * returned pointer. We scrubble that area prepending the pmpz header. */ pmpz * pmpz_from_mpz(mpz_srcptr z) { pmpz *res; int size = SIZ(z); res = (pmpz *)((char *)LIMBS(z) - PMPZ_HDRSIZE); if (LIKELY(0 != size)) { size_t slimbs; int sign; if (size > 0) { slimbs = size * sizeof(mp_limb_t); sign = 0; } else { slimbs = -size * sizeof(mp_limb_t); sign = PMPZ_SIGN_MASK; } SET_VARSIZE(res, PMPZ_HDRSIZE + slimbs); res->mdata = sign; /* implicit version: 0 */ } else { /* In the zero representation there are no limbs */ SET_VARSIZE(res, PMPZ_HDRSIZE); res->mdata = 0; /* version: 0 */ } return res; } /* * Initialize a mpz from the content of a datum * * NOTE: the function takes a pointer to a const and changes the structure. * This allows to define the structure as const in the calling function and * avoid the risk to change it inplace, which may corrupt the database data. * * The structure populated doesn't own the pointed data, so it must not be * changed in any way and must not be cleared. */ void mpz_from_pmpz(mpz_srcptr z, const pmpz *pz) { int nlimbs; mpz_ptr wz; if (UNLIKELY(0 != (PMPZ_VERSION(pz)))) { ereport(ERROR, ( errcode(ERRCODE_DATA_EXCEPTION), errmsg("unsupported mpz version: %d", PMPZ_VERSION(pz)))); } /* discard the const qualifier */ wz = (mpz_ptr)z; nlimbs = (VARSIZE(pz) - PMPZ_HDRSIZE) / sizeof(mp_limb_t); if (LIKELY(nlimbs != 0)) { ALLOC(wz) = nlimbs; SIZ(wz) = PMPZ_NEGATIVE(pz) ? -nlimbs : nlimbs; LIMBS(wz) = (mp_limb_t *)pz->data; } else { /* in the datum there is just the varlena header * so let's just refer to some static const */ ALLOC(wz) = 1; SIZ(wz) = 0; LIMBS(wz) = (mp_limb_t *)&_pgmp_limb_0; } }
14
./pgmp/src/pmpz_theor.c
/* pmpz_theor -- number theoretic functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "funcapi.h" #if PG_VERSION_NUM >= 90300 #include <access/htup_details.h> /* for heap_form_tuple */ #endif /* Function with a more generic signature are defined in pmpz.arith.c */ PGMP_PG_FUNCTION(pmpz_probab_prime_p) { const mpz_t z1; int reps; PGMP_GETARG_MPZ(z1, 0); reps = PG_GETARG_INT32(1); PG_RETURN_INT32(mpz_probab_prime_p(z1, reps)); } PGMP_PG_FUNCTION(pmpz_nextprime) { const mpz_t z1; mpz_t zf; PGMP_GETARG_MPZ(z1, 0); mpz_init(zf); #if __GMP_MP_RELEASE < 40300 if (UNLIKELY(mpz_sgn(z1) < 0)) { mpz_set_ui(zf, 2); } else #endif { mpz_nextprime(zf, z1); } PGMP_RETURN_MPZ(zf); } PGMP_PG_FUNCTION(pmpz_gcdext) { const mpz_t z1; const mpz_t z2; mpz_t zf; mpz_t zs; mpz_t zt; PGMP_GETARG_MPZ(z1, 0); PGMP_GETARG_MPZ(z2, 1); mpz_init(zf); mpz_init(zs); mpz_init(zt); mpz_gcdext(zf, zs, zt, z1, z2); PGMP_RETURN_MPZ_MPZ_MPZ(zf, zs, zt); } PGMP_PG_FUNCTION(pmpz_invert) { const mpz_t z1; const mpz_t z2; mpz_t zf; int ret; PGMP_GETARG_MPZ(z1, 0); PGMP_GETARG_MPZ(z2, 1); mpz_init(zf); ret = mpz_invert(zf, z1, z2); if (ret != 0) { PGMP_RETURN_MPZ(zf); } else { PG_RETURN_NULL(); } } #define PMPZ_INT32(f) \ \ PGMP_PG_FUNCTION(pmpz_ ## f) \ { \ const mpz_t z1; \ const mpz_t z2; \ \ PGMP_GETARG_MPZ(z1, 0); \ PGMP_GETARG_MPZ(z2, 1); \ \ PG_RETURN_INT32(mpz_ ## f (z1, z2)); \ } PMPZ_INT32(jacobi) PMPZ_INT32(legendre) PMPZ_INT32(kronecker) #define PMPZ_ULONG(f) \ \ PGMP_PG_FUNCTION(pmpz_ ## f) \ { \ unsigned long op; \ mpz_t ret; \ \ PGMP_GETARG_ULONG(op, 0); \ \ mpz_init(ret); \ mpz_ ## f (ret, op); \ \ PGMP_RETURN_MPZ(ret); \ } PMPZ_ULONG(fac_ui) PMPZ_ULONG(fib_ui) PMPZ_ULONG(lucnum_ui) #define PMPZ_ULONG_MPZ2(f) \ \ PGMP_PG_FUNCTION(pmpz_ ## f) \ { \ unsigned long op; \ mpz_t ret1; \ mpz_t ret2; \ \ PGMP_GETARG_ULONG(op, 0); \ \ mpz_init(ret1); \ mpz_init(ret2); \ mpz_ ## f (ret1, ret2, op); \ \ PGMP_RETURN_MPZ_MPZ(ret1, ret2); \ } PMPZ_ULONG_MPZ2(fib2_ui) PMPZ_ULONG_MPZ2(lucnum2_ui)
15
./pgmp/src/pmpz_io.c
/* pmpz_io -- mpz Input/Output functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "utils/builtins.h" /* for numeric_out */ #include <math.h> /* for isinf, isnan */ /* * Input/Output functions */ PGMP_PG_FUNCTION(pmpz_in) { char *str; mpz_t z; str = PG_GETARG_CSTRING(0); if (0 != mpz_init_set_str(z, str, 0)) { const char *ell; const int maxchars = 50; ell = (strlen(str) > maxchars) ? "..." : ""; ereport(ERROR, ( errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input for mpz: \"%.*s%s\"", maxchars, str, ell))); } PGMP_RETURN_MPZ(z); } PGMP_PG_FUNCTION(pmpz_in_base) { int base; char *str; mpz_t z; base = PG_GETARG_INT32(1); if (!(base == 0 || (2 <= base && base <= PGMP_MAXBASE_IO))) { ereport(ERROR, ( errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid base for mpz input: %d", base), errhint("base should be between 2 and %d", PGMP_MAXBASE_IO))); } str = TextDatumGetCString(PG_GETARG_POINTER(0)); if (0 != mpz_init_set_str(z, str, base)) { const char *ell; const int maxchars = 50; ell = (strlen(str) > maxchars) ? "..." : ""; ereport(ERROR, ( errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("invalid input for mpz base %d: \"%.*s%s\"", base, 50, str, ell))); } PGMP_RETURN_MPZ(z); } PGMP_PG_FUNCTION(pmpz_out) { const mpz_t z; char *buf; PGMP_GETARG_MPZ(z, 0); /* We must allocate the output buffer ourselves because the buffer * returned by mpz_get_str actually starts a few bytes before (because of * the custom GMP allocator); Postgres will try to free the pointer we * return in printtup() so with the offsetted pointer a segfault is * granted. */ buf = palloc(mpz_sizeinbase(z, 10) + 2); /* add sign and null */ PG_RETURN_CSTRING(mpz_get_str(buf, 10, z)); } PGMP_PG_FUNCTION(pmpz_out_base) { const mpz_t z; int base; char *buf; PGMP_GETARG_MPZ(z, 0); base = PG_GETARG_INT32(1); if (!((-36 <= base && base <= -2) || (2 <= base && base <= PGMP_MAXBASE_IO))) { ereport(ERROR, ( errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid base for mpz output: %d", base), errhint("base should be between -36 and -2 or between 2 and %d", PGMP_MAXBASE_IO))); } /* Allocate the output buffer manually - see mpmz_out to know why */ buf = palloc(mpz_sizeinbase(z, ABS(base)) + 2); /* add sign and null */ PG_RETURN_CSTRING(mpz_get_str(buf, base, z)); } /* * Cast functions */ static Datum _pmpz_from_long(long in); static Datum _pmpz_from_double(double in); PGMP_PG_FUNCTION(pmpz_from_int2) { int16 in = PG_GETARG_INT16(0); return _pmpz_from_long(in); } PGMP_PG_FUNCTION(pmpz_from_int4) { int32 in = PG_GETARG_INT32(0); return _pmpz_from_long(in); } PGMP_PG_FUNCTION(pmpz_from_int8) { int64 in = PG_GETARG_INT64(0); #if PGMP_LONG_64 return _pmpz_from_long(in); #elif PGMP_LONG_32 int neg = 0; uint32 lo; uint32 hi; mpz_t z; if (LIKELY(in != INT64_MIN)) { if (in < 0) { neg = 1; in = -in; } lo = in & 0xFFFFFFFFUL; hi = in >> 32; if (hi) { mpz_init_set_ui(z, hi); mpz_mul_2exp(z, z, 32); mpz_add_ui(z, z, lo); } else { mpz_init_set_ui(z, lo); } if (neg) { mpz_neg(z, z); } } else { /* this would overflow the long */ mpz_init_set_si(z, 1L); mpz_mul_2exp(z, z, 63); mpz_neg(z, z); } PGMP_RETURN_MPZ(z); #endif } static Datum _pmpz_from_long(long in) { mpz_t z; mpz_init_set_si(z, in); PGMP_RETURN_MPZ(z); } PGMP_PG_FUNCTION(pmpz_from_float4) { float4 in = PG_GETARG_FLOAT4(0); return _pmpz_from_double(in); } PGMP_PG_FUNCTION(pmpz_from_float8) { float8 in = PG_GETARG_FLOAT8(0); return _pmpz_from_double(in); } static Datum _pmpz_from_double(double in) { mpz_t z; if (isinf(in) || isnan(in)) { ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("can't convert float value to mpz: \"%f\"", in))); } mpz_init_set_d(z, in); PGMP_RETURN_MPZ(z); } PGMP_PG_FUNCTION(pmpz_from_numeric) { char *str; char *p; mpz_t z; /* convert the numeric into string. */ str = DatumGetCString(DirectFunctionCall1(numeric_out, PG_GETARG_DATUM(0))); /* truncate the string if it contains a decimal dot */ if ((p = strchr(str, '.'))) { *p = '\0'; } if (0 != mpz_init_set_str(z, str, 10)) { /* here str may have been cropped, but I expect this error * only triggered by NaN, so not in case of regular number */ ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("can't convert numeric value to mpz: \"%s\"", str))); } PGMP_RETURN_MPZ(z); } PGMP_PG_FUNCTION(pmpz_to_int2) { const mpz_t z; int16 out; PGMP_GETARG_MPZ(z, 0); if (!mpz_fits_sshort_p(z)) { ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("numeric value too big to be converted to int2 data type"))); } out = mpz_get_si(z); PG_RETURN_INT16(out); } PGMP_PG_FUNCTION(pmpz_to_int4) { const mpz_t z; int32 out; PGMP_GETARG_MPZ(z, 0); if (!mpz_fits_sint_p(z)) { ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("numeric value too big to be converted to int4 data type"))); } out = mpz_get_si(z); PG_RETURN_INT32(out); } PGMP_PG_FUNCTION(pmpz_to_int8) { const mpz_t z; int64 ret = 0; PGMP_GETARG_MPZ(z, 0); if (0 != pmpz_get_int64(z, &ret)) { ereport(ERROR, ( errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("numeric value too big to be converted to int8 data type"))); } PG_RETURN_INT64(ret); } /* Convert an mpz into and int64. * * return 0 in case of success, else a nonzero value */ int pmpz_get_int64(mpz_srcptr z, int64 *out) { #if PGMP_LONG_64 if (mpz_fits_slong_p(z)) { *out = mpz_get_si(z); return 0; } #elif PGMP_LONG_32 switch (SIZ(z)) { case 0: *out = 0LL; return 0; break; case 1: *out = (int64)(LIMBS(z)[0]); return 0; break; case -1: *out = -(int64)(LIMBS(z)[0]); return 0; break; case 2: if (LIMBS(z)[1] < 0x80000000L) { *out = (int64)(LIMBS(z)[1]) << 32 | (int64)(LIMBS(z)[0]); return 0; } break; case -2: if (LIMBS(z)[1] < 0x80000000L) { *out = -((int64)(LIMBS(z)[1]) << 32 | (int64)(LIMBS(z)[0])); return 0; } else if (LIMBS(z)[0] == 0 && LIMBS(z)[1] == 0x80000000L) { *out = -0x8000000000000000LL; return 0; } break; } #endif return -1; } PGMP_PG_FUNCTION(pmpz_to_float4) { const mpz_t z; double out; PGMP_GETARG_MPZ(z, 0); out = mpz_get_d(z); PG_RETURN_FLOAT4((float4)out); } PGMP_PG_FUNCTION(pmpz_to_float8) { const mpz_t z; double out; PGMP_GETARG_MPZ(z, 0); out = mpz_get_d(z); PG_RETURN_FLOAT8((float8)out); }
16
./pgmp/src/pmpz_bits.c
/* pmpz_bits -- bit manipulation functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpz.h" #include "pgmp-impl.h" #include "fmgr.h" #include "funcapi.h" /* Function with a more generic signature are defined in pmpz.arith.c */ /* Macro to get and return mp_bitcnt_t * * the value is defined as unsigned long, so it doesn't fit into an int8 on 64 * bit platform. We'll convert them to/from mpz in SQL. */ #define PGMP_GETARG_BITCNT(tgt,n) \ do { \ mpz_t _tmp; \ PGMP_GETARG_MPZ(_tmp, n); \ \ if (!(mpz_fits_ulong_p(_tmp))) { \ ereport(ERROR, ( \ errcode(ERRCODE_INVALID_PARAMETER_VALUE), \ errmsg("argument doesn't fit into a bitcount type") )); \ } \ \ tgt = mpz_get_ui(_tmp); \ } while (0) #define PGMP_RETURN_BITCNT(n) \ do { \ mpz_t _rv; \ mpz_init_set_ui(_rv, n); \ PGMP_RETURN_MPZ(_rv); \ } while (0) /* Return the largest possible mp_bitcnt_t. Useful for testing the return * value of a few other bit manipulation functions as the value depends on the * server platform. */ PGMP_PG_FUNCTION(pgmp_max_bitcnt) { mp_bitcnt_t ret; ret = ~((mp_bitcnt_t)0); PGMP_RETURN_BITCNT(ret); } PGMP_PG_FUNCTION(pmpz_popcount) { const mpz_t z; mp_bitcnt_t ret; PGMP_GETARG_MPZ(z, 0); ret = mpz_popcount(z); PGMP_RETURN_BITCNT(ret); } PGMP_PG_FUNCTION(pmpz_hamdist) { const mpz_t z1; const mpz_t z2; mp_bitcnt_t ret; PGMP_GETARG_MPZ(z1, 0); PGMP_GETARG_MPZ(z2, 1); ret = mpz_hamdist(z1, z2); PGMP_RETURN_BITCNT(ret); } #define PMPZ_SCAN(f) \ \ PGMP_PG_FUNCTION(pmpz_ ## f) \ { \ const mpz_t z; \ mp_bitcnt_t start; \ \ PGMP_GETARG_MPZ(z, 0); \ PGMP_GETARG_BITCNT(start, 1); \ \ PGMP_RETURN_BITCNT(mpz_ ## f(z, start)); \ } PMPZ_SCAN(scan0) PMPZ_SCAN(scan1) /* inplace bit fiddling operations */ #define PMPZ_BIT(f) \ \ PGMP_PG_FUNCTION(pmpz_ ## f) \ { \ const mpz_t z; \ mp_bitcnt_t idx; \ mpz_t ret; \ \ PGMP_GETARG_MPZ(z, 0); \ PGMP_GETARG_BITCNT(idx, 1); \ \ mpz_init_set(ret, z); \ mpz_ ## f(ret, idx); \ PGMP_RETURN_MPZ(ret); \ } PMPZ_BIT(setbit) PMPZ_BIT(clrbit) #if __GMP_MP_RELEASE >= 40200 PMPZ_BIT(combit) #endif PGMP_PG_FUNCTION(pmpz_tstbit) { const mpz_t z; mp_bitcnt_t idx; int32 ret; PGMP_GETARG_MPZ(z, 0); PGMP_GETARG_BITCNT(idx, 1); ret = mpz_tstbit(z, idx); PG_RETURN_INT32(ret); }
17
./pgmp/src/pmpq.c
/* pmpq -- PostgreSQL data type for GMP mpq * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpq.h" #include "pgmp-impl.h" #include "fmgr.h" /* To be referred to to represent the zero */ extern const mp_limb_t _pgmp_limb_0; extern const mp_limb_t _pgmp_limb_1; /* * Create a pmpq structure from the content of a mpq * * The function is not const as the numerator will be realloc'd to make room * to the denom limbs after it. For this reason this function must never * receive directly data read from the database. */ pmpq * pmpq_from_mpq(mpq_ptr q) { pmpq *res; mpz_ptr num = mpq_numref(q); mpz_ptr den = mpq_denref(q); int nsize = SIZ(num); if (LIKELY(0 != nsize)) { /* Make enough room after the numer to store the denom limbs */ int nalloc = ABS(nsize); int dsize = SIZ(mpq_denref(q)); if (nalloc >= dsize) { LIMBS(num) = _mpz_realloc(num, nalloc + dsize); res = (pmpq *)((char *)LIMBS(num) - PMPQ_HDRSIZE); SET_VARSIZE(res, PMPQ_HDRSIZE + (nalloc + dsize) * sizeof(mp_limb_t)); /* copy the denom after the numer */ memcpy(res->data + nalloc, LIMBS(den), dsize * sizeof(mp_limb_t)); /* Set the number of limbs and order and implicitly version 0 */ res->mdata = PMPQ_SET_SIZE_FIRST(PMPQ_SET_NUMER_FIRST(0), nalloc); } else { LIMBS(den) = _mpz_realloc(den, nalloc + dsize); res = (pmpq *)((char *)LIMBS(den) - PMPQ_HDRSIZE); SET_VARSIZE(res, PMPQ_HDRSIZE + (nalloc + dsize) * sizeof(mp_limb_t)); /* copy the numer after the denom */ memcpy(res->data + dsize, LIMBS(num), nalloc * sizeof(mp_limb_t)); /* Set the number of limbs and order and implicitly version 0 */ res->mdata = PMPQ_SET_SIZE_FIRST(PMPQ_SET_DENOM_FIRST(0), dsize); } /* Set the sign */ if (nsize < 0) { res->mdata = PMPQ_SET_NEGATIVE(res->mdata); } } else { res = (pmpq *)((char *)LIMBS(num) - PMPQ_HDRSIZE); SET_VARSIZE(res, PMPQ_HDRSIZE); res->mdata = 0; } return res; } /* * Initialize a mpq from the content of a datum * * NOTE: the function takes a pointer to a const and changes the structure. * This allows to define the structure as const in the calling function and * avoid the risk to change it inplace, which may corrupt the database data. * * The structure populated doesn't own the pointed data, so it must not be * changed in any way and must not be cleared. */ void mpq_from_pmpq(mpq_srcptr q, const pmpq *pq) { /* discard the const qualifier */ mpq_ptr wq = (mpq_ptr)q; mpz_ptr num = mpq_numref(wq); mpz_ptr den = mpq_denref(wq); if (UNLIKELY(0 != (PMPQ_VERSION(pq)))) { ereport(ERROR, ( errcode(ERRCODE_DATA_EXCEPTION), errmsg("unsupported mpq version: %d", PMPQ_VERSION(pq)))); } if (0 != PMPQ_NLIMBS(pq)) { mpz_ptr fst, snd; if (PMPQ_NUMER_FIRST(pq)) { fst = num; snd = den; } else { fst = den; snd = num; } /* We have data from numer and denom into the datum */ ALLOC(fst) = SIZ(fst) = PMPQ_SIZE_FIRST(pq); LIMBS(fst) = (mp_limb_t *)pq->data; ALLOC(snd) = SIZ(snd) = PMPQ_SIZE_SECOND(pq); LIMBS(snd) = (mp_limb_t *)pq->data + ALLOC(fst); if (PMPQ_NEGATIVE(pq)) { SIZ(num) = -SIZ(num); } } else { /* in the datum there is not 1/0, * so let's just refer to some static const */ ALLOC(num) = 1; SIZ(num) = 0; LIMBS(num) = (mp_limb_t *)(&_pgmp_limb_0); ALLOC(den) = 1; SIZ(den) = 1; LIMBS(den) = (mp_limb_t *)(&_pgmp_limb_1); } }
18
./pgmp/src/pmpq_agg.c
/* pmpq_agg -- mpq aggregation functions * * Copyright (C) 2011 Daniele Varrazzo * * This file is part of the PostgreSQL GMP Module * * The PostgreSQL GMP Module is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * The PostgreSQL GMP Module is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the PostgreSQL GMP Module. If not, see * http://www.gnu.org/licenses/. */ #include "pmpq.h" #include "pgmp_utils.h" /* for AggCheckCallContext on PG < 9.0 */ #include "pgmp-impl.h" #include "fmgr.h" /* Convert an inplace accumulator into a pmpq structure. * * This function is strict, so don't care about NULLs */ PGMP_PG_FUNCTION(_pmpq_from_agg) { mpq_t *a; a = (mpq_t *)PG_GETARG_POINTER(0); PGMP_RETURN_MPQ(*a); } /* Macro to create an accumulation function from a gmp operator. * * This function can't be strict because the internal state is not compatible * with the base type. */ #define PMPQ_AGG(op, BLOCK, rel) \ \ PGMP_PG_FUNCTION(_pmpq_agg_ ## op) \ { \ mpq_t *a; \ const mpq_t q; \ MemoryContext oldctx; \ MemoryContext aggctx; \ \ if (UNLIKELY(!AggCheckCallContext(fcinfo, &aggctx))) \ { \ ereport(ERROR, \ (errcode(ERRCODE_DATA_EXCEPTION), \ errmsg("_mpq_agg_" #op " can only be called in accumulation"))); \ } \ \ if (PG_ARGISNULL(1)) { \ if (PG_ARGISNULL(0)) { \ PG_RETURN_NULL(); \ } \ else { \ PG_RETURN_POINTER(PG_GETARG_POINTER(0)); \ } \ } \ \ PGMP_GETARG_MPQ(q, 1); \ \ oldctx = MemoryContextSwitchTo(aggctx); \ \ if (LIKELY(!PG_ARGISNULL(0))) { \ a = (mpq_t *)PG_GETARG_POINTER(0); \ BLOCK(op, rel); \ } \ else { /* uninitialized */ \ a = (mpq_t *)palloc(sizeof(mpq_t)); \ mpq_init(*a); \ mpq_set(*a, q); \ } \ \ MemoryContextSwitchTo(oldctx); \ \ PG_RETURN_POINTER(a); \ } #define PMPQ_AGG_OP(op, rel) \ mpq_ ## op (*a, *a, q) PMPQ_AGG(add, PMPQ_AGG_OP, 0) PMPQ_AGG(mul, PMPQ_AGG_OP, 0) #define PMPQ_AGG_REL(op, rel) \ do { \ if (mpq_cmp(*a, q) rel 0) { \ mpq_set(*a, q); \ } \ } while (0) PMPQ_AGG(min, PMPQ_AGG_REL, >) PMPQ_AGG(max, PMPQ_AGG_REL, <)
19
./little-cms/utils/samples/vericc.c
//--------------------------------------------------------------------------------- // // Little Color Management System // Copyright (c) 1998-2010 Marti Maria Saguer // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //--------------------------------------------------------------------------------- // #include "lcms2.h" #include <string.h> #include <math.h> static int PrintUsage(void) { fprintf(stderr, "Sets profile version\n\nUsage: vericc --r<version> iccprofile.icc\n"); return 0; } int main(int argc, char *argv[]) { cmsHPROFILE hProfile; char* ptr; cmsFloat64Number Version; if (argc != 3) return PrintUsage(); ptr = argv[1]; if (strncmp(ptr, "--r", 3) != 0) return PrintUsage(); ptr += 3; if (!*ptr) { fprintf(stderr, "Wrong version number\n"); return 1; } Version = atof(ptr); hProfile = cmsOpenProfileFromFile(argv[2], "r"); if (hProfile == NULL) { fprintf(stderr, "'%s': cannot open\n", argv[2]); return 1; } cmsSetProfileVersion(hProfile, Version); cmsSaveProfileToFile(hProfile, "$$tmp.icc"); cmsCloseProfile(hProfile); remove(argv[2]); rename("$$tmp.icc", argv[2]); return 0; }
20
./little-cms/utils/samples/mktiff8.c
// // Little cms // Copyright (C) 1998-2010 Marti Maria // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // Creates a devicelink that decodes TIFF8 Lab files #include "lcms2.h" #include <stdlib.h> #include <math.h> static double DecodeAbTIFF(double ab) { if (ab <= 128.) ab += 127.; else ab -= 127.; return ab; } static cmsToneCurve* CreateStep(void) { cmsToneCurve* Gamma; cmsUInt16Number* Table; int i; double a; Table = calloc(4096, sizeof(cmsUInt16Number)); if (Table == NULL) return NULL; for (i=0; i < 4096; i++) { a = (double) i * 255. / 4095.; a = DecodeAbTIFF(a); Table[i] = (cmsUInt16Number) floor(a * 257. + 0.5); } Gamma = cmsBuildTabulatedToneCurve16(0, 4096, Table); free(Table); return Gamma; } static cmsToneCurve* CreateLinear(void) { cmsUInt16Number Linear[2] = { 0, 0xffff }; return cmsBuildTabulatedToneCurve16(0, 2, Linear); } // Set the copyright and description static cmsBool SetTextTags(cmsHPROFILE hProfile) { cmsMLU *DescriptionMLU, *CopyrightMLU; cmsBool rc = FALSE; DescriptionMLU = cmsMLUalloc(0, 1); CopyrightMLU = cmsMLUalloc(0, 1); if (DescriptionMLU == NULL || CopyrightMLU == NULL) goto Error; if (!cmsMLUsetASCII(DescriptionMLU, "en", "US", "Little cms Tiff8 CIELab")) goto Error; if (!cmsMLUsetASCII(CopyrightMLU, "en", "US", "Copyright (c) Marti Maria, 2010. All rights reserved.")) goto Error; if (!cmsWriteTag(hProfile, cmsSigProfileDescriptionTag, DescriptionMLU)) goto Error; if (!cmsWriteTag(hProfile, cmsSigCopyrightTag, CopyrightMLU)) goto Error; rc = TRUE; Error: if (DescriptionMLU) cmsMLUfree(DescriptionMLU); if (CopyrightMLU) cmsMLUfree(CopyrightMLU); return rc; } int main(int argc, char *argv[]) { cmsHPROFILE hProfile; cmsPipeline *AToB0; cmsToneCurve* PreLinear[3]; cmsToneCurve *Lin, *Step; fprintf(stderr, "Creating lcmstiff8.icm..."); remove("lcmstiff8.icm"); hProfile = cmsOpenProfileFromFile("lcmstiff8.icm", "w"); // Create linearization Lin = CreateLinear(); Step = CreateStep(); PreLinear[0] = Lin; PreLinear[1] = Step; PreLinear[2] = Step; AToB0 = cmsPipelineAlloc(0, 3, 3); cmsPipelineInsertStage(AToB0, cmsAT_BEGIN, cmsStageAllocToneCurves(0, 3, PreLinear)); cmsSetColorSpace(hProfile, cmsSigLabData); cmsSetPCS(hProfile, cmsSigLabData); cmsSetDeviceClass(hProfile, cmsSigLinkClass); cmsSetProfileVersion(hProfile, 4.2); cmsWriteTag(hProfile, cmsSigAToB0Tag, AToB0); SetTextTags(hProfile); cmsCloseProfile(hProfile); cmsFreeToneCurve(Lin); cmsFreeToneCurve(Step); cmsPipelineFree(AToB0); fprintf(stderr, "Done.\n"); return 0; }
21
./little-cms/utils/samples/itufax.c
// // Little cms // Copyright (C) 1998-2003 Marti Maria // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "lcms.h" // This is a sample on how to build a profile for decoding ITU T.42/Fax JPEG // streams. The profile has an additional ability in the input direction of // gamut compress values between 85 < a < -85 and -75 < b < 125. This conforms // the default range for ITU/T.42 -- See RFC 2301, section 6.2.3 for details // L* = [0, 100] // a* = [û85, 85] // b* = [û75, 125] // These functions does convert the encoding of ITUFAX to floating point static void ITU2Lab(WORD In[3], LPcmsCIELab Lab) { Lab -> L = (double) In[0] / 655.35; Lab -> a = (double) 170.* (In[1] - 32768.) / 65535.; Lab -> b = (double) 200.* (In[2] - 24576.) / 65535.; } static void Lab2ITU(LPcmsCIELab Lab, WORD Out[3]) { Out[0] = (WORD) floor((double) (Lab -> L / 100.)* 65535. + 0.5); Out[1] = (WORD) floor((double) (Lab -> a / 170.)* 65535. + 32768. + 0.5); Out[2] = (WORD) floor((double) (Lab -> b / 200.)* 65535. + 24576. + 0.5); } // These are the samplers-- They are passed as callbacks to cmsSample3DGrid() // then, cmsSample3DGrid() will sweel whole Lab gamut calling these functions // once for each node. In[] will contain the Lab PCS value to convert to ITUFAX // on InputDirection, or the ITUFAX value to convert to Lab in OutputDirection // You can change the number of sample points if desired, the algorithm will // remain same. 33 points gives good accurancy, but you can reduce to 22 or less // is space is critical #define GRID_POINTS 33 static int InputDirection(register WORD In[], register WORD Out[], register LPVOID Cargo) { cmsCIELab Lab; cmsLabEncoded2Float(&Lab, In); cmsClampLab(&Lab, 85, -85, 125, -75); // This function does the necessary gamut remapping Lab2ITU(&Lab, Out); return TRUE; } static int OutputDirection(register WORD In[], register WORD Out[], register LPVOID Cargo) { cmsCIELab Lab; ITU2Lab(In, &Lab); cmsFloat2LabEncoded(Out, &Lab); return TRUE; } // The main entry point. Just create a profile an populate it with required tags. // note that cmsOpenProfileFromFile("itufax.icm", "w") will NOT delete the file // if already exists. This is for obvious safety reasons. int main(int argc, char *argv[]) { LPLUT AToB0, BToA0; cmsHPROFILE hProfile; fprintf(stderr, "Creating itufax.icm..."); unlink("itufax.icm"); hProfile = cmsOpenProfileFromFile("itufax.icm", "w"); AToB0 = cmsAllocLUT(); BToA0 = cmsAllocLUT(); cmsAlloc3DGrid(AToB0, GRID_POINTS, 3, 3); cmsAlloc3DGrid(BToA0, GRID_POINTS, 3, 3); cmsSample3DGrid(AToB0, InputDirection, NULL, 0); cmsSample3DGrid(BToA0, OutputDirection, NULL, 0); cmsAddTag(hProfile, icSigAToB0Tag, AToB0); cmsAddTag(hProfile, icSigBToA0Tag, BToA0); cmsSetColorSpace(hProfile, icSigLabData); cmsSetPCS(hProfile, icSigLabData); cmsSetDeviceClass(hProfile, icSigColorSpaceClass); cmsAddTag(hProfile, icSigProfileDescriptionTag, "ITU T.42/Fax JPEG CIEL*a*b*"); cmsAddTag(hProfile, icSigCopyrightTag, "No Copyright, use freely."); cmsAddTag(hProfile, icSigDeviceMfgDescTag, "Little cms"); cmsAddTag(hProfile, icSigDeviceModelDescTag, "ITU T.42/Fax JPEG CIEL*a*b*"); cmsCloseProfile(hProfile); cmsFreeLUT(AToB0); cmsFreeLUT(BToA0); fprintf(stderr, "Done.\n"); return 0; }
22
./little-cms/utils/samples/mkcmy.c
// // Little cms // Copyright (C) 1998-2003 Marti Maria // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THIS SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, // EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY // WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL MARTI MARIA BE LIABLE FOR ANY SPECIAL, INCIDENTAL, // INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, // OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF // LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE // OF THIS SOFTWARE. // // Version 1.12 #include "lcms.h" typedef struct { cmsHPROFILE hLab; cmsHPROFILE hRGB; cmsHTRANSFORM Lab2RGB; cmsHTRANSFORM RGB2Lab; } CARGO, FAR* LPCARGO; // Our space will be CIE primaries plus a gamma of 4.5 static int Forward(register WORD In[], register WORD Out[], register LPVOID Cargo) { LPCARGO C = (LPCARGO) Cargo; WORD RGB[3]; cmsCIELab Lab; cmsLabEncoded2Float(&Lab, In); printf("%g %g %g\n", Lab.L, Lab.a, Lab.b); cmsDoTransform(C ->Lab2RGB, In, &RGB, 1); Out[0] = 0xFFFF - RGB[0]; // Our CMY is negative of RGB Out[1] = 0xFFFF - RGB[1]; Out[2] = 0xFFFF - RGB[2]; return TRUE; } static int Reverse(register WORD In[], register WORD Out[], register LPVOID Cargo) { LPCARGO C = (LPCARGO) Cargo; WORD RGB[3]; RGB[0] = 0xFFFF - In[0]; RGB[1] = 0xFFFF - In[1]; RGB[2] = 0xFFFF - In[2]; cmsDoTransform(C ->RGB2Lab, &RGB, Out, 1); return TRUE; } static void InitCargo(LPCARGO Cargo) { Cargo -> hLab = cmsCreateLabProfile(NULL); Cargo -> hRGB = cmsCreate_sRGBProfile(); Cargo->Lab2RGB = cmsCreateTransform(Cargo->hLab, TYPE_Lab_16, Cargo ->hRGB, TYPE_RGB_16, INTENT_RELATIVE_COLORIMETRIC, cmsFLAGS_NOTPRECALC); Cargo->RGB2Lab = cmsCreateTransform(Cargo ->hRGB, TYPE_RGB_16, Cargo ->hLab, TYPE_Lab_16, INTENT_RELATIVE_COLORIMETRIC, cmsFLAGS_NOTPRECALC); } static void FreeCargo(LPCARGO Cargo) { cmsDeleteTransform(Cargo ->Lab2RGB); cmsDeleteTransform(Cargo ->RGB2Lab); cmsCloseProfile(Cargo ->hLab); cmsCloseProfile(Cargo ->hRGB); } int main(void) { LPLUT AToB0, BToA0; CARGO Cargo; cmsHPROFILE hProfile; fprintf(stderr, "Creating lcmscmy.icm..."); InitCargo(&Cargo); hProfile = cmsCreateLabProfile(NULL); AToB0 = cmsAllocLUT(); BToA0 = cmsAllocLUT(); cmsAlloc3DGrid(AToB0, 25, 3, 3); cmsAlloc3DGrid(BToA0, 25, 3, 3); cmsSample3DGrid(AToB0, Reverse, &Cargo, 0); cmsSample3DGrid(BToA0, Forward, &Cargo, 0); cmsAddTag(hProfile, icSigAToB0Tag, AToB0); cmsAddTag(hProfile, icSigBToA0Tag, BToA0); cmsSetColorSpace(hProfile, icSigCmyData); cmsSetDeviceClass(hProfile, icSigOutputClass); cmsAddTag(hProfile, icSigProfileDescriptionTag, "CMY "); cmsAddTag(hProfile, icSigCopyrightTag, "Copyright (c) HP, 2007. All rights reserved."); cmsAddTag(hProfile, icSigDeviceMfgDescTag, "Little cms"); cmsAddTag(hProfile, icSigDeviceModelDescTag, "CMY space"); _cmsSaveProfile(hProfile, "lcmscmy.icm"); cmsFreeLUT(AToB0); cmsFreeLUT(BToA0); cmsCloseProfile(hProfile); FreeCargo(&Cargo); fprintf(stderr, "Done.\n"); return 0; }
23
./little-cms/utils/samples/wtpt.c
// // Little cms // Copyright (C) 1998-2000 Marti Maria // // THIS SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, // EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY // WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL MARTI MARIA BE LIABLE FOR ANY SPECIAL, INCIDENTAL, // INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, // OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF // LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE // OF THIS SOFTWARE. // // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Example: how to show white points of profiles #include "lcms.h" static void ShowWhitePoint(LPcmsCIEXYZ WtPt) { cmsCIELab Lab; cmsCIELCh LCh; cmsCIExyY xyY; char Buffer[1024]; _cmsIdentifyWhitePoint(Buffer, WtPt); printf("%s\n", Buffer); cmsXYZ2Lab(NULL, &Lab, WtPt); cmsLab2LCh(&LCh, &Lab); cmsXYZ2xyY(&xyY, WtPt); printf("XYZ=(%3.1f, %3.1f, %3.1f)\n", WtPt->X, WtPt->Y, WtPt->Z); printf("Lab=(%3.3f, %3.3f, %3.3f)\n", Lab.L, Lab.a, Lab.b); printf("(x,y)=(%3.3f, %3.3f)\n", xyY.x, xyY.y); printf("Hue=%3.2f, Chroma=%3.2f\n", LCh.h, LCh.C); printf("\n"); } int main (int argc, char *argv[]) { printf("Show media white of profiles, identifying black body locus. v2\n\n"); if (argc == 2) { cmsCIEXYZ WtPt; cmsHPROFILE hProfile = cmsOpenProfileFromFile(argv[1], "r"); printf("%s\n", cmsTakeProductName(hProfile)); cmsTakeMediaWhitePoint(&WtPt, hProfile); ShowWhitePoint(&WtPt); cmsCloseProfile(hProfile); } else { cmsCIEXYZ xyz; printf("usage:\n\nIf no parameters are given, then this program will\n"); printf("ask for XYZ value of media white. If parameter given, it must be\n"); printf("the profile to inspect.\n\n"); printf("X? "); scanf("%lf", &xyz.X); printf("Y? "); scanf("%lf", &xyz.Y); printf("Z? "); scanf("%lf", &xyz.Z); ShowWhitePoint(&xyz); } return 0; }
24
./little-cms/utils/samples/roundtrip.c
// // Little cms // Copyright (C) 1998-2011 Marti Maria // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION #include "lcms2.h" #include <math.h> static double VecDist(cmsUInt8Number bin[3], cmsUInt8Number bout[3]) { double rdist, gdist, bdist; rdist = fabs((double) bout[0] - bin[0]); gdist = fabs((double) bout[1] - bin[1]); bdist = fabs((double) bout[2] - bin[2]); return (sqrt((rdist*rdist + gdist*gdist + bdist*bdist))); } int main(int argc, char* argv[]) { int r, g, b; cmsUInt8Number RGB[3], RGB_OUT[3]; cmsHTRANSFORM xform; cmsHPROFILE hProfile; double err, SumX=0, SumX2=0, Peak = 0, n = 0; if (argc != 2) { printf("roundtrip <RGB icc profile>\n"); return 1; } hProfile = cmsOpenProfileFromFile(argv[1], "r"); xform = cmsCreateTransform(hProfile,TYPE_RGB_8, hProfile, TYPE_RGB_8, INTENT_RELATIVE_COLORIMETRIC, cmsFLAGS_NOOPTIMIZE); for (r=0; r< 256; r++) { printf("%d \r", r); for (g=0; g < 256; g++) { for (b=0; b < 256; b++) { RGB[0] = r; RGB[1] = g; RGB[2] = b; cmsDoTransform(xform, RGB, RGB_OUT, 1); err = VecDist(RGB, RGB_OUT); SumX += err; SumX2 += err * err; n += 1.0; if (err > Peak) Peak = err; } } } printf("Average %g\n", SumX / n); printf("Max %g\n", Peak); printf("Std %g\n", sqrt((n*SumX2 - SumX * SumX) / (n*(n-1)))); cmsCloseProfile(hProfile); cmsDeleteTransform(xform); return 0; }
25
./little-cms/utils/samples/mkgrayer.c
// // Little cms // Copyright (C) 1998-2003 Marti Maria // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "lcms.h" static int Forward(register WORD In[], register WORD Out[], register LPVOID Cargo) { cmsCIELab Lab; cmsLabEncoded2Float(&Lab, In); if (fabs(Lab.a) < 3 && fabs(Lab.b) < 3) { double L_01 = Lab.L / 100.0; WORD K; if (L_01 > 1) L_01 = 1; K = (WORD) floor(L_01* 65535.0 + 0.5); Out[0] = Out[1] = Out[2] = K; } else { Out[0] = 0xFFFF; Out[1] = 0; Out[2] = 0; } return TRUE; } int main(int argc, char *argv[]) { LPLUT BToA0; cmsHPROFILE hProfile; fprintf(stderr, "Creating interpol2.icc..."); unlink("interpol2.icc"); hProfile = cmsOpenProfileFromFile("interpol2.icc", "w8"); BToA0 = cmsAllocLUT(); cmsAlloc3DGrid(BToA0, 17, 3, 3); cmsSample3DGrid(BToA0, Forward, NULL, 0); cmsAddTag(hProfile, icSigBToA0Tag, BToA0); cmsSetColorSpace(hProfile, icSigRgbData); cmsSetPCS(hProfile, icSigLabData); cmsSetDeviceClass(hProfile, icSigOutputClass); cmsAddTag(hProfile, icSigProfileDescriptionTag, "Interpolation test"); cmsAddTag(hProfile, icSigCopyrightTag, "Copyright (c) HP 2007. All rights reserved."); cmsAddTag(hProfile, icSigDeviceMfgDescTag, "Little cms"); cmsAddTag(hProfile, icSigDeviceModelDescTag, "Interpolation test profile"); cmsCloseProfile(hProfile); cmsFreeLUT(BToA0); fprintf(stderr, "Done.\n"); return 0; }
26
./little-cms/utils/common/xgetopt.c
/* getopt.c */ #include <errno.h> #include <string.h> #include <stdio.h> int xoptind = 1; /* index of which argument is next */ char *xoptarg; /* pointer to argument of current option */ int xopterr = 0; /* allow error message */ static char *letP = NULL; /* remember next option char's location */ char SW = '-'; /* DOS switch character, either '-' or '/' */ /* Parse the command line options, System V style. Standard option syntax is: option ::= SW [optLetter]* [argLetter space* argument] */ int xgetopt(int argc, char *argv[], char *optionS) { unsigned char ch; char *optP; if (SW == 0) { SW = '/'; } if (argc > xoptind) { if (letP == NULL) { if ((letP = argv[xoptind]) == NULL || *(letP++) != SW) goto gopEOF; if (*letP == SW) { xoptind++; goto gopEOF; } } if (0 == (ch = *(letP++))) { xoptind++; goto gopEOF; } if (':' == ch || (optP = strchr(optionS, ch)) == NULL) goto gopError; if (':' == *(++optP)) { xoptind++; if (0 == *letP) { if (argc <= xoptind) goto gopError; letP = argv[xoptind++]; } xoptarg = letP; letP = NULL; } else { if (0 == *letP) { xoptind++; letP = NULL; } xoptarg = NULL; } return ch; } gopEOF: xoptarg = letP = NULL; return EOF; gopError: xoptarg = NULL; errno = EINVAL; if (xopterr) perror ("get command line option"); return ('?'); }
27
./little-cms/utils/common/vprf.c
//--------------------------------------------------------------------------------- // // Little Color Management System // Copyright (c) 1998-2010 Marti Maria Saguer // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //--------------------------------------------------------------------------------- // #include "utils.h" int Verbose = 0; static char ProgramName[256] = ""; void FatalError(const char *frm, ...) { va_list args; va_start(args, frm); fprintf(stderr, "[%s fatal error]: ", ProgramName); vfprintf(stderr, frm, args); fprintf(stderr, "\n"); va_end(args); exit(1); } // Show errors to the end user (unless quiet option) static void MyErrorLogHandler(cmsContext ContextID, cmsUInt32Number ErrorCode, const char *Text) { if (Verbose >= 0) fprintf(stderr, "[%s]: %s\n", ProgramName, Text); UTILS_UNUSED_PARAMETER(ErrorCode); UTILS_UNUSED_PARAMETER(ContextID); } void InitUtils(const char* PName) { strncpy(ProgramName, PName, sizeof(ProgramName)); ProgramName[sizeof(ProgramName)-1] = 0; cmsSetLogErrorHandler(MyErrorLogHandler); } // Virtual profiles are handled here. cmsHPROFILE OpenStockProfile(cmsContext ContextID, const char* File) { if (!File) return cmsCreate_sRGBProfileTHR(ContextID); if (cmsstrcasecmp(File, "*Lab2") == 0) return cmsCreateLab2ProfileTHR(ContextID, NULL); if (cmsstrcasecmp(File, "*Lab4") == 0) return cmsCreateLab4ProfileTHR(ContextID, NULL); if (cmsstrcasecmp(File, "*Lab") == 0) return cmsCreateLab4ProfileTHR(ContextID, NULL); if (cmsstrcasecmp(File, "*LabD65") == 0) { cmsCIExyY D65xyY; cmsWhitePointFromTemp( &D65xyY, 6504); return cmsCreateLab4ProfileTHR(ContextID, &D65xyY); } if (cmsstrcasecmp(File, "*XYZ") == 0) return cmsCreateXYZProfileTHR(ContextID); if (cmsstrcasecmp(File, "*Gray22") == 0) { cmsToneCurve* Curve = cmsBuildGamma(ContextID, 2.2); cmsHPROFILE hProfile = cmsCreateGrayProfileTHR(ContextID, cmsD50_xyY(), Curve); cmsFreeToneCurve(Curve); return hProfile; } if (cmsstrcasecmp(File, "*Gray30") == 0) { cmsToneCurve* Curve = cmsBuildGamma(ContextID, 3.0); cmsHPROFILE hProfile = cmsCreateGrayProfileTHR(ContextID, cmsD50_xyY(), Curve); cmsFreeToneCurve(Curve); return hProfile; } if (cmsstrcasecmp(File, "*srgb") == 0) return cmsCreate_sRGBProfileTHR(ContextID); if (cmsstrcasecmp(File, "*null") == 0) return cmsCreateNULLProfileTHR(ContextID); if (cmsstrcasecmp(File, "*Lin2222") == 0) { cmsToneCurve* Gamma = cmsBuildGamma(0, 2.2); cmsToneCurve* Gamma4[4]; cmsHPROFILE hProfile; Gamma4[0] = Gamma4[1] = Gamma4[2] = Gamma4[3] = Gamma; hProfile = cmsCreateLinearizationDeviceLink(cmsSigCmykData, Gamma4); cmsFreeToneCurve(Gamma); return hProfile; } return cmsOpenProfileFromFileTHR(ContextID, File, "r"); } // Help on available built-ins void PrintBuiltins(void) { fprintf(stderr, "\nBuilt-in profiles:\n\n"); fprintf(stderr, "\t*Lab2 -- D50-based v2 CIEL*a*b\n" "\t*Lab4 -- D50-based v4 CIEL*a*b\n" "\t*Lab -- D50-based v4 CIEL*a*b\n" "\t*XYZ -- CIE XYZ (PCS)\n" "\t*sRGB -- sRGB color space\n" "\t*Gray22 - Monochrome of Gamma 2.2\n" "\t*Gray30 - Monochrome of Gamma 3.0\n" "\t*null - Monochrome black for all input\n" "\t*Lin2222- CMYK linearization of gamma 2.2 on each channel\n"); } // Auxiliar for printing information on profile static void PrintInfo(cmsHPROFILE h, cmsInfoType Info) { char* text; int len; len = cmsGetProfileInfoASCII(h, Info, "en", "US", NULL, 0); if (len == 0) return; text = malloc(len * sizeof(char)); if (text == NULL) return; cmsGetProfileInfoASCII(h, Info, "en", "US", text, len); if (strlen(text) > 0) printf("%s\n", text); free(text); } // Displays the colorant table static void PrintColorantTable(cmsHPROFILE hInput, cmsTagSignature Sig, const char* Title) { cmsNAMEDCOLORLIST* list; int i, n; if (cmsIsTag(hInput, Sig)) { printf("%s:\n", Title); list = cmsReadTag(hInput, Sig); if (list == NULL) { printf("(Unavailable)\n"); return; } n = cmsNamedColorCount(list); for (i=0; i < n; i++) { char Name[cmsMAX_PATH]; cmsNamedColorInfo(list, i, Name, NULL, NULL, NULL, NULL); printf("\t%s\n", Name); } printf("\n"); } } void PrintProfileInformation(cmsHPROFILE hInput) { PrintInfo(hInput, cmsInfoDescription); PrintInfo(hInput, cmsInfoManufacturer); PrintInfo(hInput, cmsInfoModel); PrintInfo(hInput, cmsInfoCopyright); if (Verbose > 2) { PrintColorantTable(hInput, cmsSigColorantTableTag, "Input colorant table"); PrintColorantTable(hInput, cmsSigColorantTableOutTag, "Input colorant out table"); } printf("\n"); } // ----------------------------------------------------------------------------- void PrintRenderingIntents(void) { cmsUInt32Number Codes[200]; char* Descriptions[200]; cmsUInt32Number n, i; fprintf(stderr, "%ct<n> rendering intent:\n\n", SW); n = cmsGetSupportedIntents(200, Codes, Descriptions); for (i=0; i < n; i++) { fprintf(stderr, "\t%u - %s\n", Codes[i], Descriptions[i]); } fprintf(stderr, "\n"); } // ------------------------------------------------------------------------------ cmsBool SaveMemoryBlock(const cmsUInt8Number* Buffer, cmsUInt32Number dwLen, const char* Filename) { FILE* out = fopen(Filename, "wb"); if (out == NULL) { FatalError("Cannot create '%s'", Filename); return FALSE; } if (fwrite(Buffer, 1, dwLen, out) != dwLen) { FatalError("Cannot write %ld bytes to %s", dwLen, Filename); return FALSE; } if (fclose(out) != 0) { FatalError("Error flushing file '%s'", Filename); return FALSE; } return TRUE; } // ------------------------------------------------------------------------------ // Return a pixel type on depending on the number of channels int PixelTypeFromChanCount(int ColorChannels) { switch (ColorChannels) { case 1: return PT_GRAY; case 2: return PT_MCH2; case 3: return PT_MCH3; case 4: return PT_CMYK; case 5: return PT_MCH5; case 6: return PT_MCH6; case 7: return PT_MCH7; case 8: return PT_MCH8; case 9: return PT_MCH9; case 10: return PT_MCH10; case 11: return PT_MCH11; case 12: return PT_MCH12; case 13: return PT_MCH13; case 14: return PT_MCH14; case 15: return PT_MCH15; default: FatalError("What a weird separation of %d channels?!?!", ColorChannels); return -1; } } // ------------------------------------------------------------------------------ // Return number of channels of pixel type int ChanCountFromPixelType(int ColorChannels) { switch (ColorChannels) { case PT_GRAY: return 1; case PT_RGB: case PT_CMY: case PT_Lab: case PT_YUV: case PT_YCbCr: return 3; case PT_CMYK: return 4 ; case PT_MCH2: return 2 ; case PT_MCH3: return 3 ; case PT_MCH4: return 4 ; case PT_MCH5: return 5 ; case PT_MCH6: return 6 ; case PT_MCH7: return 7 ; case PT_MCH8: return 8 ; case PT_MCH9: return 9 ; case PT_MCH10: return 10; case PT_MCH11: return 11; case PT_MCH12: return 12; case PT_MCH13: return 12; case PT_MCH14: return 14; case PT_MCH15: return 15; default: FatalError("Unsupported color space of %d channels", ColorChannels); return -1; } }
28
./little-cms/utils/jpgicc/jpgicc.c
//--------------------------------------------------------------------------------- // // Little Color Management System // Copyright (c) 1998-2010 Marti Maria Saguer // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // This program does apply profiles to (some) JPEG files #include "utils.h" #include "jpeglib.h" #include "iccjpeg.h" // Flags static cmsBool BlackPointCompensation = FALSE; static cmsBool IgnoreEmbedded = FALSE; static cmsBool GamutCheck = FALSE; static cmsBool lIsITUFax = FALSE; static cmsBool lIsPhotoshopApp13 = FALSE; static cmsBool lIsEXIF; static cmsBool lIsDeviceLink = FALSE; static cmsBool EmbedProfile = FALSE; static const char* SaveEmbedded = NULL; static int Intent = INTENT_PERCEPTUAL; static int ProofingIntent = INTENT_PERCEPTUAL; static int PrecalcMode = 1; static int jpegQuality = 75; static cmsFloat64Number ObserverAdaptationState = 0; static char *cInpProf = NULL; static char *cOutProf = NULL; static char *cProofing = NULL; static FILE * InFile; static FILE * OutFile; static struct jpeg_decompress_struct Decompressor; static struct jpeg_compress_struct Compressor; static struct my_error_mgr { struct jpeg_error_mgr pub; // "public" fields void* Cargo; // "private" fields } ErrorHandler; cmsUInt16Number Alarm[4] = {128,128,128,0}; // Out of mem static void OutOfMem(size_t size) { FatalError("Out of memory on allocating %d bytes.", size); } static void my_error_exit (j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message) (cinfo, buffer); FatalError(buffer); } /* Definition of the APPn Markers Defined for continuous-tone G3FAX The application code APP1 initiates identification of the image as a G3FAX application and defines the spatial resolution and subsampling. This marker directly follows the SOI marker. The data format will be as follows: X'FFE1' (APP1), length, FAX identifier, version, spatial resolution. The above terms are defined as follows: Length: (Two octets) Total APP1 field octet count including the octet count itself, but excluding the APP1 marker. FAX identifier: (Six octets) X'47', X'33', X'46', X'41', X'58', X'00'. This X'00'-terminated string "G3FAX" uniquely identifies this APP1 marker. Version: (Two octets) X'07CA'. This string specifies the year of approval of the standard, for identification in the case of future revision (for example, 1994). Spatial Resolution: (Two octets) Lightness pixel density in pels/25.4 mm. The basic value is 200. Allowed values are 100, 200, 300, 400, 600 and 1200 pels/25.4 mm, with square (or equivalent) pels. NOTE û The functional equivalence of inch-based and mm-based resolutions is maintained. For example, the 200 ╫ 200 */ static cmsBool IsITUFax(jpeg_saved_marker_ptr ptr) { while (ptr) { if (ptr -> marker == (JPEG_APP0 + 1) && ptr -> data_length > 5) { const char* data = (const char*) ptr -> data; if (strcmp(data, "G3FAX") == 0) return TRUE; } ptr = ptr -> next; } return FALSE; } // Save a ITU T.42/Fax marker with defaults on boundaries. This is the only mode we support right now. static void SetITUFax(j_compress_ptr cinfo) { unsigned char Marker[] = "G3FAX\x00\0x07\xCA\x00\xC8"; jpeg_write_marker(cinfo, (JPEG_APP0 + 1), Marker, 10); } // Build a profile for decoding ITU T.42/Fax JPEG streams. // The profile has an additional ability in the input direction of // gamut compress values between 85 < a < -85 and -75 < b < 125. This conforms // the default range for ITU/T.42 -- See RFC 2301, section 6.2.3 for details // L* = [0, 100] // a* = [û85, 85] // b* = [û75, 125] // These functions does convert the encoding of ITUFAX to floating point // and vice-versa. No gamut mapping is performed yet. static void ITU2Lab(const cmsUInt16Number In[3], cmsCIELab* Lab) { Lab -> L = (double) In[0] / 655.35; Lab -> a = (double) 170.* (In[1] - 32768.) / 65535.; Lab -> b = (double) 200.* (In[2] - 24576.) / 65535.; } static void Lab2ITU(const cmsCIELab* Lab, cmsUInt16Number Out[3]) { Out[0] = (cmsUInt16Number) floor((double) (Lab -> L / 100.)* 65535. ); Out[1] = (cmsUInt16Number) floor((double) (Lab -> a / 170.)* 65535. + 32768. ); Out[2] = (cmsUInt16Number) floor((double) (Lab -> b / 200.)* 65535. + 24576. ); } // These are the samplers-- They are passed as callbacks to cmsStageSampleCLut16bit() // then, cmsSample3DGrid() will sweel whole Lab gamut calling these functions // once for each node. In[] will contain the Lab PCS value to convert to ITUFAX // on PCS2ITU, or the ITUFAX value to convert to Lab in ITU2PCS // You can change the number of sample points if desired, the algorithm will // remain same. 33 points gives good accurancy, but you can reduce to 22 or less // is space is critical #define GRID_POINTS 33 static int PCS2ITU(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo) { cmsCIELab Lab; cmsLabEncoded2Float(&Lab, In); cmsDesaturateLab(&Lab, 85, -85, 125, -75); // This function does the necessary gamut remapping Lab2ITU(&Lab, Out); return TRUE; UTILS_UNUSED_PARAMETER(Cargo); } static int ITU2PCS( register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo) { cmsCIELab Lab; ITU2Lab(In, &Lab); cmsFloat2LabEncoded(Out, &Lab); return TRUE; UTILS_UNUSED_PARAMETER(Cargo); } // This function does create the virtual input profile, which decodes ITU to the profile connection space static cmsHPROFILE CreateITU2PCS_ICC(void) { cmsHPROFILE hProfile; cmsPipeline* AToB0; cmsStage* ColorMap; AToB0 = cmsPipelineAlloc(0, 3, 3); if (AToB0 == NULL) return NULL; ColorMap = cmsStageAllocCLut16bit(0, GRID_POINTS, 3, 3, NULL); if (ColorMap == NULL) return NULL; cmsPipelineInsertStage(AToB0, cmsAT_BEGIN, ColorMap); cmsStageSampleCLut16bit(ColorMap, ITU2PCS, NULL, 0); hProfile = cmsCreateProfilePlaceholder(0); if (hProfile == NULL) { cmsPipelineFree(AToB0); return NULL; } cmsWriteTag(hProfile, cmsSigAToB0Tag, AToB0); cmsSetColorSpace(hProfile, cmsSigLabData); cmsSetPCS(hProfile, cmsSigLabData); cmsSetDeviceClass(hProfile, cmsSigColorSpaceClass); cmsPipelineFree(AToB0); return hProfile; } // This function does create the virtual output profile, with the necessary gamut mapping static cmsHPROFILE CreatePCS2ITU_ICC(void) { cmsHPROFILE hProfile; cmsPipeline* BToA0; cmsStage* ColorMap; BToA0 = cmsPipelineAlloc(0, 3, 3); if (BToA0 == NULL) return NULL; ColorMap = cmsStageAllocCLut16bit(0, GRID_POINTS, 3, 3, NULL); if (ColorMap == NULL) return NULL; cmsPipelineInsertStage(BToA0, cmsAT_BEGIN, ColorMap); cmsStageSampleCLut16bit(ColorMap, PCS2ITU, NULL, 0); hProfile = cmsCreateProfilePlaceholder(0); if (hProfile == NULL) { cmsPipelineFree(BToA0); return NULL; } cmsWriteTag(hProfile, cmsSigBToA0Tag, BToA0); cmsSetColorSpace(hProfile, cmsSigLabData); cmsSetPCS(hProfile, cmsSigLabData); cmsSetDeviceClass(hProfile, cmsSigColorSpaceClass); cmsPipelineFree(BToA0); return hProfile; } #define PS_FIXED_TO_FLOAT(h, l) ((float) (h) + ((float) (l)/(1<<16))) static cmsBool ProcessPhotoshopAPP13(JOCTET FAR *data, int datalen) { int i; for (i = 14; i < datalen; ) { long len; unsigned int type; if (!(GETJOCTET(data[i] ) == 0x38 && GETJOCTET(data[i+1]) == 0x42 && GETJOCTET(data[i+2]) == 0x49 && GETJOCTET(data[i+3]) == 0x4D)) break; // Not recognized i += 4; // identifying string type = (unsigned int) (GETJOCTET(data[i]<<8) + GETJOCTET(data[i+1])); i += 2; // resource type i += GETJOCTET(data[i]) + ((GETJOCTET(data[i]) & 1) ? 1 : 2); // resource name len = ((((GETJOCTET(data[i]<<8) + GETJOCTET(data[i+1]))<<8) + GETJOCTET(data[i+2]))<<8) + GETJOCTET(data[i+3]); i += 4; // Size if (type == 0x03ED && len >= 16) { Decompressor.X_density = (UINT16) PS_FIXED_TO_FLOAT(GETJOCTET(data[i]<<8) + GETJOCTET(data[i+1]), GETJOCTET(data[i+2]<<8) + GETJOCTET(data[i+3])); Decompressor.Y_density = (UINT16) PS_FIXED_TO_FLOAT(GETJOCTET(data[i+8]<<8) + GETJOCTET(data[i+9]), GETJOCTET(data[i+10]<<8) + GETJOCTET(data[i+11])); // Set the density unit to 1 since the // Vertical and Horizontal resolutions // are specified in Pixels per inch Decompressor.density_unit = 0x01; return TRUE; } i += len + ((len & 1) ? 1 : 0); // Alignment } return FALSE; } static cmsBool HandlePhotoshopAPP13(jpeg_saved_marker_ptr ptr) { while (ptr) { if (ptr -> marker == (JPEG_APP0 + 13) && ptr -> data_length > 9) { JOCTET FAR* data = ptr -> data; if(GETJOCTET(data[0]) == 0x50 && GETJOCTET(data[1]) == 0x68 && GETJOCTET(data[2]) == 0x6F && GETJOCTET(data[3]) == 0x74 && GETJOCTET(data[4]) == 0x6F && GETJOCTET(data[5]) == 0x73 && GETJOCTET(data[6]) == 0x68 && GETJOCTET(data[7]) == 0x6F && GETJOCTET(data[8]) == 0x70) { ProcessPhotoshopAPP13(data, ptr -> data_length); return TRUE; } } ptr = ptr -> next; } return FALSE; } typedef unsigned short uint16_t; typedef unsigned char uint8_t; typedef unsigned int uint32_t; #define INTEL_BYTE_ORDER 0x4949 #define XRESOLUTION 0x011a #define YRESOLUTION 0x011b #define RESOLUTION_UNIT 0x128 // Read a 16-bit word static uint16_t read16(uint8_t* arr, int pos, int swapBytes) { uint8_t b1 = arr[pos]; uint8_t b2 = arr[pos+1]; return (swapBytes) ? ((b2 << 8) | b1) : ((b1 << 8) | b2); } // Read a 32-bit word static uint32_t read32(uint8_t* arr, int pos, int swapBytes) { if(!swapBytes) { return (arr[pos] << 24) | (arr[pos+1] << 16) | (arr[pos+2] << 8) | arr[pos+3]; } return arr[pos] | (arr[pos+1] << 8) | (arr[pos+2] << 16) | (arr[pos+3] << 24); } static int read_tag(uint8_t* arr, int pos, int swapBytes, void* dest) { // Format should be 5 over here (rational) uint32_t format = read16(arr, pos + 2, swapBytes); // Components should be 1 uint32_t components = read32(arr, pos + 4, swapBytes); // Points to the value uint32_t offset; // sanity if (components != 1) return 0; if (format == 3) offset = pos + 8; else offset = read32(arr, pos + 8, swapBytes); switch (format) { case 5: // Rational { double num = read32(arr, offset, swapBytes); double den = read32(arr, offset + 4, swapBytes); *(double *) dest = num / den; } break; case 3: // uint 16 *(int*) dest = read16(arr, offset, swapBytes); break; default: return 0; } return 1; } // Handler for EXIF data static cmsBool HandleEXIF(struct jpeg_decompress_struct* cinfo) { jpeg_saved_marker_ptr ptr; uint32_t ifd_ofs; int pos = 0, swapBytes = 0; uint32_t i, numEntries; double XRes = -1, YRes = -1; int Unit = 2; // Inches for (ptr = cinfo ->marker_list; ptr; ptr = ptr ->next) { if ((ptr ->marker == JPEG_APP0+1) && ptr ->data_length > 6) { JOCTET FAR* data = ptr -> data; if (memcmp(data, "Exif\0\0", 6) == 0) { data += 6; // Skip EXIF marker // 8 byte TIFF header // first two determine byte order pos = 0; if (read16(data, pos, 0) == INTEL_BYTE_ORDER) { swapBytes = 1; } pos += 2; // next two bytes are always 0x002A (TIFF version) pos += 2; // offset to Image File Directory (includes the previous 8 bytes) ifd_ofs = read32(data, pos, swapBytes); // Search the directory for resolution tags numEntries = read16(data, ifd_ofs, swapBytes); for (i=0; i < numEntries; i++) { uint32_t entryOffset = ifd_ofs + 2 + (12 * i); uint32_t tag = read16(data, entryOffset, swapBytes); switch (tag) { case RESOLUTION_UNIT: if (!read_tag(data, entryOffset, swapBytes, &Unit)) return FALSE; break; case XRESOLUTION: if (!read_tag(data, entryOffset, swapBytes, &XRes)) return FALSE; break; case YRESOLUTION: if (!read_tag(data, entryOffset, swapBytes, &YRes)) return FALSE; break; default:; } } // Proceed if all found if (XRes != -1 && YRes != -1) { // 1 = None // 2 = inches // 3 = cm switch (Unit) { case 2: cinfo ->X_density = (UINT16) floor(XRes + 0.5); cinfo ->Y_density = (UINT16) floor(YRes + 0.5); break; case 1: cinfo ->X_density = (UINT16) floor(XRes * 2.54 + 0.5); cinfo ->Y_density = (UINT16) floor(YRes * 2.54 + 0.5); break; default: return FALSE; } cinfo ->density_unit = 1; /* 1 for dots/inch, or 2 for dots/cm.*/ } } } } return FALSE; } static cmsBool OpenInput(const char* FileName) { int m; lIsITUFax = FALSE; InFile = fopen(FileName, "rb"); if (InFile == NULL) { FatalError("Cannot open '%s'", FileName); } // Now we can initialize the JPEG decompression object. Decompressor.err = jpeg_std_error(&ErrorHandler.pub); ErrorHandler.pub.error_exit = my_error_exit; ErrorHandler.pub.output_message = my_error_exit; jpeg_create_decompress(&Decompressor); jpeg_stdio_src(&Decompressor, InFile); for (m = 0; m < 16; m++) jpeg_save_markers(&Decompressor, JPEG_APP0 + m, 0xFFFF); // setup_read_icc_profile(&Decompressor); fseek(InFile, 0, SEEK_SET); jpeg_read_header(&Decompressor, TRUE); return TRUE; } static cmsBool OpenOutput(const char* FileName) { OutFile = fopen(FileName, "wb"); if (OutFile == NULL) { FatalError("Cannot create '%s'", FileName); } Compressor.err = jpeg_std_error(&ErrorHandler.pub); ErrorHandler.pub.error_exit = my_error_exit; ErrorHandler.pub.output_message = my_error_exit; Compressor.input_components = Compressor.num_components = 4; jpeg_create_compress(&Compressor); jpeg_stdio_dest(&Compressor, OutFile); return TRUE; } static cmsBool Done(void) { jpeg_destroy_decompress(&Decompressor); jpeg_destroy_compress(&Compressor); return fclose(InFile) + fclose(OutFile); } // Build up the pixeltype descriptor static cmsUInt32Number GetInputPixelType(void) { int space, bps, extra, ColorChannels, Flavor; lIsITUFax = IsITUFax(Decompressor.marker_list); lIsPhotoshopApp13 = HandlePhotoshopAPP13(Decompressor.marker_list); lIsEXIF = HandleEXIF(&Decompressor); ColorChannels = Decompressor.num_components; extra = 0; // Alpha = None bps = 1; // 8 bits Flavor = 0; // Vanilla if (lIsITUFax) { space = PT_Lab; Decompressor.out_color_space = JCS_YCbCr; // Fake to don't touch } else switch (Decompressor.jpeg_color_space) { case JCS_GRAYSCALE: // monochrome space = PT_GRAY; Decompressor.out_color_space = JCS_GRAYSCALE; break; case JCS_RGB: // red/green/blue space = PT_RGB; Decompressor.out_color_space = JCS_RGB; break; case JCS_YCbCr: // Y/Cb/Cr (also known as YUV) space = PT_RGB; // Let IJG code to do the conversion Decompressor.out_color_space = JCS_RGB; break; case JCS_CMYK: // C/M/Y/K space = PT_CMYK; Decompressor.out_color_space = JCS_CMYK; if (Decompressor.saw_Adobe_marker) // Adobe keeps CMYK inverted, so change flavor Flavor = 1; // from vanilla to chocolate break; case JCS_YCCK: // Y/Cb/Cr/K space = PT_CMYK; Decompressor.out_color_space = JCS_CMYK; if (Decompressor.saw_Adobe_marker) // ditto Flavor = 1; break; default: FatalError("Unsupported color space (0x%x)", Decompressor.jpeg_color_space); return 0; } return (EXTRA_SH(extra)|CHANNELS_SH(ColorChannels)|BYTES_SH(bps)|COLORSPACE_SH(space)|FLAVOR_SH(Flavor)); } // Rearrange pixel type to build output descriptor static cmsUInt32Number ComputeOutputFormatDescriptor(cmsUInt32Number dwInput, int OutColorSpace) { int IsPlanar = T_PLANAR(dwInput); int Channels = 0; int Flavor = 0; switch (OutColorSpace) { case PT_GRAY: Channels = 1; break; case PT_RGB: case PT_CMY: case PT_Lab: case PT_YUV: case PT_YCbCr: Channels = 3; break; case PT_CMYK: if (Compressor.write_Adobe_marker) // Adobe keeps CMYK inverted, so change flavor to chocolate Flavor = 1; Channels = 4; break; default: FatalError("Unsupported output color space"); } return (COLORSPACE_SH(OutColorSpace)|PLANAR_SH(IsPlanar)|CHANNELS_SH(Channels)|BYTES_SH(1)|FLAVOR_SH(Flavor)); } // Equivalence between ICC color spaces and lcms color spaces static int GetProfileColorSpace(cmsHPROFILE hProfile) { cmsColorSpaceSignature ProfileSpace = cmsGetColorSpace(hProfile); return _cmsLCMScolorSpace(ProfileSpace); } static int GetDevicelinkColorSpace(cmsHPROFILE hProfile) { cmsColorSpaceSignature ProfileSpace = cmsGetPCS(hProfile); return _cmsLCMScolorSpace(ProfileSpace); } // From TRANSUPP static void jcopy_markers_execute(j_decompress_ptr srcinfo, j_compress_ptr dstinfo) { jpeg_saved_marker_ptr marker; /* In the current implementation, we don't actually need to examine the * option flag here; we just copy everything that got saved. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers * if the encoder library already wrote one. */ for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) { if (dstinfo->write_JFIF_header && marker->marker == JPEG_APP0 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x4A && GETJOCTET(marker->data[1]) == 0x46 && GETJOCTET(marker->data[2]) == 0x49 && GETJOCTET(marker->data[3]) == 0x46 && GETJOCTET(marker->data[4]) == 0) continue; /* reject duplicate JFIF */ if (dstinfo->write_Adobe_marker && marker->marker == JPEG_APP0+14 && marker->data_length >= 5 && GETJOCTET(marker->data[0]) == 0x41 && GETJOCTET(marker->data[1]) == 0x64 && GETJOCTET(marker->data[2]) == 0x6F && GETJOCTET(marker->data[3]) == 0x62 && GETJOCTET(marker->data[4]) == 0x65) continue; /* reject duplicate Adobe */ jpeg_write_marker(dstinfo, marker->marker, marker->data, marker->data_length); } } static void WriteOutputFields(int OutputColorSpace) { J_COLOR_SPACE in_space, jpeg_space; int components; switch (OutputColorSpace) { case PT_GRAY: in_space = jpeg_space = JCS_GRAYSCALE; components = 1; break; case PT_RGB: in_space = JCS_RGB; jpeg_space = JCS_YCbCr; components = 3; break; // red/green/blue case PT_YCbCr: in_space = jpeg_space = JCS_YCbCr; components = 3; break; // Y/Cb/Cr (also known as YUV) case PT_CMYK: in_space = JCS_CMYK; jpeg_space = JCS_YCCK; components = 4; break; // C/M/Y/components case PT_Lab: in_space = jpeg_space = JCS_YCbCr; components = 3; break; // Fake to don't touch default: FatalError("Unsupported output color space"); return; } if (jpegQuality >= 100) { // avoid destructive conversion when asking for lossless compression jpeg_space = in_space; } Compressor.in_color_space = in_space; Compressor.jpeg_color_space = jpeg_space; Compressor.input_components = Compressor.num_components = components; jpeg_set_defaults(&Compressor); jpeg_set_colorspace(&Compressor, jpeg_space); // Make sure to pass resolution through if (OutputColorSpace == PT_CMYK) Compressor.write_JFIF_header = 1; // Avoid subsampling on high quality factor jpeg_set_quality(&Compressor, jpegQuality, 1); if (jpegQuality >= 70) { int i; for(i=0; i < Compressor.num_components; i++) { Compressor.comp_info[i].h_samp_factor = 1; Compressor.comp_info[i].v_samp_factor = 1; } } } static void DoEmbedProfile(const char* ProfileFile) { FILE* f; size_t size, EmbedLen; cmsUInt8Number* EmbedBuffer; f = fopen(ProfileFile, "rb"); if (f == NULL) return; size = cmsfilelength(f); EmbedBuffer = (cmsUInt8Number*) malloc(size + 1); EmbedLen = fread(EmbedBuffer, 1, size, f); fclose(f); EmbedBuffer[EmbedLen] = 0; write_icc_profile (&Compressor, EmbedBuffer, EmbedLen); free(EmbedBuffer); } static int DoTransform(cmsHTRANSFORM hXForm, int OutputColorSpace) { JSAMPROW ScanLineIn; JSAMPROW ScanLineOut; //Preserve resolution values from the original // (Thanks to Robert Bergs for finding out this bug) Compressor.density_unit = Decompressor.density_unit; Compressor.X_density = Decompressor.X_density; Compressor.Y_density = Decompressor.Y_density; // Compressor.write_JFIF_header = 1; jpeg_start_decompress(&Decompressor); jpeg_start_compress(&Compressor, TRUE); if (OutputColorSpace == PT_Lab) SetITUFax(&Compressor); // Embed the profile if needed if (EmbedProfile && cOutProf) DoEmbedProfile(cOutProf); ScanLineIn = (JSAMPROW) malloc(Decompressor.output_width * Decompressor.num_components); ScanLineOut = (JSAMPROW) malloc(Compressor.image_width * Compressor.num_components); while (Decompressor.output_scanline < Decompressor.output_height) { jpeg_read_scanlines(&Decompressor, &ScanLineIn, 1); cmsDoTransform(hXForm, ScanLineIn, ScanLineOut, Decompressor.output_width); jpeg_write_scanlines(&Compressor, &ScanLineOut, 1); } free(ScanLineIn); free(ScanLineOut); jpeg_finish_decompress(&Decompressor); jpeg_finish_compress(&Compressor); return TRUE; } // Transform one image static int TransformImage(char *cDefInpProf, char *cOutProf) { cmsHPROFILE hIn, hOut, hProof; cmsHTRANSFORM xform; cmsUInt32Number wInput, wOutput; int OutputColorSpace; cmsUInt32Number dwFlags = 0; cmsUInt32Number EmbedLen; cmsUInt8Number* EmbedBuffer; cmsSetAdaptationState(ObserverAdaptationState); if (BlackPointCompensation) { dwFlags |= cmsFLAGS_BLACKPOINTCOMPENSATION; } switch (PrecalcMode) { case 0: dwFlags |= cmsFLAGS_NOOPTIMIZE; break; case 2: dwFlags |= cmsFLAGS_HIGHRESPRECALC; break; case 3: dwFlags |= cmsFLAGS_LOWRESPRECALC; break; default:; } if (GamutCheck) { dwFlags |= cmsFLAGS_GAMUTCHECK; cmsSetAlarmCodes(Alarm); } // Take input color space wInput = GetInputPixelType(); if (lIsDeviceLink) { hIn = cmsOpenProfileFromFile(cDefInpProf, "r"); hOut = NULL; hProof = NULL; } else { if (!IgnoreEmbedded && read_icc_profile(&Decompressor, &EmbedBuffer, &EmbedLen)) { hIn = cmsOpenProfileFromMem(EmbedBuffer, EmbedLen); if (Verbose) { fprintf(stdout, " (Embedded profile found)\n"); PrintProfileInformation(hIn); fflush(stdout); } if (hIn != NULL && SaveEmbedded != NULL) SaveMemoryBlock(EmbedBuffer, EmbedLen, SaveEmbedded); free(EmbedBuffer); } else { // Default for ITU/Fax if (cDefInpProf == NULL && T_COLORSPACE(wInput) == PT_Lab) cDefInpProf = "*Lab"; if (cDefInpProf != NULL && cmsstrcasecmp(cDefInpProf, "*lab") == 0) hIn = CreateITU2PCS_ICC(); else hIn = OpenStockProfile(0, cDefInpProf); } if (cOutProf != NULL && cmsstrcasecmp(cOutProf, "*lab") == 0) hOut = CreatePCS2ITU_ICC(); else hOut = OpenStockProfile(0, cOutProf); hProof = NULL; if (cProofing != NULL) { hProof = OpenStockProfile(0, cProofing); if (hProof == NULL) { FatalError("Proofing profile couldn't be read."); } dwFlags |= cmsFLAGS_SOFTPROOFING; } } if (!hIn) FatalError("Input profile couldn't be read."); if (!hOut) FatalError("Output profile couldn't be read."); // Assure both, input profile and input JPEG are on same colorspace if (cmsGetColorSpace(hIn) != _cmsICCcolorSpace(T_COLORSPACE(wInput))) FatalError("Input profile is not operating in proper color space"); // Output colorspace is given by output profile if (lIsDeviceLink) { OutputColorSpace = GetDevicelinkColorSpace(hIn); } else { OutputColorSpace = GetProfileColorSpace(hOut); } jpeg_copy_critical_parameters(&Decompressor, &Compressor); WriteOutputFields(OutputColorSpace); wOutput = ComputeOutputFormatDescriptor(wInput, OutputColorSpace); xform = cmsCreateProofingTransform(hIn, wInput, hOut, wOutput, hProof, Intent, ProofingIntent, dwFlags); if (xform == NULL) FatalError("Cannot transform by using the profiles"); DoTransform(xform, OutputColorSpace); jcopy_markers_execute(&Decompressor, &Compressor); cmsDeleteTransform(xform); cmsCloseProfile(hIn); cmsCloseProfile(hOut); if (hProof) cmsCloseProfile(hProof); return 1; } // Simply print help static void Help(int level) { fprintf(stderr, "little cms ICC profile applier for JPEG - v3.2 [LittleCMS %2.2f]\n\n", LCMS_VERSION / 1000.0); switch(level) { default: case 0: fprintf(stderr, "usage: jpgicc [flags] input.jpg output.jpg\n"); fprintf(stderr, "\nflags:\n\n"); fprintf(stderr, "%cv - Verbose\n", SW); fprintf(stderr, "%ci<profile> - Input profile (defaults to sRGB)\n", SW); fprintf(stderr, "%co<profile> - Output profile (defaults to sRGB)\n", SW); PrintRenderingIntents(); fprintf(stderr, "%cb - Black point compensation\n", SW); fprintf(stderr, "%cd<0..1> - Observer adaptation state (abs.col. only)\n", SW); fprintf(stderr, "%cn - Ignore embedded profile\n", SW); fprintf(stderr, "%ce - Embed destination profile\n", SW); fprintf(stderr, "%cs<new profile> - Save embedded profile as <new profile>\n", SW); fprintf(stderr, "\n"); fprintf(stderr, "%cc<0,1,2,3> - Precalculates transform (0=Off, 1=Normal, 2=Hi-res, 3=LoRes) [defaults to 1]\n", SW); fprintf(stderr, "\n"); fprintf(stderr, "%cp<profile> - Soft proof profile\n", SW); fprintf(stderr, "%cm<0,1,2,3> - SoftProof intent\n", SW); fprintf(stderr, "%cg - Marks out-of-gamut colors on softproof\n", SW); fprintf(stderr, "%c!<r>,<g>,<b> - Out-of-gamut marker channel values\n", SW); fprintf(stderr, "\n"); fprintf(stderr, "%cq<0..100> - Output JPEG quality\n", SW); fprintf(stderr, "\n"); fprintf(stderr, "%ch<0,1,2,3> - More help\n", SW); break; case 1: fprintf(stderr, "Examples:\n\n" "To color correct from scanner to sRGB:\n" "\tjpgicc %ciscanner.icm in.jpg out.jpg\n" "To convert from monitor1 to monitor2:\n" "\tjpgicc %cimon1.icm %comon2.icm in.jpg out.jpg\n" "To make a CMYK separation:\n" "\tjpgicc %coprinter.icm inrgb.jpg outcmyk.jpg\n" "To recover sRGB from a CMYK separation:\n" "\tjpgicc %ciprinter.icm incmyk.jpg outrgb.jpg\n" "To convert from CIELab ITU/Fax JPEG to sRGB\n" "\tjpgicc in.jpg out.jpg\n\n", SW, SW, SW, SW, SW); break; case 2: PrintBuiltins(); break; case 3: fprintf(stderr, "This program is intended to be a demo of the little cms\n" "engine. Both lcms and this program are freeware. You can\n" "obtain both in source code at http://www.littlecms.com\n" "For suggestions, comments, bug reports etc. send mail to\n" "[email protected]\n\n"); break; } exit(0); } // The toggles stuff static void HandleSwitches(int argc, char *argv[]) { int s; while ((s=xgetopt(argc,argv,"bBnNvVGgh:H:i:I:o:O:P:p:t:T:c:C:Q:q:M:m:L:l:eEs:S:!:D:d:")) != EOF) { switch (s) { case 'b': case 'B': BlackPointCompensation = TRUE; break; case 'd': case 'D': ObserverAdaptationState = atof(xoptarg); if (ObserverAdaptationState < 0 || ObserverAdaptationState > 1.0) FatalError("Adaptation state should be 0..1"); break; case 'v': case 'V': Verbose = TRUE; break; case 'i': case 'I': if (lIsDeviceLink) FatalError("Device-link already specified"); cInpProf = xoptarg; break; case 'o': case 'O': if (lIsDeviceLink) FatalError("Device-link already specified"); cOutProf = xoptarg; break; case 'l': case 'L': if (cInpProf != NULL || cOutProf != NULL) FatalError("input/output profiles already specified"); cInpProf = xoptarg; lIsDeviceLink = TRUE; break; case 'p': case 'P': cProofing = xoptarg; break; case 't': case 'T': Intent = atoi(xoptarg); break; case 'N': case 'n': IgnoreEmbedded = TRUE; break; case 'e': case 'E': EmbedProfile = TRUE; break; case 'g': case 'G': GamutCheck = TRUE; break; case 'c': case 'C': PrecalcMode = atoi(xoptarg); if (PrecalcMode < 0 || PrecalcMode > 2) FatalError("Unknown precalc mode '%d'", PrecalcMode); break; case 'H': case 'h': { int a = atoi(xoptarg); Help(a); } break; case 'q': case 'Q': jpegQuality = atoi(xoptarg); if (jpegQuality > 100) jpegQuality = 100; if (jpegQuality < 0) jpegQuality = 0; break; case 'm': case 'M': ProofingIntent = atoi(xoptarg); break; case 's': case 'S': SaveEmbedded = xoptarg; break; case '!': if (sscanf(xoptarg, "%hu,%hu,%hu", &Alarm[0], &Alarm[1], &Alarm[2]) == 3) { int i; for (i=0; i < 3; i++) { Alarm[i] = (Alarm[i] << 8) | Alarm[i]; } } break; default: FatalError("Unknown option - run without args to see valid ones"); } } } int main(int argc, char* argv[]) { InitUtils("jpgicc"); HandleSwitches(argc, argv); if ((argc - xoptind) != 2) { Help(0); } OpenInput(argv[xoptind]); OpenOutput(argv[xoptind+1]); TransformImage(cInpProf, cOutProf); if (Verbose) { fprintf(stdout, "\n"); fflush(stdout); } Done(); return 0; }
29
./little-cms/utils/jpgicc/iccjpeg.c
/* * iccprofile.c * * This file provides code to read and write International Color Consortium * (ICC) device profiles embedded in JFIF JPEG image files. The ICC has * defined a standard format for including such data in JPEG "APP2" markers. * The code given here does not know anything about the internal structure * of the ICC profile data; it just knows how to put the profile data into * a JPEG file being written, or get it back out when reading. * * This code depends on new features added to the IJG JPEG library as of * IJG release 6b; it will not compile or work with older IJG versions. * * NOTE: this code would need surgery to work on 16-bit-int machines * with ICC profiles exceeding 64K bytes in size. If you need to do that, * change all the "unsigned int" variables to "INT32". You'll also need * to find a malloc() replacement that can allocate more than 64K. */ #include "iccjpeg.h" #include <stdlib.h> /* define malloc() */ /* * Since an ICC profile can be larger than the maximum size of a JPEG marker * (64K), we need provisions to split it into multiple markers. The format * defined by the ICC specifies one or more APP2 markers containing the * following data: * Identifying string ASCII "ICC_PROFILE\0" (12 bytes) * Marker sequence number 1 for first APP2, 2 for next, etc (1 byte) * Number of markers Total number of APP2's used (1 byte) * Profile data (remainder of APP2 data) * Decoders should use the marker sequence numbers to reassemble the profile, * rather than assuming that the APP2 markers appear in the correct sequence. */ #define ICC_MARKER (JPEG_APP0 + 2) /* JPEG marker code for ICC */ #define ICC_OVERHEAD_LEN 14 /* size of non-profile data in APP2 */ #define MAX_BYTES_IN_MARKER 65533 /* maximum data len of a JPEG marker */ #define MAX_DATA_BYTES_IN_MARKER (MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN) /* * This routine writes the given ICC profile data into a JPEG file. * It *must* be called AFTER calling jpeg_start_compress() and BEFORE * the first call to jpeg_write_scanlines(). * (This ordering ensures that the APP2 marker(s) will appear after the * SOI and JFIF or Adobe markers, but before all else.) */ void write_icc_profile (j_compress_ptr cinfo, const JOCTET *icc_data_ptr, unsigned int icc_data_len) { unsigned int num_markers; /* total number of markers we'll write */ int cur_marker = 1; /* per spec, counting starts at 1 */ unsigned int length; /* number of bytes to write in this marker */ /* Calculate the number of markers we'll need, rounding up of course */ num_markers = icc_data_len / MAX_DATA_BYTES_IN_MARKER; if (num_markers * MAX_DATA_BYTES_IN_MARKER != icc_data_len) num_markers++; while (icc_data_len > 0) { /* length of profile to put in this marker */ length = icc_data_len; if (length > MAX_DATA_BYTES_IN_MARKER) length = MAX_DATA_BYTES_IN_MARKER; icc_data_len -= length; /* Write the JPEG marker header (APP2 code and marker length) */ jpeg_write_m_header(cinfo, ICC_MARKER, (unsigned int) (length + ICC_OVERHEAD_LEN)); /* Write the marker identifying string "ICC_PROFILE" (null-terminated). * We code it in this less-than-transparent way so that the code works * even if the local character set is not ASCII. */ jpeg_write_m_byte(cinfo, 0x49); jpeg_write_m_byte(cinfo, 0x43); jpeg_write_m_byte(cinfo, 0x43); jpeg_write_m_byte(cinfo, 0x5F); jpeg_write_m_byte(cinfo, 0x50); jpeg_write_m_byte(cinfo, 0x52); jpeg_write_m_byte(cinfo, 0x4F); jpeg_write_m_byte(cinfo, 0x46); jpeg_write_m_byte(cinfo, 0x49); jpeg_write_m_byte(cinfo, 0x4C); jpeg_write_m_byte(cinfo, 0x45); jpeg_write_m_byte(cinfo, 0x0); /* Add the sequencing info */ jpeg_write_m_byte(cinfo, cur_marker); jpeg_write_m_byte(cinfo, (int) num_markers); /* Add the profile data */ while (length--) { jpeg_write_m_byte(cinfo, *icc_data_ptr); icc_data_ptr++; } cur_marker++; } } /* * Prepare for reading an ICC profile */ void setup_read_icc_profile (j_decompress_ptr cinfo) { /* Tell the library to keep any APP2 data it may find */ jpeg_save_markers(cinfo, ICC_MARKER, 0xFFFF); } /* * Handy subroutine to test whether a saved marker is an ICC profile marker. */ static boolean marker_is_icc (jpeg_saved_marker_ptr marker) { return marker->marker == ICC_MARKER && marker->data_length >= ICC_OVERHEAD_LEN && /* verify the identifying string */ GETJOCTET(marker->data[0]) == 0x49 && GETJOCTET(marker->data[1]) == 0x43 && GETJOCTET(marker->data[2]) == 0x43 && GETJOCTET(marker->data[3]) == 0x5F && GETJOCTET(marker->data[4]) == 0x50 && GETJOCTET(marker->data[5]) == 0x52 && GETJOCTET(marker->data[6]) == 0x4F && GETJOCTET(marker->data[7]) == 0x46 && GETJOCTET(marker->data[8]) == 0x49 && GETJOCTET(marker->data[9]) == 0x4C && GETJOCTET(marker->data[10]) == 0x45 && GETJOCTET(marker->data[11]) == 0x0; } /* * See if there was an ICC profile in the JPEG file being read; * if so, reassemble and return the profile data. * * TRUE is returned if an ICC profile was found, FALSE if not. * If TRUE is returned, *icc_data_ptr is set to point to the * returned data, and *icc_data_len is set to its length. * * IMPORTANT: the data at **icc_data_ptr has been allocated with malloc() * and must be freed by the caller with free() when the caller no longer * needs it. (Alternatively, we could write this routine to use the * IJG library's memory allocator, so that the data would be freed implicitly * at jpeg_finish_decompress() time. But it seems likely that many apps * will prefer to have the data stick around after decompression finishes.) * * NOTE: if the file contains invalid ICC APP2 markers, we just silently * return FALSE. You might want to issue an error message instead. */ boolean read_icc_profile (j_decompress_ptr cinfo, JOCTET **icc_data_ptr, unsigned int *icc_data_len) { jpeg_saved_marker_ptr marker; int num_markers = 0; int seq_no; JOCTET *icc_data; unsigned int total_length; #define MAX_SEQ_NO 255 /* sufficient since marker numbers are bytes */ char marker_present[MAX_SEQ_NO+1]; /* 1 if marker found */ unsigned int data_length[MAX_SEQ_NO+1]; /* size of profile data in marker */ unsigned int data_offset[MAX_SEQ_NO+1]; /* offset for data in marker */ *icc_data_ptr = NULL; /* avoid confusion if FALSE return */ *icc_data_len = 0; /* This first pass over the saved markers discovers whether there are * any ICC markers and verifies the consistency of the marker numbering. */ for (seq_no = 1; seq_no <= MAX_SEQ_NO; seq_no++) marker_present[seq_no] = 0; for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) { if (marker_is_icc(marker)) { if (num_markers == 0) num_markers = GETJOCTET(marker->data[13]); else if (num_markers != GETJOCTET(marker->data[13])) return FALSE; /* inconsistent num_markers fields */ seq_no = GETJOCTET(marker->data[12]); if (seq_no <= 0 || seq_no > num_markers) return FALSE; /* bogus sequence number */ if (marker_present[seq_no]) return FALSE; /* duplicate sequence numbers */ marker_present[seq_no] = 1; data_length[seq_no] = marker->data_length - ICC_OVERHEAD_LEN; } } if (num_markers == 0) return FALSE; /* Check for missing markers, count total space needed, * compute offset of each marker's part of the data. */ total_length = 0; for (seq_no = 1; seq_no <= num_markers; seq_no++) { if (marker_present[seq_no] == 0) return FALSE; /* missing sequence number */ data_offset[seq_no] = total_length; total_length += data_length[seq_no]; } if (total_length <= 0) return FALSE; /* found only empty markers? */ /* Allocate space for assembled data */ icc_data = (JOCTET *) malloc(total_length * sizeof(JOCTET)); if (icc_data == NULL) return FALSE; /* oops, out of memory */ /* and fill it in */ for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) { if (marker_is_icc(marker)) { JOCTET FAR *src_ptr; JOCTET *dst_ptr; unsigned int length; seq_no = GETJOCTET(marker->data[12]); dst_ptr = icc_data + data_offset[seq_no]; src_ptr = marker->data + ICC_OVERHEAD_LEN; length = data_length[seq_no]; while (length--) { *dst_ptr++ = *src_ptr++; } } } *icc_data_ptr = icc_data; *icc_data_len = total_length; return TRUE; }

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
8
Add dataset card