Skip to main content

c/
shm_sem.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// POSIX shared memory + named semaphores
6// ============================================================
7
8const NAME_MAX: usize = 255;
9const SEM_NSEMS_MAX: usize = 256;
10
11// global spinlock for semtab, upgrade to per-entry if contention matters
12static SEMTAB_LOCK: AtomicI32 = AtomicI32::new(0);
13
14struct SemEntry {
15    ino: u64,
16    sem: *mut sem_t,
17    refcnt: u32,
18}
19
20// zero-init is fine for static mut (all-zero = free slots)
21static mut SEMTAB: [SemEntry; SEM_NSEMS_MAX] = {
22    const ZERO: SemEntry = SemEntry { ino: 0, sem: core::ptr::null_mut(), refcnt: 0 };
23    [ZERO; SEM_NSEMS_MAX]
24};
25
26unsafe fn semtab_lock() {
27    while SEMTAB_LOCK.compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed).is_err() {
28        core::hint::spin_loop();
29    }
30}
31
32unsafe fn semtab_unlock() {
33    SEMTAB_LOCK.store(0, Ordering::Release);
34}
35
36// Validate shm/sem name and construct /dev/shm/<name> path.
37// Returns path length or -1 with ERRNO set.
38unsafe fn shm_mapname(name: *const c_char, buf: *mut u8) -> c_int {
39    let mut p = name;
40    // strip leading /
41    while *p == b'/' as c_char { p = p.add(1); }
42    let start = p;
43    // find end of first component
44    while *p != 0 && *p != b'/' as c_char { p = p.add(1); }
45    let len = p.offset_from(start) as usize;
46    // no trailing /, not empty, not "." or ".."
47    if len == 0 || *p != 0 {
48        ERRNO!() = EINVAL;
49        return -1;
50    }
51    if len == 1 && *start == b'.' as c_char {
52        ERRNO!() = EINVAL;
53        return -1;
54    }
55    if len == 2 && *start == b'.' as c_char && *start.add(1) == b'.' as c_char {
56        ERRNO!() = EINVAL;
57        return -1;
58    }
59    if len > NAME_MAX {
60        ERRNO!() = ENAMETOOLONG;
61        return -1;
62    }
63    // build /dev/shm/<name>
64    let prefix = b"/dev/shm/\0";
65    let mut i = 0;
66    while prefix[i] != 0 {
67        *buf.add(i) = prefix[i];
68        i += 1;
69    }
70    let mut j = 0;
71    while j < len {
72        *buf.add(i + j) = *start.add(j) as u8;
73        j += 1;
74    }
75    *buf.add(i + j) = 0;
76    (i + j) as c_int
77}
78
79#[no_mangle]
80pub unsafe extern "C" fn shm_open(name: *const c_char, flags: c_int, mode: mode_t) -> c_int {
81    let mut buf = [0u8; 16 + NAME_MAX + 1];
82    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
83    let fd = sys_open(buf.as_ptr(), (flags | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
84    if fd < 0 { ERRNO!() = (-fd) as c_int; return -1; }
85    fd as c_int
86}
87
88#[no_mangle]
89pub unsafe extern "C" fn shm_unlink(name: *const c_char) -> c_int {
90    let mut buf = [0u8; 16 + NAME_MAX + 1];
91    if shm_mapname(name, buf.as_mut_ptr()) < 0 { return -1; }
92    let r = sys_unlink(buf.as_ptr());
93    syscall_ret(r) as c_int
94}
95
96#[no_mangle]
97pub unsafe extern "C" fn sem_open(name: *const c_char, flags: c_int, mut args: ...) -> *mut sem_t {
98    let mut buf = [0u8; 16 + NAME_MAX + 1];
99    if shm_mapname(name, buf.as_mut_ptr()).is_negative() {
100        return core::ptr::null_mut(); // SEM_FAILED
101    }
102
103    let oflags = flags & (O_CREAT | O_EXCL);
104
105    semtab_lock();
106
107    // find a free slot
108    let mut slot: c_int = -1;
109    for i in 0..SEMTAB_LEN {
110        if SEMTAB[i].sem.is_null() && slot < 0 { slot = i as c_int; }
111    }
112    if slot < 0 {
113        ERRNO!() = EMFILE;
114        semtab_unlock();
115        return core::ptr::null_mut();
116    }
117    // reserve slot
118    SEMTAB[slot as usize].sem = !0usize as *mut sem_t; // sentinel
119    semtab_unlock();
120
121    // extract va_args for O_CREAT
122    let mut mode: mode_t = 0;
123    let mut value: c_uint = 0;
124    if oflags & O_CREAT != 0 {
125        mode = args.next_arg::<mode_t>() & 0o666;
126        value = args.next_arg::<c_uint>();
127        if value > SEM_VALUE_MAX as c_uint {
128            ERRNO!() = EINVAL;
129            semtab_lock();
130            SEMTAB[slot as usize].sem = core::ptr::null_mut();
131            semtab_unlock();
132            return core::ptr::null_mut();
133        }
134    }
135
136    // try opening existing first (unless O_CREAT|O_EXCL)
137    if oflags != O_CREAT | O_EXCL {
138        let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
139        if fd >= 0 {
140            let map = sys_mmap(
141                core::ptr::null_mut(),
142                core::mem::size_of::<sem_t>(),
143                PROT_READ | PROT_WRITE,
144                MAP_SHARED,
145                fd as i32,
146                0,
147            );
148            sys_close(fd);
149            if map != MMAP_FAILED {
150                let st_ino = get_ino(fd as c_int, buf.as_ptr());
151                return sem_register(map as *mut sem_t, st_ino, slot);
152            }
153        }
154        if oflags == 0 {
155            // no O_CREAT and file doesn't exist
156            semtab_lock();
157            SEMTAB[slot as usize].sem = core::ptr::null_mut();
158            semtab_unlock();
159            return core::ptr::null_mut();
160        }
161    }
162
163    // create: write sem_t to temp file, mmap, link
164    let mut tmp = [0u8; 32];
165    // Each attempt gets a fresh unpredictable name; reusing one name made
166    // the retry loop below useless and let a local user pre-create it.
167    unsafe fn make_tmp_name(tmp: &mut [u8; 32]) {
168        let prefix = b"/dev/shm/tmp-";
169        tmp[..prefix.len()].copy_from_slice(prefix);
170        let mut r: u64 = 0;
171        let got = crate::getrandom(
172            &mut r as *mut u64 as *mut u8,
173            core::mem::size_of::<u64>(),
174            0,
175        );
176        if got != core::mem::size_of::<u64>() as isize {
177            let mut ts: timespec = core::mem::zeroed();
178            sys_clock_gettime(0, &mut ts);
179            r = (ts.tv_nsec as u64) ^ ((crate::getpid() as u64) << 32);
180        }
181        let hex = b"0123456789abcdef";
182        for i in 0..16 {
183            tmp[prefix.len() + i] = hex[((r >> (4 * (15 - i))) & 0xf) as usize];
184        }
185        tmp[prefix.len() + 16] = 0;
186    }
187
188    let mut newsem: sem_t = core::mem::zeroed();
189    newsem.__val[0] = value as c_int;
190    newsem.__val[1] = 0;
191    newsem.__val[2] = 128; // pshared=0 flag
192
193    let mut attempts = 0usize;
194    loop {
195        make_tmp_name(&mut tmp);
196        let tmp_path = tmp.as_ptr();
197        let fd = sys_open(tmp_path as *const u8, (O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NONBLOCK) as i64, mode as i64);
198        if fd < 0 {
199            if (-fd) as c_int == EEXIST {
200                attempts += 1;
201                if attempts >= 16 {
202                    ERRNO!() = EEXIST;
203                    semtab_lock();
204                    SEMTAB[slot as usize].sem = core::ptr::null_mut();
205                    semtab_unlock();
206                    return core::ptr::null_mut();
207                }
208                continue;
209            }
210            semtab_lock();
211            SEMTAB[slot as usize].sem = core::ptr::null_mut();
212            semtab_unlock();
213            return core::ptr::null_mut();
214        }
215        let written = sys_write(fd, &newsem as *const sem_t as *const u8, core::mem::size_of::<sem_t>());
216        if written != core::mem::size_of::<sem_t>() as i64 {
217            sys_close(fd);
218            sys_unlink(tmp_path);
219            semtab_lock();
220            SEMTAB[slot as usize].sem = core::ptr::null_mut();
221            semtab_unlock();
222            return core::ptr::null_mut();
223        }
224        let map = sys_mmap(
225            core::ptr::null_mut(),
226            core::mem::size_of::<sem_t>(),
227            PROT_READ | PROT_WRITE,
228            MAP_SHARED,
229            fd as i32,
230            0,
231        );
232        sys_close(fd);
233        if map == MMAP_FAILED {
234            sys_unlink(tmp_path);
235            semtab_lock();
236            SEMTAB[slot as usize].sem = core::ptr::null_mut();
237            semtab_unlock();
238            return core::ptr::null_mut();
239        }
240        // link to final name
241        let r = sys_linkat(AT_FDCWD, tmp_path, AT_FDCWD, buf.as_ptr(), 0);
242        let e = if r < 0 { (-r) as c_int } else { 0 };
243        sys_unlink(tmp_path);
244        if e == 0 {
245            let st_ino = get_ino(-1, buf.as_ptr());
246            return sem_register(map as *mut sem_t, st_ino, slot);
247        }
248        sys_munmap(map, core::mem::size_of::<sem_t>());
249        if e != EEXIST || oflags == O_CREAT | O_EXCL {
250            ERRNO!() = e;
251            semtab_lock();
252            SEMTAB[slot as usize].sem = core::ptr::null_mut();
253            semtab_unlock();
254            return core::ptr::null_mut();
255        }
256        // EEXIST without O_EXCL: retry open existing
257        break;
258    }
259
260    // fallthrough: try opening the existing file that won the race
261    let fd = sys_open(buf.as_ptr(), (O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) as i64, 0);
262    if fd < 0 {
263        semtab_lock();
264        SEMTAB[slot as usize].sem = core::ptr::null_mut();
265        semtab_unlock();
266        return core::ptr::null_mut();
267    }
268    let map = sys_mmap(
269        core::ptr::null_mut(),
270        core::mem::size_of::<sem_t>(),
271        PROT_READ | PROT_WRITE,
272        MAP_SHARED,
273        fd as i32,
274        0,
275    );
276    sys_close(fd);
277    if map == MMAP_FAILED {
278        semtab_lock();
279        SEMTAB[slot as usize].sem = core::ptr::null_mut();
280        semtab_unlock();
281        return core::ptr::null_mut();
282    }
283    let st_ino = get_ino(-1, buf.as_ptr());
284    sem_register(map as *mut sem_t, st_ino, slot)
285}
286
287unsafe fn get_ino(_fd_hint: c_int, path: *const u8) -> u64 {
288    let mut st: Stat = core::mem::zeroed();
289    if sys_newfstatat(AT_FDCWD, path as *const c_char, &mut st as *mut Stat as *mut u8, 0) == 0 {
290        st.st_ino
291    } else {
292        0
293    }
294}
295
296unsafe fn sem_register(map: *mut sem_t, ino: u64, slot_hint: c_int) -> *mut sem_t {
297    semtab_lock();
298    // check if already mapped (by inode)
299    for i in 0..SEMTAB_LEN {
300        if SEMTAB[i].ino == ino && !SEMTAB[i].sem.is_null() && SEMTAB[i].sem != !0usize as *mut sem_t {
301            // already mapped: unmap new, use existing, release hint slot
302            sys_munmap(map as *mut u8, core::mem::size_of::<sem_t>());
303            SEMTAB[slot_hint as usize].sem = core::ptr::null_mut();
304            SEMTAB[i].refcnt += 1;
305            let ret = SEMTAB[i].sem;
306            semtab_unlock();
307            return ret;
308        }
309    }
310    // new entry
311    SEMTAB[slot_hint as usize].sem = map;
312    SEMTAB[slot_hint as usize].ino = ino;
313    SEMTAB[slot_hint as usize].refcnt = 1;
314    semtab_unlock();
315    map
316}
317
318const SEMTAB_LEN: usize = SEM_NSEMS_MAX;
319
320#[no_mangle]
321pub unsafe extern "C" fn sem_close(sem: *mut sem_t) -> c_int {
322    if sem.is_null() {
323        ERRNO!() = EINVAL;
324        return -1;
325    }
326    semtab_lock();
327    for i in 0..SEMTAB_LEN {
328        if SEMTAB[i].sem == sem {
329            if SEMTAB[i].refcnt == 0 {
330                semtab_unlock();
331                ERRNO!() = EINVAL;
332                return -1;
333            }
334            SEMTAB[i].refcnt -= 1;
335            if SEMTAB[i].refcnt == 0 {
336                SEMTAB[i].sem = core::ptr::null_mut();
337                SEMTAB[i].ino = 0;
338                semtab_unlock();
339                sys_munmap(sem as *mut u8, core::mem::size_of::<sem_t>());
340                return 0;
341            }
342            semtab_unlock();
343            return 0;
344        }
345    }
346    semtab_unlock();
347    ERRNO!() = EINVAL;
348    -1
349}
350
351#[no_mangle]
352pub unsafe extern "C" fn sem_unlink(name: *const c_char) -> c_int {
353    shm_unlink(name)
354}
355
356// --- pthread_once ---
357#[no_mangle]
358pub unsafe extern "C" fn pthread_once(control: *mut pthread_once_t, init_routine: Option<unsafe extern "C" fn()>) -> c_int {
359    if a_load(control) == 2 { return 0; }
360    loop {
361        match a_cas(control, 0, 1) {
362            0 => {
363                if let Some(f) = init_routine { f(); }
364                if a_swap(control, 2) == 3 { futex_wake(control, -1); }
365                return 0;
366            }
367            1 => { a_cas(control, 1, 3); }
368            3 => { futex_wait(control, 3); }
369            _ => { return 0; }
370        }
371    }
372}
373
374// --- pthread_key_* ---
375#[no_mangle]
376pub unsafe extern "C" fn pthread_key_create(key: *mut pthread_key_t, dtor: Option<unsafe extern "C" fn(*mut c_void)>) -> c_int {
377    let start = NEXT_KEY.load(Ordering::Relaxed);
378    let mut j = start;
379    loop {
380        if KEY_DTORS[j].is_none() {
381            KEY_DTORS[j] = dtor;
382            NEXT_KEY.store((j + 1) % PTHREAD_KEYS_MAX, Ordering::Relaxed);
383            *key = j as pthread_key_t;
384            return 0;
385        }
386        j = (j + 1) % PTHREAD_KEYS_MAX;
387        if j == start { return EAGAIN; }
388    }
389}
390#[no_mangle]
391pub unsafe extern "C" fn pthread_key_delete(key: pthread_key_t) -> c_int {
392    if key as usize >= PTHREAD_KEYS_MAX {
393        return EINVAL;
394    }
395    KEY_DTORS[key as usize] = None;
396    let count = thread_slot_count();
397    let mut i = 0usize;
398    while i < count {
399        let slot = thread_slot_at(i);
400        if !slot.is_null() && core::ptr::read_volatile(&raw const (*slot).tid) > 0 {
401            (*slot).tsd[key as usize] = core::ptr::null_mut();
402        }
403        i += 1;
404    }
405    0
406}
407#[no_mangle]
408pub unsafe extern "C" fn pthread_getspecific(key: pthread_key_t) -> *mut c_void {
409    if key as usize >= PTHREAD_KEYS_MAX {
410        return core::ptr::null_mut();
411    }
412    if let Some(slot) = find_thread() { slot.tsd[key as usize] } else { core::ptr::null_mut() }
413}
414#[no_mangle]
415pub unsafe extern "C" fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int {
416    if key as usize >= PTHREAD_KEYS_MAX {
417        ERRNO!() = EINVAL;
418        return EINVAL;
419    }
420    if let Some(slot) = find_thread() {
421        slot.tsd[key as usize] = value as *mut c_void;
422        0
423    } else { EINVAL }
424}
425
426// --- pthread_cancel/state ---
427unsafe fn run_cleanup_handlers(slot: &mut Thread) {
428    let mut cb = slot.cancelbuf;
429    while !cb.is_null() {
430        let cur = &*cb;
431        let f = cur.__f;
432        let x = cur.__x;
433        cb = cur.__next;
434        if let Some(func) = f {
435            func(x);
436        }
437    }
438    slot.cancelbuf = core::ptr::null_mut();
439}
440
441unsafe fn do_cancel() -> ! {
442    if let Some(slot) = find_thread() {
443        run_cleanup_handlers(slot);
444        slot.result = !0usize as *mut c_void; // PTHREAD_CANCELED
445        slot.detach_state = DT_EXITED;
446        futex_wake(&raw mut slot.detach_state, 1);
447    }
448    sys_exit_thread(0);
449}
450
451extern "C" fn cancel_handler(_sig: c_int) {
452    unsafe {
453        if let Some(slot) = find_thread() {
454            // In asynchronous mode, cancel immediately from the signal handler.
455            // In deferred mode, the signal just interrupts blocking syscalls so
456            // the next cancellation point can act on the pending request.
457            if slot.cancel != 0
458                && slot.cancel_state == PTHREAD_CANCEL_ENABLE
459                && slot.cancel_type == PTHREAD_CANCEL_ASYNCHRONOUS
460            {
461                do_cancel();
462            }
463        }
464    }
465}
466
467static CANCEL_INIT: AtomicI32 = AtomicI32::new(0);
468
469unsafe fn ensure_cancel_handler() {
470    if CANCEL_INIT.swap(1, Ordering::AcqRel) == 0 {
471        let act = KSigAction {
472            sa_handler: cancel_handler as *const () as usize,
473            sa_flags: SA_RESTORER,
474            sa_restorer: sig_restorer as *const () as usize,
475            sa_mask: [!0u64],
476        };
477        sys_rt_sigaction(SIGCANCEL, &act as *const KSigAction, core::ptr::null_mut(), 8);
478    }
479}
480
481#[no_mangle]
482pub unsafe extern "C" fn pthread_cancel(thread: PthreadT) -> c_int {
483    let slot = thread as *mut Thread;
484    if slot.is_null() { return EINVAL; }
485    ensure_cancel_handler();
486    a_store(&raw mut (*slot).cancel, 1);
487    let tid = (*slot).tid;
488    if tid > 0 {
489        sys_tgkill(sys_getpid() as c_int, tid, SIGCANCEL);
490    }
491    0
492}
493#[no_mangle]
494pub unsafe extern "C" fn pthread_setcancelstate(state: c_int, oldstate: *mut c_int) -> c_int {
495    if state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE { return EINVAL; }
496    if let Some(slot) = find_thread() {
497        if !oldstate.is_null() { *oldstate = slot.cancel_state; }
498        slot.cancel_state = state;
499        0
500    } else { EINVAL }
501}
502#[no_mangle]
503pub unsafe extern "C" fn pthread_setcanceltype(type_: c_int, oldtype: *mut c_int) -> c_int {
504    if type_ != PTHREAD_CANCEL_DEFERRED && type_ != PTHREAD_CANCEL_ASYNCHRONOUS { return EINVAL; }
505    if let Some(slot) = find_thread() {
506        if !oldtype.is_null() { *oldtype = slot.cancel_type; }
507        slot.cancel_type = type_;
508        0
509    } else { EINVAL }
510}
511#[no_mangle]
512pub unsafe extern "C" fn pthread_testcancel() {
513    if let Some(slot) = find_thread() {
514        if slot.cancel != 0 && slot.cancel_state == PTHREAD_CANCEL_ENABLE {
515            do_cancel();
516        }
517    }
518}
519
520#[no_mangle]
521pub unsafe extern "C" fn _pthread_cleanup_push(cb: *mut __ptcb, f: Option<unsafe extern "C" fn(*mut c_void)>, x: *mut c_void) {
522    (*cb).__f = f;
523    (*cb).__x = x;
524    if let Some(slot) = find_thread() {
525        (*cb).__next = slot.cancelbuf;
526        slot.cancelbuf = cb;
527    } else {
528        (*cb).__next = core::ptr::null_mut();
529    }
530}
531
532#[no_mangle]
533pub unsafe extern "C" fn _pthread_cleanup_pop(cb: *mut __ptcb, run: c_int) {
534    if let Some(slot) = find_thread() {
535        slot.cancelbuf = (*cb).__next;
536    }
537    if run != 0 {
538        if let Some(f) = (*cb).__f {
539            f((*cb).__x);
540        }
541    }
542}
543
544#[no_mangle]
545pub unsafe extern "C" fn pthread_kill(thread: PthreadT, sig: c_int) -> c_int {
546    let slot = thread as *mut Thread;
547    if slot.is_null() { return EINVAL; }
548    let tid = (*slot).tid;
549    if tid <= 0 { return EINVAL; }
550    if sys_tgkill(sys_getpid() as c_int, tid, sig) < 0 { -1 } else { 0 }
551}
552
553#[no_mangle]
554pub unsafe extern "C" fn pthread_sigmask(how: c_int, set: *const SigSetT, oldset: *mut SigSetT) -> c_int {
555    // POSIX pthread functions return the error number itself, not -1/errno.
556    if sigprocmask(how, set, oldset) < 0 { ERRNO!() } else { 0 }
557}
558
559
560#[repr(C)]
561pub struct lconv {
562    pub decimal_point: *mut c_char,
563    pub thousands_sep: *mut c_char,
564    pub grouping: *mut c_char,
565    pub int_curr_symbol: *mut c_char,
566    pub currency_symbol: *mut c_char,
567    pub mon_decimal_point: *mut c_char,
568    pub mon_thousands_sep: *mut c_char,
569    pub mon_grouping: *mut c_char,
570    pub positive_sign: *mut c_char,
571    pub negative_sign: *mut c_char,
572    pub int_frac_digits: c_char,
573    pub frac_digits: c_char,
574    pub p_cs_precedes: c_char,
575    pub p_sep_by_space: c_char,
576    pub n_cs_precedes: c_char,
577    pub n_sep_by_space: c_char,
578    pub p_sign_posn: c_char,
579    pub n_sign_posn: c_char,
580    pub int_p_cs_precedes: c_char,
581    pub int_p_sep_by_space: c_char,
582    pub int_n_cs_precedes: c_char,
583    pub int_n_sep_by_space: c_char,
584    pub int_p_sign_posn: c_char,
585    pub int_n_sign_posn: c_char,
586}
587
588static UTF8_NAME: [u8; 6] = [b'U', b'T', b'F', b'-', b'8', 0];
589static C_NAME: [u8; 2] = [b'C', 0];
590static mut LOCALE_NAME: *const c_char = C_NAME.as_ptr() as *const c_char;
591static mut LOCALE_CTYPE_UTF8: bool = true;
592static mut EMPTY_STR: [c_char; 1] = [0];
593static mut DECIMAL_POINT: [c_char; 2] = [b'.' as c_char, 0];
594static mut LCONV: lconv = lconv {
595    decimal_point: core::ptr::null_mut(),
596    thousands_sep: core::ptr::null_mut(),
597    grouping: core::ptr::null_mut(),
598    int_curr_symbol: core::ptr::null_mut(),
599    currency_symbol: core::ptr::null_mut(),
600    mon_decimal_point: core::ptr::null_mut(),
601    mon_thousands_sep: core::ptr::null_mut(),
602    mon_grouping: core::ptr::null_mut(),
603    positive_sign: core::ptr::null_mut(),
604    negative_sign: core::ptr::null_mut(),
605    int_frac_digits: (-1i32) as c_char,
606    frac_digits: (-1i32) as c_char,
607    p_cs_precedes: (-1i32) as c_char,
608    p_sep_by_space: (-1i32) as c_char,
609    n_cs_precedes: (-1i32) as c_char,
610    n_sep_by_space: (-1i32) as c_char,
611    p_sign_posn: (-1i32) as c_char,
612    n_sign_posn: (-1i32) as c_char,
613    int_p_cs_precedes: (-1i32) as c_char,
614    int_p_sep_by_space: (-1i32) as c_char,
615    int_n_cs_precedes: (-1i32) as c_char,
616    int_n_sep_by_space: (-1i32) as c_char,
617    int_p_sign_posn: (-1i32) as c_char,
618    int_n_sign_posn: (-1i32) as c_char,
619};
620
621#[no_mangle]
622pub unsafe extern "C" fn setlocale(_category: c_int, locale: *const c_char) -> *mut c_char {
623    if locale.is_null() || *locale == 0 {
624        return LOCALE_NAME as *mut c_char;
625    }
626    let name = locale as *const u8;
627    if crate::cstr_eq(name, b"C") || crate::cstr_eq(name, b"POSIX") {
628        LOCALE_CTYPE_UTF8 = false;
629        return LOCALE_NAME as *mut c_char;
630    }
631    if crate::cstr_contains_ci(name, b"UTF-8") || crate::cstr_contains_ci(name, b"UTF8") {
632        LOCALE_CTYPE_UTF8 = true;
633        return LOCALE_NAME as *mut c_char;
634    }
635    core::ptr::null_mut()
636}
637
638#[no_mangle]
639pub unsafe extern "C" fn localeconv() -> *mut lconv {
640    let empty = core::ptr::addr_of_mut!(EMPTY_STR) as *mut c_char;
641    let lconv = core::ptr::addr_of_mut!(LCONV);
642    (*lconv).decimal_point = core::ptr::addr_of_mut!(DECIMAL_POINT) as *mut c_char;
643    (*lconv).thousands_sep = empty;
644    (*lconv).grouping = empty;
645    (*lconv).int_curr_symbol = empty;
646    (*lconv).currency_symbol = empty;
647    (*lconv).mon_decimal_point = empty;
648    (*lconv).mon_thousands_sep = empty;
649    (*lconv).mon_grouping = empty;
650    (*lconv).positive_sign = empty;
651    (*lconv).negative_sign = empty;
652    lconv
653}
654
655pub type locale_t = *mut c_void;
656static mut CURRENT_LOCALE: locale_t = LC_GLOBAL_LOCALE;
657
658static mut C_LOCALE_STORAGE: c_int = 0;
659const C_LOCALE: locale_t = core::ptr::addr_of_mut!(C_LOCALE_STORAGE) as locale_t;
660const LC_GLOBAL_LOCALE: locale_t = usize::MAX as locale_t;
661
662#[no_mangle]
663pub unsafe extern "C" fn newlocale(_mask: c_int, name: *const c_char, base: locale_t) -> locale_t {
664    if !name.is_null() && *name != 0 {
665        let n = name as *const u8;
666        if !crate::cstr_eq(n, b"C") && !crate::cstr_eq(n, b"POSIX") {
667            return core::ptr::null_mut();
668        }
669    }
670    if base.is_null() || base == C_LOCALE || base == LC_GLOBAL_LOCALE {
671        C_LOCALE
672    } else {
673        core::ptr::null_mut()
674    }
675}
676
677#[no_mangle]
678pub unsafe extern "C" fn freelocale(_loc: locale_t) {}
679
680#[no_mangle]
681pub unsafe extern "C" fn uselocale(loc: locale_t) -> locale_t {
682    let old = CURRENT_LOCALE;
683    if !loc.is_null() {
684        CURRENT_LOCALE = loc;
685    }
686    old
687}
688
689#[no_mangle]
690pub unsafe extern "C" fn duplocale(loc: locale_t) -> locale_t {
691    if loc.is_null() {
692        return core::ptr::null_mut();
693    }
694    C_LOCALE
695}
696
697const NL_ITEM_CODESET: c_int = 14;
698const NL_ITEM_RADIXCHAR: c_int = 0x10000;
699const NL_ITEM_THOUSEP: c_int = 0x10001;
700const NL_ITEM_YESEXPR: c_int = 0x50000;
701const NL_ITEM_NOEXPR: c_int = 0x50001;
702
703const C_TIME_STRINGS: &[u8] = b"Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat\0\
704Sunday\0Monday\0Tuesday\0Wednesday\0Thursday\0Friday\0Saturday\0\
705Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec\0\
706January\0February\0March\0April\0May\0June\0July\0August\0\
707September\0October\0November\0December\0\
708AM\0PM\0\
709%a %b %e %T %Y\0%m/%d/%y\0%H:%M:%S\0%I:%M:%S %p\0\
710\0\0%m/%d/%y\00123456789\0%a %b %e %T %Y\0%H:%M:%S\0";
711
712const C_NUMERIC_STRINGS: &[u8] = b".\0\0";
713const C_MESSAGES_STRINGS: &[u8] = b"^[yY]\0^[nN]\0";
714
715unsafe fn langinfo_str(table: *const u8, mut idx: c_int) -> *mut c_char {
716    let mut p = table;
717    while idx > 0 {
718        while *p != 0 { p = p.add(1); }
719        p = p.add(1);
720        idx -= 1;
721    }
722    p as *mut c_char
723}
724
725#[no_mangle]
726pub unsafe extern "C" fn nl_langinfo(item: c_int) -> *mut c_char {
727    if item == NL_ITEM_CODESET {
728        return if LOCALE_CTYPE_UTF8 {
729            b"UTF-8\0".as_ptr() as *mut c_char
730        } else {
731            b"US-ASCII\0".as_ptr() as *mut c_char
732        };
733    }
734    let cat = item >> 16;
735    let idx = item & 0xFFFF;
736    match cat {
737        1 => {
738            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
739            langinfo_str(C_NUMERIC_STRINGS.as_ptr(), idx)
740        }
741        2 => {
742            if idx > 49 { return b"\0".as_ptr() as *mut c_char; }
743            langinfo_str(C_TIME_STRINGS.as_ptr(), idx)
744        }
745        5 => {
746            if idx > 1 { return b"\0".as_ptr() as *mut c_char; }
747            langinfo_str(C_MESSAGES_STRINGS.as_ptr(), idx)
748        }
749        _ => b"\0".as_ptr() as *mut c_char,
750    }
751}
752
753pub type nl_catd = *mut c_void;
754
755#[no_mangle]
756pub unsafe extern "C" fn catopen(_name: *const c_char, _oflag: c_int) -> nl_catd {
757    !0usize as nl_catd
758}
759
760#[no_mangle]
761pub unsafe extern "C" fn catclose(_catd: nl_catd) -> c_int { 0 }
762
763#[no_mangle]
764pub unsafe extern "C" fn catgets(catd: nl_catd, _set_id: c_int, _msg_id: c_int, s: *const c_char) -> *mut c_char {
765    if catd == !0usize as nl_catd {
766        ERRNO!() = EBADF;
767        return s as *mut c_char;
768    }
769    s as *mut c_char
770}
771
772pub type IconvT = *mut c_void;
773
774const UNICODE_SURROGATE_START: u32 = 0xD800;
775const UNICODE_HIGH_SURROGATE_END: u32 = 0xDBFF;
776const UNICODE_LOW_SURROGATE_START: u32 = 0xDC00;
777const UNICODE_SURROGATE_END: u32 = 0xDFFF;
778const UNICODE_SURROGATE_END_EXCL: u32 = 0xE000;
779const UNICODE_SUPPLEMENTARY_BASE: u32 = 0x10000;
780const UNICODE_SUPPLEMENTARY_SIZE: u32 = 0x100000;
781const UNICODE_MAX: u32 = 0x110000;
782
783const ENC_UTF8: i32 = 1;
784const ENC_UTF16LE: i32 = 2;
785const ENC_UTF16BE: i32 = 3;
786const ENC_UTF32LE: i32 = 4;
787const ENC_UTF32BE: i32 = 5;
788const ENC_WCHAR_T: i32 = 6;
789const ENC_ASCII: i32 = 7;
790const ENC_LATIN1: i32 = 8;
791const ENC_WIN1252: i32 = 9;
792const ENC_WIN1251: i32 = 10;
793const ENC_KOI8R: i32 = 11;
794const ENC_GBK: i32 = 12;
795const ENC_GB2312: i32 = 13;
796const ENC_BIG5: i32 = 14;
797const ENC_EUCJP: i32 = 15;
798const ENC_SHIFTJIS: i32 = 16;
799const ENC_ISO8859_2: i32 = 17;
800const ENC_ISO8859_3: i32 = 18;
801const ENC_ISO8859_4: i32 = 19;
802const ENC_ISO8859_5: i32 = 20;
803const ENC_ISO8859_6: i32 = 21;
804const ENC_ISO8859_7: i32 = 22;
805const ENC_ISO8859_8: i32 = 23;
806const ENC_ISO8859_9: i32 = 24;
807const ENC_ISO8859_10: i32 = 25;
808const ENC_ISO8859_11: i32 = 26;
809const ENC_ISO8859_13: i32 = 27;
810const ENC_ISO8859_14: i32 = 28;
811const ENC_ISO8859_15: i32 = 29;
812const ENC_ISO8859_16: i32 = 30;
813
814
815fn make_cd(from: i32, to: i32) -> IconvT {
816    ((from as usize) << 16 | (to as usize) << 1 | 1) as IconvT
817}
818fn extract_from(cd: IconvT) -> i32 {
819    ((cd as usize) >> 16) as i32
820}
821fn extract_to(cd: IconvT) -> i32 {
822    (((cd as usize) >> 1) & 0x7fff) as i32
823}
824
825unsafe fn match_name(input: *const u8, target: &[u8]) -> bool {
826    let mut i = input;
827    let mut j = 0;
828    while *i != 0 && j < target.len() {
829        let mut c = *i;
830        if !c.is_ascii_alphanumeric() { i = i.add(1); continue; }
831        c = c.to_ascii_lowercase();
832        if c != target[j] { return false; }
833        i = i.add(1);
834        j += 1;
835    }
836    while *i != 0 && !(*i).is_ascii_alphanumeric() { i = i.add(1); }
837    *i == 0 && j == target.len()
838}
839
840const ENCODING_ALIASES: &[(&[&[u8]], i32)] = &[
841    (&[b"utf8", b"utf-8", b"char"], ENC_UTF8),
842    (&[b"utf16le", b"utf-16le"], ENC_UTF16LE),
843    (&[b"utf16be", b"utf-16be"], ENC_UTF16BE),
844    (&[b"utf32le", b"utf-32le", b"ucs4le"], ENC_UTF32LE),
845    (&[b"utf32be", b"utf-32be", b"ucs4be"], ENC_UTF32BE),
846    (&[b"wchart", b"wchar-t"], ENC_WCHAR_T),
847    (&[b"ascii", b"usascii", b"iso646"], ENC_ASCII),
848    (&[b"iso88591", b"iso-8859-1", b"latin1"], ENC_LATIN1),
849    (&[b"iso88592", b"iso-8859-2"], ENC_ISO8859_2),
850    (&[b"iso88593", b"iso-8859-3"], ENC_ISO8859_3),
851    (&[b"iso88594", b"iso-8859-4"], ENC_ISO8859_4),
852    (&[b"iso88595", b"iso-8859-5"], ENC_ISO8859_5),
853    (&[b"iso88596", b"iso-8859-6"], ENC_ISO8859_6),
854    (&[b"iso88597", b"iso-8859-7"], ENC_ISO8859_7),
855    (&[b"iso88598", b"iso-8859-8"], ENC_ISO8859_8),
856    (&[b"iso88599", b"iso-8859-9"], ENC_ISO8859_9),
857    (&[b"iso885910", b"iso-8859-10"], ENC_ISO8859_10),
858    (&[b"iso885911", b"iso-8859-11", b"tis620"], ENC_ISO8859_11),
859    (&[b"iso885913", b"iso-8859-13"], ENC_ISO8859_13),
860    (&[b"iso885914", b"iso-8859-14"], ENC_ISO8859_14),
861    (&[b"iso885915", b"iso-8859-15"], ENC_ISO8859_15),
862    (&[b"iso885916", b"iso-8859-16"], ENC_ISO8859_16),
863    (&[b"cp1252", b"windows1252", b"windows-1252"], ENC_WIN1252),
864    (&[b"cp1251", b"windows1251", b"windows-1251"], ENC_WIN1251),
865    (&[b"koi8r", b"koi8-r"], ENC_KOI8R),
866    (&[b"gbk", b"cp936"], ENC_GBK),
867    (&[b"gb2312"], ENC_GB2312),
868    (&[b"big5", b"bigfive", b"cp950"], ENC_BIG5),
869    (&[b"eucjp", b"euc-jp"], ENC_EUCJP),
870    (&[b"shiftjis", b"sjis", b"cp932"], ENC_SHIFTJIS),
871];
872
873unsafe fn find_encoding(name: *const u8) -> i32 {
874    if name.is_null() { return -1; }
875    for &(aliases, enc) in ENCODING_ALIASES {
876        for alias in aliases {
877            if match_name(name, alias) {
878                return enc;
879            }
880        }
881    }
882    -1
883}
884
885fn uni_to_jis(c: u32) -> u16 {
886    let mut b = 0usize;
887    let mut nel = REV_JIS.len();
888    loop {
889        let i = nel / 2;
890        let j = REV_JIS[b + i] as usize;
891        let row = j / 256;
892        let col = j % 256;
893        let d = JIS0208[row * 94 + col] as u32;
894        if d == c { return (j as u16) + 0x2121; }
895        if nel == 1 { return 0; }
896        if c < d { nel /= 2; }
897        else { b += i; nel -= nel / 2; }
898    }
899}
900
901fn iso8859_decode_table(enc: i32) -> Option<&'static [u32; 128]> {
902    match enc {
903        ENC_ISO8859_2 => Some(&ISO8859_2_TO_U),
904        ENC_ISO8859_3 => Some(&ISO8859_3_TO_U),
905        ENC_ISO8859_4 => Some(&ISO8859_4_TO_U),
906        ENC_ISO8859_5 => Some(&ISO8859_5_TO_U),
907        ENC_ISO8859_6 => Some(&ISO8859_6_TO_U),
908        ENC_ISO8859_7 => Some(&ISO8859_7_TO_U),
909        ENC_ISO8859_8 => Some(&ISO8859_8_TO_U),
910        ENC_ISO8859_9 => Some(&ISO8859_9_TO_U),
911        ENC_ISO8859_10 => Some(&ISO8859_10_TO_U),
912        ENC_ISO8859_11 => Some(&ISO8859_11_TO_U),
913        ENC_ISO8859_13 => Some(&ISO8859_13_TO_U),
914        ENC_ISO8859_14 => Some(&ISO8859_14_TO_U),
915        ENC_ISO8859_15 => Some(&ISO8859_15_TO_U),
916        ENC_ISO8859_16 => Some(&ISO8859_16_TO_U),
917        _ => None,
918    }
919}
920
921unsafe fn iconv_decode(enc: i32, src: *const u8, src_left: usize) -> (u32, usize, c_int) {
922    if src_left == 0 { return (0, 0, EINVAL); }
923    if let Some(table) = iso8859_decode_table(enc) {
924        return (iso8859_to_u(table, *src), 1, 0);
925    }
926    match enc {
927        ENC_UTF8 => {
928            let c = *src;
929            if c < 128 { return (c as u32, 1, 0); }
930            if c < 0xC2 { return (0, 0, EILSEQ); }
931            if c < 0xE0 {
932                if src_left < 2 || (*src.add(1) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
933                return (((c as u32 & 0x1F) << 6) | (*src.add(1) as u32 & 0x3F), 2, 0);
934            }
935            if c < 0xF0 {
936                if src_left < 3 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
937                let cp = ((c as u32 & 0x0F) << 12) | ((*src.add(1) as u32 & 0x3F) << 6) | (*src.add(2) as u32 & 0x3F);
938                if cp < 0x800 { return (0, 0, EILSEQ); }
939                return (cp, 3, 0);
940            }
941            if c < 0xF8 {
942                if src_left < 4 || (*src.add(1) & 0xC0) != 0x80 || (*src.add(2) & 0xC0) != 0x80 || (*src.add(3) & 0xC0) != 0x80 { return (0, 0, EILSEQ); }
943                let cp = ((c as u32 & 0x07) << 18) | ((*src.add(1) as u32 & 0x3F) << 12) | ((*src.add(2) as u32 & 0x3F) << 6) | (*src.add(3) as u32 & 0x3F);
944                if cp < UNICODE_SUPPLEMENTARY_BASE || cp >= UNICODE_MAX { return (0, 0, EILSEQ); }
945                return (cp, 4, 0);
946            }
947            (0, 0, EILSEQ)
948        }
949        ENC_UTF16LE => {
950            if src_left < 2 { return (0, 0, EINVAL); }
951            let c = (*src as u32) | ((*src.add(1) as u32) << 8);
952            if c >= UNICODE_SURROGATE_START && c <= UNICODE_HIGH_SURROGATE_END {
953                if src_left < 4 { return (0, 0, EINVAL); }
954                let d = (*src.add(2) as u32) | ((*src.add(3) as u32) << 8);
955                if d < UNICODE_LOW_SURROGATE_START || d > UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
956                return (((c - UNICODE_SURROGATE_START) << 10) + (d - UNICODE_LOW_SURROGATE_START) + UNICODE_SUPPLEMENTARY_BASE, 4, 0);
957            }
958            if c >= UNICODE_LOW_SURROGATE_START && c <= UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
959            (c, 2, 0)
960        }
961        ENC_UTF16BE => {
962            if src_left < 2 { return (0, 0, EINVAL); }
963            let c = ((*src as u32) << 8) | (*src.add(1) as u32);
964            if c >= UNICODE_SURROGATE_START && c <= UNICODE_HIGH_SURROGATE_END {
965                if src_left < 4 { return (0, 0, EINVAL); }
966                let d = ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
967                if d < UNICODE_LOW_SURROGATE_START || d > UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
968                return (((c - UNICODE_SURROGATE_START) << 10) + (d - UNICODE_LOW_SURROGATE_START) + UNICODE_SUPPLEMENTARY_BASE, 4, 0);
969            }
970            if c >= UNICODE_LOW_SURROGATE_START && c <= UNICODE_SURROGATE_END { return (0, 0, EILSEQ); }
971            (c, 2, 0)
972        }
973        ENC_UTF32LE => {
974            if src_left < 4 { return (0, 0, EINVAL); }
975            let c = (*src as u32) | ((*src.add(1) as u32) << 8) | ((*src.add(2) as u32) << 16) | ((*src.add(3) as u32) << 24);
976            if c >= UNICODE_SURROGATE_START && c < UNICODE_SURROGATE_END_EXCL { return (0, 0, EILSEQ); }
977            if c >= UNICODE_MAX { return (0, 0, EILSEQ); }
978            (c, 4, 0)
979        }
980        ENC_UTF32BE => {
981            if src_left < 4 { return (0, 0, EINVAL); }
982            let c = ((*src as u32) << 24) | ((*src.add(1) as u32) << 16) | ((*src.add(2) as u32) << 8) | (*src.add(3) as u32);
983            if c >= UNICODE_SURROGATE_START && c < UNICODE_SURROGATE_END_EXCL { return (0, 0, EILSEQ); }
984            if c >= UNICODE_MAX { return (0, 0, EILSEQ); }
985            (c, 4, 0)
986        }
987        ENC_WCHAR_T => {
988            if src_left < 4 { return (0, 0, EINVAL); }
989            let c = core::ptr::read_unaligned(src as *const u32);
990            if c >= UNICODE_SURROGATE_START && c < UNICODE_SURROGATE_END_EXCL { return (0, 0, EILSEQ); }
991            if c >= UNICODE_MAX { return (0, 0, EILSEQ); }
992            (c, 4, 0)
993        }
994        ENC_ASCII => {
995            let c = *src as u32;
996            if c >= 128 { return (0, 0, EILSEQ); }
997            (c, 1, 0)
998        }
999        ENC_LATIN1 => (*src as u32, 1, 0),
1000        ENC_WIN1252 => {
1001            let b = *src;
1002            if b < 128 { return (b as u32, 1, 0); }
1003            (WIN1252_TO_U[b as usize - 128], 1, 0)
1004        }
1005        ENC_GBK | ENC_GB2312 => {
1006            let c = *src;
1007            if c < 128 { return (c as u32, 1, 0); }
1008            if c == 128 { return (0x20AC, 1, 0); }
1009            if src_left < 2 { return (0, 0, EINVAL); }
1010            let d = *src.add(1);
1011            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
1012            let row = (c as usize).wrapping_sub(0x81);
1013            if row >= 126 { return (0, 0, EILSEQ); }
1014            let mut col = (d as usize) - 0x40;
1015            if col > 63 { col -= 1; }
1016            let cp = GB18030_TABLE[row * 190 + col] as u32;
1017            if cp == 0 { return (0, 0, EILSEQ); }
1018            (cp, 2, 0)
1019        }
1020        ENC_BIG5 => {
1021            let c = *src;
1022            if c < 128 { return (c as u32, 1, 0); }
1023            if src_left < 2 { return (0, 0, EINVAL); }
1024            let d = *src.add(1);
1025            if d < 0x40 || d == 0x7F || d > 0xFE { return (0, 0, EILSEQ); }
1026            let mut col = (d as usize) - 0x40;
1027            if col > 0x3E { col -= 0x22; }
1028            if c >= 0xA1 && c < 0xFA {
1029                let row = (c as usize) - 0xA1;
1030                if row >= 89 { return (0, 0, EILSEQ); }
1031                let cp = BIG5_TABLE[row * 157 + col] as u32;
1032                if cp == 0 { return (0, 0, EILSEQ); }
1033                return (cp, 2, 0);
1034            }
1035            (0, 0, EILSEQ)
1036        }
1037        ENC_EUCJP => {
1038            let c = *src;
1039            if c < 128 { return (c as u32, 1, 0); }
1040            if c == 0x8E {
1041                if src_left < 2 { return (0, 0, EINVAL); }
1042                let d = *src.add(1);
1043                if d < 0xA1 || d > 0xDF { return (0, 0, EILSEQ); }
1044                return ((d as u32) + 0xFF61 - 0xA1, 2, 0);
1045            }
1046            if c < 0xA1 { return (0, 0, EILSEQ); }
1047            if src_left < 2 { return (0, 0, EINVAL); }
1048            let d = *src.add(1);
1049            if d < 0xA1 || d > 0xFE { return (0, 0, EILSEQ); }
1050            let row = (c as usize) - 0xA1;
1051            let col = (d as usize) - 0xA1;
1052            if row >= 84 || col >= 94 { return (0, 0, EILSEQ); }
1053            let cp = JIS0208[row * 94 + col] as u32;
1054            if cp == 0 { return (0, 0, EILSEQ); }
1055            (cp, 2, 0)
1056        }
1057        ENC_SHIFTJIS => {
1058            let c = *src;
1059            if c < 128 { return (c as u32, 1, 0); }
1060            if c >= 0xA1 && c <= 0xDF { return ((c as u32) + 0xFF61 - 0xA1, 1, 0); }
1061            if src_left < 2 { return (0, 0, EINVAL); }
1062            let d = *src.add(1);
1063            if d < 0x40 || d == 0x7F || d > 0xFC { return (0, 0, EILSEQ); }
1064            let row = if c >= 129 && c <= 159 { (c as usize) - 129 }
1065                      else if c >= 224 && c <= 239 { (c as usize) - 193 }
1066                      else { return (0, 0, EILSEQ); };
1067            let (col, row_adj) = if d >= 64 && d <= 158 && d != 127 {
1068                let mut dd = d as usize;
1069                if dd > 127 { dd -= 1; }
1070                (dd - 64, row * 2)
1071            } else if d >= 159 && d <= 252 {
1072                ((d as usize) - 159, row * 2 + 1)
1073            } else {
1074                return (0, 0, EILSEQ);
1075            };
1076            if row_adj >= 84 { return (0, 0, EILSEQ); }
1077            let cp = JIS0208[row_adj * 94 + col] as u32;
1078            if cp == 0 { return (0, 0, EILSEQ); }
1079            (cp, 2, 0)
1080        }
1081        _ => (0, 0, EILSEQ),
1082    }
1083}
1084
1085unsafe fn encode_single_byte(
1086    table: &[u32; 128],
1087    c: u32,
1088    dst: *mut u8,
1089    dst_left: usize,
1090) -> (usize, c_int) {
1091    if let Some(b) = u_to_iso8859(table, c) {
1092        if dst_left < 1 { return (0, E2BIG); }
1093        *dst = b;
1094        (1, 0)
1095    } else {
1096        (0, EILSEQ)
1097    }
1098}
1099
1100unsafe fn iconv_encode(enc: i32, c: u32, dst: *mut u8, dst_left: usize) -> (usize, c_int) {
1101    // All ISO-8859 tables, Windows-1251 and KOI8-R share the same
1102    // ASCII-passthrough + reverse-table encoding.
1103    let single_byte_table = match enc {
1104        ENC_ISO8859_2 => Some(&ISO8859_2_TO_U),
1105        ENC_ISO8859_3 => Some(&ISO8859_3_TO_U),
1106        ENC_ISO8859_4 => Some(&ISO8859_4_TO_U),
1107        ENC_ISO8859_5 => Some(&ISO8859_5_TO_U),
1108        ENC_ISO8859_6 => Some(&ISO8859_6_TO_U),
1109        ENC_ISO8859_7 => Some(&ISO8859_7_TO_U),
1110        ENC_ISO8859_8 => Some(&ISO8859_8_TO_U),
1111        ENC_ISO8859_9 => Some(&ISO8859_9_TO_U),
1112        ENC_ISO8859_10 => Some(&ISO8859_10_TO_U),
1113        ENC_ISO8859_11 => Some(&ISO8859_11_TO_U),
1114        ENC_ISO8859_13 => Some(&ISO8859_13_TO_U),
1115        ENC_ISO8859_14 => Some(&ISO8859_14_TO_U),
1116        ENC_ISO8859_15 => Some(&ISO8859_15_TO_U),
1117        ENC_ISO8859_16 => Some(&ISO8859_16_TO_U),
1118        ENC_WIN1251 => Some(&WIN1251_TO_U),
1119        ENC_KOI8R => Some(&KOI8R_TO_U),
1120        _ => None,
1121    };
1122    if let Some(table) = single_byte_table {
1123        return encode_single_byte(table, c, dst, dst_left);
1124    }
1125
1126    match enc {
1127        ENC_UTF8 => {
1128            if c < 0x80 {
1129                if dst_left < 1 { return (0, E2BIG); }
1130                *dst = c as u8; return (1, 0);
1131            }
1132            if c < 0x800 {
1133                if dst_left < 2 { return (0, E2BIG); }
1134                *dst = (0xC0 | (c >> 6)) as u8;
1135                *dst.add(1) = (0x80 | (c & 0x3F)) as u8;
1136                return (2, 0);
1137            }
1138            if c < 0x10000 {
1139                if dst_left < 3 { return (0, E2BIG); }
1140                *dst = (0xE0 | (c >> 12)) as u8;
1141                *dst.add(1) = (0x80 | ((c >> 6) & 0x3F)) as u8;
1142                *dst.add(2) = (0x80 | (c & 0x3F)) as u8;
1143                return (3, 0);
1144            }
1145            if dst_left < 4 { return (0, E2BIG); }
1146            *dst = (0xF0 | (c >> 18)) as u8;
1147            *dst.add(1) = (0x80 | ((c >> 12) & 0x3F)) as u8;
1148            *dst.add(2) = (0x80 | ((c >> 6) & 0x3F)) as u8;
1149            *dst.add(3) = (0x80 | (c & 0x3F)) as u8;
1150            (4, 0)
1151        }
1152        ENC_UTF16LE => {
1153            if c < UNICODE_SUPPLEMENTARY_BASE {
1154                if dst_left < 2 { return (0, E2BIG); }
1155                *dst = (c & 0xFF) as u8;
1156                *dst.add(1) = (c >> 8) as u8;
1157                return (2, 0);
1158            }
1159            if dst_left < 4 { return (0, E2BIG); }
1160            let c = c - UNICODE_SUPPLEMENTARY_BASE;
1161            let hi = ((c >> 10) + UNICODE_SURROGATE_START) as u16;
1162            let lo = ((c & 0x3FF) + UNICODE_LOW_SURROGATE_START) as u16;
1163            *dst = (hi & 0xFF) as u8; *dst.add(1) = (hi >> 8) as u8;
1164            *dst.add(2) = (lo & 0xFF) as u8; *dst.add(3) = (lo >> 8) as u8;
1165            (4, 0)
1166        }
1167        ENC_UTF16BE => {
1168            if c < UNICODE_SUPPLEMENTARY_BASE {
1169                if dst_left < 2 { return (0, E2BIG); }
1170                *dst = (c >> 8) as u8;
1171                *dst.add(1) = (c & 0xFF) as u8;
1172                return (2, 0);
1173            }
1174            if dst_left < 4 { return (0, E2BIG); }
1175            let c = c - UNICODE_SUPPLEMENTARY_BASE;
1176            let hi = ((c >> 10) + UNICODE_SURROGATE_START) as u16;
1177            let lo = ((c & 0x3FF) + UNICODE_LOW_SURROGATE_START) as u16;
1178            *dst = (hi >> 8) as u8; *dst.add(1) = (hi & 0xFF) as u8;
1179            *dst.add(2) = (lo >> 8) as u8; *dst.add(3) = (lo & 0xFF) as u8;
1180            (4, 0)
1181        }
1182        ENC_UTF32LE => {
1183            if dst_left < 4 { return (0, E2BIG); }
1184            *dst = (c & 0xFF) as u8; *dst.add(1) = ((c >> 8) & 0xFF) as u8;
1185            *dst.add(2) = ((c >> 16) & 0xFF) as u8; *dst.add(3) = (c >> 24) as u8;
1186            (4, 0)
1187        }
1188        ENC_UTF32BE => {
1189            if dst_left < 4 { return (0, E2BIG); }
1190            *dst = (c >> 24) as u8; *dst.add(1) = ((c >> 16) & 0xFF) as u8;
1191            *dst.add(2) = ((c >> 8) & 0xFF) as u8; *dst.add(3) = (c & 0xFF) as u8;
1192            (4, 0)
1193        }
1194        ENC_WCHAR_T => {
1195            if dst_left < 4 { return (0, E2BIG); }
1196            core::ptr::write_unaligned(dst as *mut u32, c);
1197            (4, 0)
1198        }
1199        ENC_ASCII => {
1200            if c < 128 {
1201                if dst_left < 1 { return (0, E2BIG); }
1202                *dst = c as u8; return (1, 0);
1203            }
1204            (0, EILSEQ)
1205        }
1206        ENC_LATIN1 => {
1207            if c < 256 {
1208                if dst_left < 1 { return (0, E2BIG); }
1209                *dst = c as u8; return (1, 0);
1210            }
1211            (0, EILSEQ)
1212        }
1213        ENC_WIN1252 => {
1214            if c < 128 {
1215                if dst_left < 1 { return (0, E2BIG); }
1216                *dst = c as u8; return (1, 0);
1217            }
1218            if c >= 0xA0 && c <= 0xFF && WIN1252_TO_U[c as usize - 128] == c {
1219                if dst_left < 1 { return (0, E2BIG); }
1220                *dst = c as u8; return (1, 0);
1221            }
1222            for i in 0..128usize {
1223                if WIN1252_TO_U[i] == c {
1224                    if dst_left < 1 { return (0, E2BIG); }
1225                    *dst = (i + 128) as u8; return (1, 0);
1226                }
1227            }
1228            (0, EILSEQ)
1229        }
1230        ENC_GBK | ENC_GB2312 => {
1231            if c < 128 {
1232                if dst_left < 1 { return (0, E2BIG); }
1233                *dst = c as u8; return (1, 0);
1234            }
1235            if c == 0x20AC {
1236                if dst_left < 1 { return (0, E2BIG); }
1237                *dst = 128; return (1, 0);
1238            }
1239            for row in 0..126usize {
1240                for col in 0..190usize {
1241                    if GB18030_TABLE[row * 190 + col] as u32 == c {
1242                        if dst_left < 2 { return (0, E2BIG); }
1243                        *dst = (row + 0x81) as u8;
1244                        *dst.add(1) = if col <= 62 { (col + 0x40) as u8 } else { (col + 0x41) as u8 };
1245                        return (2, 0);
1246                    }
1247                }
1248            }
1249            (0, EILSEQ)
1250        }
1251        ENC_BIG5 => {
1252            if c < 128 {
1253                if dst_left < 1 { return (0, E2BIG); }
1254                *dst = c as u8; return (1, 0);
1255            }
1256            for row in 0..89usize {
1257                for col in 0..157usize {
1258                    if BIG5_TABLE[row * 157 + col] as u32 == c {
1259                        if dst_left < 2 { return (0, E2BIG); }
1260                        *dst = (row + 0xA1) as u8;
1261                        *dst.add(1) = if col <= 0x3E { (col + 0x40) as u8 } else { (col + 0x62) as u8 };
1262                        return (2, 0);
1263                    }
1264                }
1265            }
1266            (0, EILSEQ)
1267        }
1268        ENC_EUCJP => {
1269            if c < 128 {
1270                if dst_left < 1 { return (0, E2BIG); }
1271                *dst = c as u8; return (1, 0);
1272            }
1273            if c >= 0xFF61 && c <= 0xFF9F {
1274                if dst_left < 2 { return (0, E2BIG); }
1275                *dst = 0x8E;
1276                *dst.add(1) = (c - 0xFF61 + 0xA1) as u8;
1277                return (2, 0);
1278            }
1279            let jis = uni_to_jis(c);
1280            if jis == 0 { return (0, EILSEQ); }
1281            if dst_left < 2 { return (0, E2BIG); }
1282            *dst = ((jis >> 8) as u8).wrapping_add(0x80);
1283            *dst.add(1) = ((jis & 0xFF) as u8).wrapping_add(0x80);
1284            (2, 0)
1285        }
1286        ENC_SHIFTJIS => {
1287            if c < 128 {
1288                if dst_left < 1 { return (0, E2BIG); }
1289                *dst = c as u8; return (1, 0);
1290            }
1291            if c >= 0xFF61 && c <= 0xFF9F {
1292                if dst_left < 1 { return (0, E2BIG); }
1293                *dst = (c - 0xFF61 + 0xA1) as u8;
1294                return (1, 0);
1295            }
1296            let jis = uni_to_jis(c);
1297            if jis == 0 { return (0, EILSEQ); }
1298            if dst_left < 2 { return (0, E2BIG); }
1299            let r = (jis >> 8) as usize;
1300            let d = (jis & 0xFF) as usize;
1301            *dst = ((r + 1) / 2 + if r < 95 { 112 } else { 176 }) as u8;
1302            *dst.add(1) = if r % 2 == 1 { (d + 31 + d / 96) as u8 } else { (d + 126) as u8 };
1303            (2, 0)
1304        }
1305        _ => (0, EILSEQ),
1306    }
1307}
1308
1309#[no_mangle]
1310pub unsafe extern "C" fn iconv_open(tocode: *const c_char, fromcode: *const c_char) -> IconvT {
1311    let to = find_encoding(tocode as *const u8);
1312    let from = find_encoding(fromcode as *const u8);
1313    if to < 0 || from < 0 {
1314        ERRNO!() = EINVAL;
1315        return !0usize as IconvT;
1316    }
1317    make_cd(from, to)
1318}
1319
1320#[no_mangle]
1321pub unsafe extern "C" fn iconv(
1322    cd: IconvT,
1323    inbuf: *mut *mut c_char,
1324    inbytesleft: *mut SizeT,
1325    outbuf: *mut *mut c_char,
1326    outbytesleft: *mut SizeT,
1327) -> SizeT {
1328    if cd == !0usize as IconvT {
1329        ERRNO!() = EINVAL;
1330        return !0usize;
1331    }
1332    // A null inbuf is the state-reset call; all converters are stateless.
1333    if inbuf.is_null() { return 0; }
1334    if inbytesleft.is_null() || outbuf.is_null() || outbytesleft.is_null() {
1335        ERRNO!() = EINVAL;
1336        return !0usize;
1337    }
1338    let from = extract_from(cd);
1339    let to = extract_to(cd);
1340    let mut src = *inbuf as *const u8;
1341    let mut dst = *outbuf as *mut u8;
1342    let mut src_left = *inbytesleft;
1343    let mut dst_left = *outbytesleft;
1344    let mut subst = 0usize;
1345    // Publish the conversion position before every error return; POSIX
1346    // requires *inbuf/*outbuf to point at the unconverted input/output.
1347    macro_rules! fail {
1348        ($e:expr) => {{
1349            *inbuf = src as *mut c_char;
1350            *outbuf = dst as *mut c_char;
1351            *inbytesleft = src_left;
1352            *outbytesleft = dst_left;
1353            ERRNO!() = $e;
1354            return !0usize;
1355        }};
1356    }
1357    while src_left > 0 {
1358        let (cp, consumed, err) = iconv_decode(from, src, src_left);
1359        if err != 0 {
1360            if err == EINVAL { break; }
1361            fail!(err);
1362        }
1363        let (written, err) = iconv_encode(to, cp, dst, dst_left);
1364        if err != 0 {
1365            if err == E2BIG {
1366                fail!(E2BIG);
1367            }
1368            if dst_left < 1 {
1369                fail!(E2BIG);
1370            }
1371            *dst = b'*';
1372            dst = dst.add(1);
1373            dst_left -= 1;
1374            subst += 1;
1375        } else {
1376            dst = dst.add(written);
1377            dst_left -= written;
1378        }
1379        src = src.add(consumed);
1380        src_left -= consumed;
1381    }
1382    *inbuf = src as *mut c_char;
1383    *outbuf = dst as *mut c_char;
1384    *inbytesleft = src_left;
1385    *outbytesleft = dst_left;
1386    subst
1387}
1388
1389#[no_mangle]
1390pub unsafe extern "C" fn iconv_close(_cd: IconvT) -> c_int { 0 }
1391