path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
cosmopolitan/libc/sysv/consts/TCSAFLUSH.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,TCSAFLUSH,2,2,2,2,2,2,2,2
| 88 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SHM_W.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon shm,SHM_W,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0
| 101 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/IP_RECVERR.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ip,IP_RECVERR,11,11,0,0,0,0,0,75
| 87 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/TIOCNXCL.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,TIOCNXCL,0x540d,0x540d,0x2000740e,0x2000740e,0x2000740e,0x2000740e,0x2000740e,0
| 142 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SIGXFSZ.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon sig,SIGXFSZ,25,25,25,25,25,25,25,25
| 90 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/TIOCMSET.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon modem,TIOCMSET,0x5418,0x5418,0x8004746d,0x8004746d,0x8004746d,0x8004746d,0x8004746d,-1
| 141 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/fs.h | #ifndef COSMOPOLITAN_LIBC_SYSV_CONSTS_FS_H_
#define COSMOPOLITAN_LIBC_SYSV_CONSTS_FS_H_
#define FS_IOC_GETFLAGS 0x80086601
#define FS_IOC_SETFLAGS 0x40086602
#define FS_IOC_GETVERSION 0x80087601
#define FS_IOC_SETVERSION 0x40087602
#define FS_IOC_FIEMAP 0xc020660b
#define FS_IOC_FSGETXATTR 0x801c581f
#define FS_IOC_FSSETXATTR 0x401c5820
#define FS_IOC_GETFSLABEL 0x81009431
#define FS_IOC_SETFSLABEL 0x41009432
#define FS_FL_USER_VISIBLE 0x0003DFFF /* user visible flags */
#define FS_FL_USER_MODIFIABLE 0x000380FF /* user modifiable flags */
#define FS_SECRM_FL 0x00000001 /* secure deletion */
#define FS_UNRM_FL 0x00000002 /* undelete */
#define FS_COMPR_FL 0x00000004 /* compress */
#define FS_SYNC_FL 0x00000008 /* synchronous */
#define FS_IMMUTABLE_FL 0x00000010
#define FS_APPEND_FL 0x00000020 /* append-only */
#define FS_NODUMP_FL 0x00000040
#define FS_NOATIME_FL 0x00000080
#define FS_DIRTY_FL 0x00000100
#define FS_COMPRBLK_FL 0x00000200
#define FS_NOCOMP_FL 0x00000400
#define FS_ENCRYPT_FL 0x00000800 /* encrypted file */
#define FS_BTREE_FL 0x00001000
#define FS_INDEX_FL 0x00001000 /* hash-indexed directory */
#define FS_IMAGIC_FL 0x00002000
#define FS_JOURNAL_DATA_FL 0x00004000
#define FS_NOTAIL_FL 0x00008000
#define FS_DIRSYNC_FL 0x00010000
#define FS_TOPDIR_FL 0x00020000
#define FS_HUGE_FILE_FL 0x00040000
#define FS_EXTENT_FL 0x00080000
#endif /* COSMOPOLITAN_LIBC_SYSV_CONSTS_FS_H_ */
| 1,607 | 39 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SF_MNOWAIT.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon sf,SF_MNOWAIT,0,0,0,0,2,0,0,0
| 84 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_vmsplice.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_vmsplice,0x0116,0x004b,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff
| 121 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/O_CLOEXEC.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon open,O_CLOEXEC,0x00080000,0x00080000,0x01000000,0x01000000,0x00100000,0x00010000,0x00400000,0x00080000
| 157 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/IPV6_V6ONLY.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ipv6,IPV6_V6ONLY,26,26,27,27,27,27,27,27
| 95 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SA_NOMASK.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon compat,SA_NOMASK,0x40000000,0x40000000,16,16,16,16,16,0x40000000
| 119 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/EPFNOSUPPORT.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon errno,EPFNOSUPPORT,96,96,46,46,46,46,46,10046
| 100 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/ENOTSUP.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon errno,ENOTSUP,95,95,45,45,45,91,86,10045
#ifdef __x86_64__
.yoink kDos2Errno.ENOTSUP
#endif
| 146 | 6 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SO_KEEPALIVE.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon so,SO_KEEPALIVE,9,9,8,8,8,8,8,8
| 86 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/B38400.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon baud,B38400,15,15,38400,38400,38400,38400,38400,38400
| 108 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/w.h | #ifndef COSMOPOLITAN_LIBC_SYSV_CONSTS_W_H_
#define COSMOPOLITAN_LIBC_SYSV_CONSTS_W_H_
#include "libc/runtime/symbolic.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const int WNOHANG;
extern const int WUNTRACED;
extern const int WCONTINUED;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#define WNOHANG LITERALLY(1)
#define WUNTRACED SYMBOLIC(WUNTRACED)
#define WCONTINUED SYMBOLIC(WCONTINUED)
#endif /* COSMOPOLITAN_LIBC_SYSV_CONSTS_W_H_ */
| 494 | 19 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/VMIN.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,VMIN,6+1,6+1,16,16,16,16,16,6
| 92 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/CHRTYPE.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon misc,CHRTYPE,51,51,51,51,51,51,51,0
| 90 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/_posix.h | #ifndef COSMOPOLITAN_LIBC_SYSV_CONSTS__POSIX_H_
#define COSMOPOLITAN_LIBC_SYSV_CONSTS__POSIX_H_
/* The Open Group Base Specifications Issue 7, 2018 edition */
/* IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008) */
#define _POSIX_AIO_LISTIO_MAX 2
#define _POSIX_CLOCKRES_MIN 20000000
#define _POSIX_AIO_MAX 1
#define _POSIX_ARG_MAX 4096
#define _POSIX_CHILD_MAX 25
#define _POSIX_DELAYTIMER_MAX 32
#define _POSIX_HOST_NAME_MAX 255
#define _POSIX_LINK_MAX 8
#define _POSIX_LOGIN_NAME_MAX 9
#define _POSIX_MAX_CANON 255
#define _POSIX_MAX_INPUT 255
#define _POSIX_MQ_OPEN_MAX 8
#define _POSIX_MQ_PRIO_MAX 32
#define _POSIX_NAME_MAX 14
#define _POSIX_NGROUPS_MAX 8
#define _POSIX_OPEN_MAX 20
#define _POSIX_PATH_MAX 256
#define _POSIX_PIPE_BUF 512
#define _POSIX_RE_DUP_MAX 255
#define _POSIX_RTSIG_MAX 8
#define _POSIX_SEM_NSEMS_MAX 256
#define _POSIX_SEM_VALUE_MAX 32767
#define _POSIX_SIGQUEUE_MAX 32
#define _POSIX_SSIZE_MAX 32767
#define _POSIX_SS_REPL_MAX 4
#define _POSIX_STREAM_MAX 8
#define _POSIX_SYMLINK_MAX 255
#define _POSIX_SYMLOOP_MAX 8
#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4
#define _POSIX_THREAD_KEYS_MAX 128
#define _POSIX_THREAD_THREADS_MAX 64
#define _POSIX_TIMER_MAX 32
#define _POSIX_TRACE_EVENT_NAME_MAX 30
#define _POSIX_TRACE_NAME_MAX 8
#define _POSIX_TRACE_SYS_MAX 8
#define _POSIX_TRACE_USER_EVENT_MAX 32
#define _POSIX_TTY_NAME_MAX 9
#define _POSIX_TZNAME_MAX 6
#define _POSIX2_BC_BASE_MAX 99
#define _POSIX2_BC_DIM_MAX 2048
#define _POSIX2_BC_SCALE_MAX 99
#define _POSIX2_BC_STRING_MAX 1000
#define _POSIX2_CHARCLASS_NAME_MAX 14
#define _POSIX2_COLL_WEIGHTS_MAX 2
#define _POSIX2_EXPR_NEST_MAX 32
#define _POSIX2_LINE_MAX 2048
#define _POSIX2_RE_DUP_MAX 255
#endif /* COSMOPOLITAN_LIBC_SYSV_CONSTS__POSIX_H_ */
| 2,421 | 57 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/TIOCFLAG_SOFTCAR.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,TIOCFLAG_SOFTCAR,0,0,0,0,0,0x1,0x1,0
| 99 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/EPOLL_CLOEXEC.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon epoll,EPOLL_CLOEXEC,0x080000,0x080000,0x01000000,0x01000000,0x100000,0x010000,0x010000,0x80000
| 149 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/ELIBACC.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon junkerr,ELIBACC,79,79,-1,-1,-1,-1,-1,-1
| 94 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SOL_IUCV.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon sol,SOL_IUCV,277,277,-1,-1,-1,-1,-1,-1
| 93 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/MCAST_INCLUDE.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon misc,MCAST_INCLUDE,1,1,1,1,1,0,0,0
| 89 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/UL_SETFSIZE.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon misc,UL_SETFSIZE,2,2,2,2,2,0,0,0
| 87 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/PTRACE_TRACEME.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ptrace,PTRACE_TRACEME,0,0,0,0,0,0,-1,-1
| 94 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/IPV6_DROP_MEMBERSHIP.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ipv6,IPV6_DROP_MEMBERSHIP,21,21,0,0,0,0,0,13
| 99 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_pause.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_pause,0x0022,0x0fff,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff
| 118 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/PTRACE_GETFPREGS.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ptrace,PTRACE_GETFPREGS,14,14,-1,-1,35,35,-1,-1
| 102 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/UDP_NO_CHECK6_TX.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon misc,UDP_NO_CHECK6_TX,101,101,0,0,0,0,0,0
| 96 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SOCK_DCCP.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon sock,SOCK_DCCP,6,6,0,0,0,0,0,0
| 85 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_mq_getsetattr.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_mq_getsetattr,0x00f5,0x00b9,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff
| 126 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_timer_create.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_timer_create,0x00de,0x006b,0xfff,0xfff,0xfff,0xfff,0x0eb,0xfff
| 125 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SIOCSIFNETMASK.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon sio,SIOCSIFNETMASK,0x891c,0x891c,0x80206916,0x80206916,0x80206916,0x80206916,0x80206916,0
| 144 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_ioperm.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_ioperm,0x00ad,0x0fff,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff
| 119 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/TABDLY.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,TABDLY,0b0001100000000000,0b0001100000000000,0b000000110000000100,0b000000110000000100,0b000000000000000100,0,0,0b0001100000000000
| 193 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/AF_ATMPVC.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon af,AF_ATMPVC,8,8,0,0,0,0,0,0
| 83 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/TIOCSERGETMULTI.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,TIOCSERGETMULTI,0x545a,0x545a,0,0,0,0,0,0
| 104 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_pwrite.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_pwrite,0x0012,0x0044,0x200009a,0x009a,0x01dc,0x00ae,0x0ae,0xfff
| 126 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/IPV6_RTHDR_TYPE_0.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ipv6,IPV6_RTHDR_TYPE_0,0,0,0,0,0,0,0,0
| 93 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/TIOCPKT_FLUSHWRITE.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon pty,TIOCPKT_FLUSHWRITE,2,2,2,2,2,2,2,2
| 93 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_ioprio_get.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_ioprio_get,0x00fc,0x001f,0xfff,0xfff,0xfff,0xfff,0xfff,0xfff
| 123 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_cpuset_getaffinity.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_cpuset_getaffinity,0xfff,0xfff,0xfff,0xfff,0x01e7,0xfff,0xfff,0xfff
| 130 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/SEEK_DATA.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon splice,SEEK_DATA,3,3,4,4,3,-1,-1,-1
| 90 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/EISCONN.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon errno,EISCONN,106,106,56,56,56,56,56,10056
#ifdef __x86_64__
.yoink kDos2Errno.EISCONN
#endif
| 148 | 6 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/seek.h | #ifndef COSMOPOLITAN_LIBC_SYSV_CONSTS_SEEK_H_
#define COSMOPOLITAN_LIBC_SYSV_CONSTS_SEEK_H_
#include "libc/runtime/symbolic.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern const int SEEK_DATA;
extern const int SEEK_HOLE;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#define SEEK_DATA SYMBOLIC(SEEK_DATA)
#define SEEK_HOLE SYMBOLIC(SEEK_HOLE)
#endif /* COSMOPOLITAN_LIBC_SYSV_CONSTS_SEEK_H_ */
| 441 | 17 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/OLCUC.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon termios,OLCUC,0b0000000000000010,0b0000000000000010,0,0,0,0b0000000000100000,0,0b0000000000000010
| 152 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/MSG_CONFIRM.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon msg,MSG_CONFIRM,0x0800,0x0800,0,0,0,0,0,0
| 96 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/EXFULL.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon junkerr,EXFULL,54,54,-1,-1,-1,-1,-1,-1
| 93 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/AT_EACCESS.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon at,AT_EACCESS,0x0200,0x0200,0x10,0x10,0x0100,1,0x100,0
| 109 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_chown.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_chown,0x005c,0x0fff,0x2000010,0x0010,0x0010,0x0010,0x010,0xfff
| 125 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/IPPROTO_PIM.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon iproto,IPPROTO_PIM,103,103,103,103,103,103,103,-1
| 104 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/__NR_dup.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon nr,__NR_dup,0x0020,0x0017,0x2000029,0x0029,0x0029,0x0029,0x029,0xfff
| 123 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/EPOLLIN.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon epoll,EPOLLIN,1,1,1,1,1,1,1,1
| 84 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/sysv/consts/IP_BIND_ADDRESS_NO_PORT.S | #include "libc/sysv/consts/syscon.internal.h"
.syscon ip,IP_BIND_ADDRESS_NO_PORT,24,24,0,0,0,0,0,0
| 99 | 3 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/tty-graph.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/intrin/newbie.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
#include "libc/vga/vga.internal.h"
/**
* @fileoverview Instantiation of routines for normal console output in
* graphical video modes.
*
* @see libc/vga/tty-graph.inc
*/
#undef KLOGTTY
#define MAYUNROLLLOOPS unrollloops
#define COLOR TtyCanvasColor
#define BPP 32
#define MAPCOLOR TtyGraphMapColor
#define DIRTY TtyGraphDirty
#undef UPDATE
#define RESETDIRTY TtyGraphResetDirty
#define DRAWBITMAP TtyGraphDrawBitmap
#define FILLRECT TtyGraphFillRect
#define MOVERECT TtyGraphMoveRect
#define DRAWCHAR _TtyGraphDrawChar
#define ERASELINECELLS _TtyGraphEraseLineCells
#define MOVELINECELLS _TtyGraphMoveLineCells
#include "libc/vga/tty-graph.inc"
| 3,299 | 55 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/vga-init.greg.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/dce.h"
#include "libc/runtime/pc.internal.h"
#include "libc/str/str.h"
#include "libc/vga/vga.internal.h"
#ifdef __x86_64__
struct Tty _vga_tty;
void _vga_reinit(struct Tty *tty, unsigned short starty, unsigned short startx,
unsigned init_flags) {
struct mman *mm = (struct mman *)(BANE + 0x0500);
unsigned char vid_type = mm->pc_video_type;
unsigned short height = mm->pc_video_height, width = mm->pc_video_width,
stride = mm->pc_video_stride;
uint64_t vid_buf_phy = mm->pc_video_framebuffer;
void *vid_buf = (void *)(BANE + vid_buf_phy);
size_t vid_buf_sz = mm->pc_video_framebuffer_size;
uint8_t chr_ht, chr_wid;
if (vid_type == PC_VIDEO_TEXT) {
unsigned short chr_ht_val = mm->pc_video_char_height;
if (chr_ht_val > 32 || chr_ht_val < 2)
chr_ht = VGA_ASSUME_CHAR_HEIGHT_PX;
else
chr_ht = chr_ht_val;
} else
chr_ht = VGA_ASSUME_CHAR_HEIGHT_PX;
chr_wid = VGA_ASSUME_CHAR_WIDTH_PX;
/* Make sure the video buffer is mapped into virtual memory. */
__invert_memory_area(mm, __get_pml4t(), vid_buf_phy, vid_buf_sz,
PAGE_RW | PAGE_XD);
__ref_pages(mm, __get_pml4t(), vid_buf_phy, vid_buf_sz);
/*
* Initialize our tty structure from the current screen geometry, screen
* contents, cursor position, & character dimensions.
*/
_StartTty(tty, vid_type, height, width, stride, starty, startx, chr_ht,
chr_wid, vid_buf, init_flags);
}
textstartup void _vga_init(void) {
if (IsMetal()) {
struct mman *mm = (struct mman *)(BANE + 0x0500);
unsigned short starty = mm->pc_video_curs_info.y,
startx = mm->pc_video_curs_info.x;
_vga_reinit(&_vga_tty, starty, startx, 0);
}
}
#endif /* __x86_64__ */
| 4,290 | 77 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/readv-vga.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/calls/struct/fd.internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/vga/vga.internal.h"
#ifdef __x86_64__
ssize_t sys_readv_vga(struct Fd *fd, const struct iovec *iov, int iovlen) {
/*
* NOTE: this routine is always non-blocking.
*
* sys_readv_metal() calls here to ask if the VGA teletypewriter has any
* "status reports" escape sequences to send out.
*
* If there are no such status reports, then immediately return ⤠0.
* sysv_readv_metal() will then try to read from an actual input device.
*/
size_t i, redd = 0;
ssize_t res = 0;
for (i = 0; i < iovlen; ++i) {
void *input = iov[i].iov_base;
size_t len = iov[i].iov_len;
res = _TtyRead(&_vga_tty, input, len);
if (res < 0) break;
redd += res;
if (redd != len) return redd;
}
if (!redd) return res;
return redd;
}
#endif /* __x86_64__ */
| 3,448 | 59 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/tty.greg.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/bing.internal.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/directmap.internal.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/runtime/pc.internal.h"
#include "libc/str/str.h"
#include "libc/str/thompike.h"
#include "libc/str/unicode.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/errfuns.h"
#include "libc/vga/vga.internal.h"
#ifdef __x86_64__
/**
* @fileoverview ECMA-48 / VT100 video terminal implementation for bare
* metal VGA.
*
* The code is mainly a pared-down version of the implementation of a
* pseudo-tty in tool/build/lib/pty.c.
*
* @see tool/build/lib/pty.c
*/
#define DEFAULT_FG \
((TtyCanvasColor){.bgr.r = 0xaa, .bgr.g = 0xaa, .bgr.b = 0xaa, .bgr.x = 0xff})
#define DEFAULT_BG \
((TtyCanvasColor){.bgr.r = 0, .bgr.g = 0, .bgr.b = 0, .bgr.x = 0xff})
#define CRTPORT 0x3d4
static void SetYn(struct Tty *tty, unsigned short yn) {
tty->yn = yn;
}
static void SetXn(struct Tty *tty, unsigned short xn) {
tty->xn = xn;
}
static void SetYp(struct Tty *tty, unsigned short yp) {
tty->yp = yp;
}
static void SetXp(struct Tty *tty, unsigned short xp) {
tty->xp = xp;
}
static void SetXsFb(struct Tty *tty, unsigned short xsfb) {
tty->xsfb = xsfb;
}
static bool SetWcs(struct Tty *tty, unsigned init_flags) {
#ifdef VGA_USE_WCS
struct DirectMap dm;
if (!(init_flags & kTtyAllocWcs)) return false;
dm = sys_mmap_metal(NULL, Yn(tty) * Xn(tty) * sizeof(wchar_t),
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1,
0);
if (dm.addr == (void *)-1) {
tty->wcs = NULL;
return false;
}
tty->wcs = dm.addr;
return true;
#else
return false;
#endif
}
static size_t Yn(struct Tty *tty) {
return tty->yn;
}
static size_t Xn(struct Tty *tty) {
return tty->xn;
}
static wchar_t *Wcs(struct Tty *tty) {
#ifdef VGA_USE_WCS
return tty->wcs;
#else
return NULL;
#endif
}
static void TtyNoopUpdate(struct Tty *);
static void TtyTextDrawChar(struct Tty *, size_t, size_t, wchar_t);
static void TtyTextEraseLineCells(struct Tty *, size_t, size_t, size_t);
static void TtyTextMoveLineCells(struct Tty *, size_t, size_t, size_t, size_t,
size_t);
static void TtySetType(struct Tty *tty, unsigned char type,
unsigned init_flags) {
tty->type = type;
if ((init_flags & kTtyKlog) == 0) {
switch (type) {
case PC_VIDEO_BGR565:
tty->update = _TtyBgr565Update;
goto graphics_mode;
case PC_VIDEO_BGR555:
tty->update = _TtyBgr555Update;
goto graphics_mode;
case PC_VIDEO_BGRX8888:
tty->update = _TtyBgrxUpdate;
goto graphics_mode;
case PC_VIDEO_RGBX8888:
tty->update = _TtyRgbxUpdate;
graphics_mode:
tty->drawchar = _TtyGraphDrawChar;
tty->eraselinecells = _TtyGraphEraseLineCells;
tty->movelinecells = _TtyGraphMoveLineCells;
break;
default:
tty->update = TtyNoopUpdate;
tty->drawchar = TtyTextDrawChar;
tty->eraselinecells = TtyTextEraseLineCells;
tty->movelinecells = TtyTextMoveLineCells;
}
} else {
switch (type) {
case PC_VIDEO_BGR565:
case PC_VIDEO_BGR555:
tty->update = _TtyKlog16Update;
tty->drawchar = _TtyKlog16DrawChar;
tty->eraselinecells = _TtyKlog16EraseLineCells;
tty->movelinecells = _TtyKlog16MoveLineCells;
break;
case PC_VIDEO_BGRX8888:
case PC_VIDEO_RGBX8888:
tty->update = _TtyKlog32Update;
tty->drawchar = _TtyKlog32DrawChar;
tty->eraselinecells = _TtyKlog32EraseLineCells;
tty->movelinecells = _TtyKlog32MoveLineCells;
break;
default:
tty->update = TtyNoopUpdate;
tty->drawchar = TtyTextDrawChar;
tty->eraselinecells = TtyTextEraseLineCells;
tty->movelinecells = TtyTextMoveLineCells;
}
}
}
void _StartTty(struct Tty *tty, unsigned char type, unsigned short yp,
unsigned short xp, unsigned short xsfb, unsigned short starty,
unsigned short startx, unsigned char yc, unsigned char xc,
void *fb, unsigned init_flags) {
unsigned short yn, xn, xs = xp * sizeof(TtyCanvasColor);
struct DirectMap dm;
memset(tty, 0, sizeof(struct Tty));
SetYp(tty, yp);
SetXp(tty, xp);
SetXsFb(tty, xsfb);
if (type == PC_VIDEO_TEXT) {
yn = yp;
xn = xp;
tty->canvas = fb;
} else {
yn = yp / yc;
xn = xp / xc;
if ((init_flags & kTtyKlog) != 0) {
tty->canvas = fb;
xs = xsfb;
} else {
dm = sys_mmap_metal(NULL, (size_t)yp * xs, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (dm.addr == (void *)-1) {
/*
* We are a bit low on memory. Try to go on anyway, & initialize
* our tty as an emergency console.
*/
init_flags |= kTtyKlog;
tty->canvas = fb;
xs = xsfb;
} else
tty->canvas = dm.addr;
}
}
SetYn(tty, yn);
SetXn(tty, xn);
tty->yc = yc;
tty->xc = xc;
tty->fb = fb;
if (starty >= yn) starty = yn - 1;
if (startx >= xn) startx = xn - 1;
tty->y = starty;
tty->x = startx;
if ((init_flags & kTtyKlog) != 0) init_flags &= ~kTtyAllocWcs;
tty->xs = xs;
TtySetType(tty, type, init_flags);
if (SetWcs(tty, init_flags)) {
wchar_t *wcs = Wcs(tty);
size_t n = (size_t)yn * xn, i;
if (type == PC_VIDEO_TEXT) {
struct VgaTextCharCell *ccs = fb;
for (i = 0; i < n; ++i) wcs[i] = bing(ccs[i].ch, 0);
} else
wmemset(wcs, L' ', n);
}
_TtyResetOutputMode(tty);
}
static wchar_t *GetXlatAscii(void) {
unsigned i;
static bool once;
static wchar_t xlat[128];
if (!once) {
for (i = 0; i < 128; ++i) {
xlat[i] = i;
}
once = true;
}
return xlat;
}
static wchar_t *GetXlatLineDrawing(void) {
unsigned i;
static bool once;
static wchar_t xlat[128];
if (!once) {
for (i = 0; i < 128; ++i) {
if (0x5F <= i && i <= 0x7E) {
xlat[i] = u" ââââââ°±â¤ââââââ¼âºâ»ââ¼â½ââ¤â´â¬ââ¤â¥Ïâ £·"[i - 0x5F];
} else {
xlat[i] = i;
}
}
once = true;
}
return xlat;
}
static wchar_t *GetXlatItalic(void) {
/* Unimplemented. Simply output normal non-italicized characters for now. */
return GetXlatAscii();
}
static wchar_t *GetXlatBoldItalic(void) {
/*
* Unimplemented. Simply output high-intensity non-italicized characters
* for now.
*/
return GetXlatAscii();
}
static wchar_t *GetXlatBoldFraktur(void) {
/* Unimplemented. */
return GetXlatAscii();
}
static wchar_t *GetXlatFraktur(void) {
/* Unimplemented. */
return GetXlatAscii();
}
static wchar_t *GetXlatDoubleWidth(void) {
unsigned i;
static bool once;
static wchar_t xlat[128];
if (!once) {
for (i = 0; i < ARRAYLEN(xlat); ++i) {
if ('!' <= i && i <= '~') {
xlat[i] = -(i - '!' + L'ï¼');
} else {
xlat[i] = i;
}
}
once = true;
}
return xlat;
}
static wchar_t *GetXlatSgr(struct Tty *tty) {
switch (!!(tty->pr & kTtyFraktur) << 2 | !!(tty->pr & kTtyItalic) << 1 |
!!(tty->pr & kTtyBold) << 0) {
case 0b100:
case 0b110:
return GetXlatFraktur();
case 0b101:
case 0b111:
return GetXlatBoldFraktur();
case 0b011:
return GetXlatBoldItalic();
case 0b010:
return GetXlatItalic();
default:
return GetXlatAscii();
}
}
static void TtySetXlat(struct Tty *tty, wchar_t *xlat) {
tty->xlat = xlat;
tty->pr &= ~(kTtyItalic | kTtyFraktur);
}
static void TtySetCodepage(struct Tty *tty, char id) {
unsigned i;
switch (id) {
default:
case 'B':
TtySetXlat(tty, GetXlatAscii());
break;
case '0':
TtySetXlat(tty, GetXlatLineDrawing());
break;
}
}
/**
* Map the given direct color value to one of the 16 basic foreground colors
* or one of the 16 background colors.
*
* @see drivers/tty/vt/vt.c in Linux 5.9.14 source code
*/
static uint8_t TtyGetTextColor(TtyCanvasColor color) {
uint8_t r = color.bgr.r, g = color.bgr.g, b = color.bgr.b;
uint8_t hue = 0, max = MAX(MAX(r, g), b);
if (r > max / 2) hue |= 4;
if (g > max / 2) hue |= 2;
if (b > max / 2) hue |= 1;
if (hue == 7 && max <= 0x55)
hue = 8;
else if (max > 0xaa)
hue |= 8;
return hue;
}
/**
* Map the currently active foreground & background colors & terminal
* configuration to a VGA text character attribute byte.
*
* @see VGA_USE_BLINK macro (libc/vga/vga.internal.h)
* @see drivers/tty/vt/vt.c in Linux 5.9.14 source code
*/
static uint8_t TtyGetTextAttr(struct Tty *tty) {
uint8_t fg = TtyGetTextColor(tty->fg), bg = TtyGetTextColor(tty->bg);
uint8_t attr;
if ((tty->pr & kTtyFlip) == 0)
attr = fg | bg << 4;
else
attr = bg | fg << 4;
#ifdef VGA_USE_BLINK
/*
* If blinking is enabled, we can only have the 8 dark background color
* codes (0 to 7). Simply map any bright background color (8 to 15) to
* its corresponding dark color, & call it a day. This is a bit more
* simplistic than what Linux does, but should be enough.
*/
attr &= ~0x80;
if ((tty->pr & kTtyBlink) != 0) attr |= 0x80;
#endif
if ((tty->pr & kTtyBold) != 0) attr |= 0x08;
return attr;
}
static void TtyNoopUpdate(struct Tty *tty) {
}
static void TtyTextDrawChar(struct Tty *tty, size_t y, size_t x, wchar_t wc) {
uint8_t attr = TtyGetTextAttr(tty);
struct VgaTextCharCell *ccs = (struct VgaTextCharCell *)tty->canvas;
size_t i = tty->y * Xn(tty) + tty->x;
int c = unbing(wc);
if (c == -1) c = 0xFE;
ccs[i] = (struct VgaTextCharCell){c, attr};
}
static void TtyTextEraseLineCells(struct Tty *tty, size_t dsty, size_t dstx,
size_t n) {
uint8_t attr = TtyGetTextAttr(tty);
struct VgaTextCharCell *ccs = (struct VgaTextCharCell *)tty->canvas;
size_t dst = dsty * Xn(tty) + dstx, i;
for (i = 0; i < n; ++i) ccs[dst + i] = (struct VgaTextCharCell){' ', attr};
}
void _TtyEraseLineCells(struct Tty *tty, size_t dsty, size_t dstx, size_t n) {
tty->eraselinecells(tty, dsty, dstx, n);
if (Wcs(tty)) {
size_t i = dsty * Xn(tty) + dstx;
wmemset(Wcs(tty) + i, L' ', n);
}
}
void _TtyEraseLines(struct Tty *tty, size_t dsty, size_t n) {
size_t xn = Xn(tty), y;
y = dsty;
while (n-- != 0) {
_TtyEraseLineCells(tty, y, 0, xn);
++y;
}
}
static void TtyTextMoveLineCells(struct Tty *tty, size_t dsty, size_t dstx,
size_t srcy, size_t srcx, size_t n) {
size_t xn = Xn(tty);
size_t dst = dsty * xn + dstx, src = srcy * xn + srcx;
struct VgaTextCharCell *ccs = (struct VgaTextCharCell *)tty->canvas;
memmove(ccs + dst, ccs + src, n * sizeof(struct VgaTextCharCell));
}
void _TtyMoveLineCells(struct Tty *tty, size_t dsty, size_t dstx, size_t srcy,
size_t srcx, size_t n) {
size_t xn = Xn(tty);
size_t dst = dsty * xn + dstx, src = srcy * xn + srcx;
tty->movelinecells(tty, dsty, dstx, srcy, srcx, n);
if (Wcs(tty)) wmemmove(Wcs(tty) + dst, Wcs(tty) + src, n);
}
void _TtyMoveLines(struct Tty *tty, size_t dsty, size_t srcy, size_t n) {
size_t xn = Xn(tty);
if (dsty < srcy) {
while (n-- != 0) {
_TtyMoveLineCells(tty, dsty, 0, srcy, 0, xn);
++dsty;
++srcy;
}
} else if (dsty > srcy) {
while (n-- != 0) _TtyMoveLineCells(tty, dsty + n, 0, srcy + n, 0, xn);
}
}
void _TtyResetOutputMode(struct Tty *tty) {
tty->updy1 = tty->updx1 = tty->updy2 = tty->updx2 = 0;
tty->pr = 0;
tty->fg = DEFAULT_FG;
tty->bg = DEFAULT_BG;
tty->u8 = 0;
tty->n8 = 0;
tty->conf = 0;
tty->savey = 0;
tty->savex = 0;
tty->state = 0;
tty->esc.i = 0;
tty->input.i = 0;
tty->xlat = GetXlatAscii();
}
void _TtyFullReset(struct Tty *tty) {
_TtyResetOutputMode(tty);
tty->y = 0;
tty->x = 0;
_TtyEraseLines(tty, 0, Yn(tty));
}
void _TtySetY(struct Tty *tty, unsigned short y) {
tty->conf &= ~kTtyRedzone;
tty->y = MAX(0, MIN(Yn(tty) - 1, y));
}
void _TtySetX(struct Tty *tty, unsigned short x) {
tty->conf &= ~kTtyRedzone;
tty->x = MAX(0, MIN(Xn(tty) - 1, x));
}
static void TtyScroll(struct Tty *tty) {
_TtyMoveLines(tty, 0, 1, Yn(tty) - 1);
_TtyEraseLines(tty, Yn(tty) - 1, 1);
}
static void TtyReverse(struct Tty *tty) {
_TtyMoveLines(tty, 1, 0, Yn(tty) - 1);
_TtyEraseLines(tty, 0, 1);
}
static void TtyIndex(struct Tty *tty) {
if (tty->y < Yn(tty) - 1) {
++tty->y;
} else {
TtyScroll(tty);
}
}
static void TtyReverseIndex(struct Tty *tty) {
if (tty->y) {
--tty->y;
} else {
TtyReverse(tty);
}
}
static void TtyCarriageReturn(struct Tty *tty) {
_TtySetX(tty, 0);
}
static void TtyNewline(struct Tty *tty) {
TtyIndex(tty);
if (!(tty->conf & kTtyNoopost)) {
TtyCarriageReturn(tty);
}
}
static void TtyAdvance(struct Tty *tty) {
tty->conf &= ~kTtyRedzone;
tty->x = 0;
if (tty->y < Yn(tty) - 1) {
++tty->y;
} else {
TtyScroll(tty);
}
}
static void TtyWriteGlyph(struct Tty *tty, wint_t wc, int w) {
if (w < 1) wc = L' ', w = 1;
if ((tty->conf & kTtyRedzone) || tty->x + w > Xn(tty)) {
TtyAdvance(tty);
}
tty->drawchar(tty, tty->y, tty->x, wc);
if (Wcs(tty)) Wcs(tty)[tty->y * Xn(tty) + tty->x] = wc;
if ((tty->x += w) >= Xn(tty)) {
tty->x = Xn(tty) - 1;
tty->conf |= kTtyRedzone;
}
}
static void TtyWriteTab(struct Tty *tty) {
unsigned x, x2;
if (tty->conf & kTtyRedzone) {
TtyAdvance(tty);
}
x2 = MIN(Xn(tty), ROUNDUP(tty->x + 1, 8));
for (x = tty->x; x < x2; ++x) {
tty->eraselinecells(tty, tty->y, x, 1);
}
if (Wcs(tty)) {
for (x = tty->x; x < x2; ++x) {
Wcs(tty)[tty->y * Xn(tty) + x] = L' ';
}
}
if (x2 < Xn(tty)) {
tty->x = x2;
} else {
tty->x = Xn(tty) - 1;
tty->conf |= kTtyRedzone;
}
}
int TtyAtoi(const char *s, const char **e) {
int i;
for (i = 0; isdigit(*s); ++s) i *= 10, i += *s - '0';
if (e) *e = s;
return i;
}
static int TtyGetMoveParam(struct Tty *tty) {
int x = TtyAtoi(tty->esc.s, NULL);
if (x < 1) x = 1;
return x;
}
static void TtySetCursorPosition(struct Tty *tty) {
int row, col;
const char *s = tty->esc.s;
row = max(1, TtyAtoi(s, &s));
if (*s == ';') ++s;
col = max(1, TtyAtoi(s, &s));
_TtySetY(tty, row - 1);
_TtySetX(tty, col - 1);
}
static void TtySetCursorRow(struct Tty *tty) {
_TtySetY(tty, TtyGetMoveParam(tty) - 1);
}
static void TtySetCursorColumn(struct Tty *tty) {
_TtySetX(tty, TtyGetMoveParam(tty) - 1);
}
static void TtyMoveCursor(struct Tty *tty, int dy, int dx) {
int n = TtyGetMoveParam(tty);
_TtySetY(tty, tty->y + dy * n);
_TtySetX(tty, tty->x + dx * n);
}
static void TtyScrollUp(struct Tty *tty) {
int n = TtyGetMoveParam(tty);
while (n--) TtyScroll(tty);
}
static void TtyScrollDown(struct Tty *tty) {
int n = TtyGetMoveParam(tty);
while (n--) TtyReverse(tty);
}
static void TtySetCursorStatus(struct Tty *tty, bool status) {
if (status) {
tty->conf &= ~kTtyNocursor;
} else {
tty->conf |= kTtyNocursor;
}
}
static void TtySetMode(struct Tty *tty, bool status) {
const char *p = tty->esc.s;
switch (*p++) {
case '?':
while (isdigit(*p)) {
switch (TtyAtoi(p, &p)) {
case 25:
TtySetCursorStatus(tty, status);
break;
default:
break;
}
if (*p == ';') {
++p;
}
}
break;
default:
break;
}
}
static void TtySaveCursorPosition(struct Tty *tty) {
tty->savey = tty->y;
tty->savex = tty->x;
}
static void TtyRestoreCursorPosition(struct Tty *tty) {
_TtySetY(tty, tty->savey);
_TtySetX(tty, tty->savex);
}
static void TtyEraseDisplay(struct Tty *tty) {
switch (TtyAtoi(tty->esc.s, NULL)) {
case 0:
_TtyEraseLineCells(tty, tty->y, tty->x, Xn(tty) - tty->x);
_TtyEraseLines(tty, tty->y + 1, Yn(tty) - tty->y - 1);
break;
case 1:
_TtyEraseLines(tty, 0, tty->y);
_TtyEraseLineCells(tty, tty->y, 0, tty->x);
break;
case 2:
case 3:
_TtyEraseLines(tty, 0, Yn(tty));
break;
default:
break;
}
}
static void TtyEraseLine(struct Tty *tty) {
switch (TtyAtoi(tty->esc.s, NULL)) {
case 0:
_TtyEraseLineCells(tty, tty->y, tty->x, Xn(tty) - tty->x);
break;
case 1:
_TtyEraseLineCells(tty, tty->y, 0, tty->x);
break;
case 2:
_TtyEraseLines(tty, tty->y, 1);
break;
default:
break;
}
}
static void TtyEraseCells(struct Tty *tty) {
int yn, xn, yi, xi, n, left;
yn = Yn(tty);
xn = Xn(tty);
yi = tty->y;
xi = tty->x;
left = min(max(TtyAtoi(tty->esc.s, NULL), 1), yn * xn - (yi * xn + xi));
while (left) {
if (left >= xn - xi) {
_TtyEraseLineCells(tty, yi, xi, xn - xi);
left -= xn - xi;
++yi;
xi = 0;
} else {
_TtyEraseLineCells(tty, yi, xi, left);
left = 0;
}
}
}
static int TtyArg1(struct Tty *tty) {
return max(1, TtyAtoi(tty->esc.s, NULL));
}
static void TtyInsertCells(struct Tty *tty) {
int n = min(Xn(tty) - tty->x, TtyArg1(tty));
_TtyMoveLineCells(tty, tty->y, tty->x + n, tty->y, tty->x,
Xn(tty) - (tty->x + n));
_TtyEraseLineCells(tty, tty->y, tty->x, n);
}
static void TtyInsertLines(struct Tty *tty) {
int n = min(Yn(tty) - tty->y, TtyArg1(tty));
_TtyMoveLines(tty, tty->y + n, tty->y, Yn(tty) - tty->y - n);
_TtyEraseLines(tty, tty->y, n);
}
static void TtyDeleteCells(struct Tty *tty) {
int n = min(Xn(tty) - tty->x, TtyArg1(tty));
_TtyMoveLineCells(tty, tty->y, tty->x, tty->y, tty->x + n,
Xn(tty) - (tty->x + n));
_TtyEraseLineCells(tty, tty->y, tty->x, n);
}
static void TtyDeleteLines(struct Tty *tty) {
int n = min(Yn(tty) - tty->y, TtyArg1(tty));
_TtyMoveLines(tty, tty->y, tty->y + n, Yn(tty) - tty->y - n);
_TtyEraseLines(tty, tty->y + n, n);
}
static void TtyReportDeviceStatus(struct Tty *tty) {
static const char report[] = "\e[0n";
_TtyWriteInput(tty, report, strlen(report));
}
static void TtyReportPreferredVtType(struct Tty *tty) {
static const char report[] = "\e[?1;0c";
_TtyWriteInput(tty, report, strlen(report));
}
static void TtyReportPreferredVtIdentity(struct Tty *tty) {
static const char report[] = "\e/Z";
_TtyWriteInput(tty, report, strlen(report));
}
static void TtyBell(struct Tty *tty) {
tty->conf |= kTtyBell;
}
static void TtyLed(struct Tty *tty) {
switch (TtyAtoi(tty->esc.s, NULL)) {
case 0:
tty->conf &= ~kTtyLed1;
tty->conf &= ~kTtyLed2;
tty->conf &= ~kTtyLed3;
tty->conf &= ~kTtyLed4;
break;
case 1:
tty->conf |= kTtyLed1;
break;
case 2:
tty->conf |= kTtyLed2;
break;
case 3:
tty->conf |= kTtyLed3;
break;
case 4:
tty->conf |= kTtyLed4;
break;
default:
break;
}
}
static void TtyReportCursorPosition(struct Tty *tty) {
char *p;
char buf[2 + 10 + 1 + 10 + 1];
p = buf;
*p++ = '\e';
*p++ = '[';
p = FormatInt32(p, (tty->y + 1) & 0x7fff);
*p++ = ';';
p = FormatInt32(p, (tty->x + 1) & 0x7fff);
*p++ = 'R';
_TtyWriteInput(tty, buf, p - buf);
}
static void TtyCsiN(struct Tty *tty) {
switch (TtyAtoi(tty->esc.s, NULL)) {
case 5:
TtyReportDeviceStatus(tty);
break;
case 6:
TtyReportCursorPosition(tty);
break;
default:
break;
}
}
/** Create a direct color pixel value. */
static TtyCanvasColor TtyMapTrueColor(uint8_t r, uint8_t g, uint8_t b) {
return (TtyCanvasColor){.bgr.r = r, .bgr.g = g, .bgr.b = b, .bgr.x = 0xff};
}
/** Map the given 256-color code to a direct color. */
static TtyCanvasColor TtyMapXtermColor(uint8_t color) {
uint8_t r, g, b;
if (color < 8) {
r = (color & 1) ? 0xaa : 0;
g = (color & 2) ? 0xaa : 0;
b = (color & 4) ? 0xaa : 0;
} else if (color < 16) {
r = (color & 1) ? 0xff : 0x55;
g = (color & 2) ? 0xff : 0x55;
b = (color & 4) ? 0xff : 0x55;
} else if (color < 232) {
color -= 16;
b = color % 6 * 0x55 / 2;
color /= 6;
g = color % 6 * 0x55 / 2;
color /= 6;
r = color * 0x55 / 2;
} else
r = g = b = (unsigned)color * 10 - 2312;
return TtyMapTrueColor(r, g, b);
}
/** Map the given ECMA-48 / VT100 SGR color code to a direct color. */
static TtyCanvasColor TtyMapEcma48Color(uint8_t color) {
return TtyMapXtermColor(color % 16);
}
static void TtySelectGraphicsRendition(struct Tty *tty) {
char *p, c;
unsigned x;
uint8_t code[4];
enum {
kSgr,
kSgrFg = 010,
kSgrFgTrue = 012,
kSgrFgXterm = 015,
kSgrBg = 020,
kSgrBgTrue = 022,
kSgrBgXterm = 025,
} t;
x = 0;
t = kSgr;
p = tty->esc.s;
bzero(code, sizeof(code));
for (;;) {
c = *p++;
switch (c) {
case '\0':
return;
case '0' ... '9':
x *= 10;
x += c - '0';
break;
case ';':
case 'm':
code[code[3]] = x;
x = 0;
switch (t) {
case kSgr:
switch (code[0]) {
case 38:
t = kSgrFg;
break;
case 48:
t = kSgrBg;
break;
case 0:
tty->pr = 0;
tty->fg = DEFAULT_FG;
tty->bg = DEFAULT_BG;
tty->xlat = GetXlatSgr(tty);
break;
case 1:
tty->pr |= kTtyBold;
tty->xlat = GetXlatSgr(tty);
break;
case 2:
tty->pr |= kTtyFaint;
break;
case 3:
tty->pr |= kTtyItalic;
tty->xlat = GetXlatSgr(tty);
break;
case 4:
tty->pr |= kTtyUnder;
break;
case 5:
tty->pr |= kTtyBlink;
break;
case 7:
tty->pr |= kTtyFlip;
break;
case 8:
tty->pr |= kTtyConceal;
break;
case 9:
tty->pr |= kTtyStrike;
break;
case 20:
tty->pr |= kTtyFraktur;
tty->xlat = GetXlatSgr(tty);
break;
case 21:
tty->pr |= kTtyUnder | kTtyDunder;
break;
case 22:
tty->pr &= ~(kTtyFaint | kTtyBold);
tty->xlat = GetXlatSgr(tty);
break;
case 23:
tty->pr &= ~kTtyItalic;
tty->xlat = GetXlatSgr(tty);
break;
case 24:
tty->pr &= ~(kTtyUnder | kTtyDunder);
break;
case 25:
tty->pr &= ~kTtyBlink;
break;
case 27:
tty->pr &= ~kTtyFlip;
break;
case 28:
tty->pr &= ~kTtyConceal;
break;
case 29:
tty->pr &= ~kTtyStrike;
break;
case 39:
tty->fg = DEFAULT_FG;
tty->pr &= ~kTtyFg;
break;
case 49:
tty->bg = DEFAULT_BG;
tty->pr &= ~kTtyBg;
break;
case 90 ... 97:
code[0] -= 90 - 30;
code[0] += 8;
/* fallthrough */
case 30 ... 37:
tty->fg = TtyMapEcma48Color(code[0] - 30);
tty->pr |= kTtyFg;
tty->pr &= ~kTtyTrue;
break;
case 100 ... 107:
code[0] -= 100 - 40;
code[0] += 8;
/* fallthrough */
case 40 ... 47:
tty->bg = TtyMapEcma48Color(code[0] - 40);
tty->pr |= kTtyBg;
tty->pr &= ~kTtyTrue;
break;
default:
break;
}
break;
case kSgrFg:
case kSgrBg:
switch (code[0]) {
case 2:
case 5:
t += code[0];
break;
default:
t = kSgr;
break;
}
break;
case kSgrFgTrue:
if (++code[3] == 3) {
code[3] = 0;
t = kSgr;
tty->fg = TtyMapTrueColor(code[0], code[1], code[2]);
tty->pr |= kTtyFg;
tty->pr |= kTtyTrue;
}
break;
case kSgrBgTrue:
if (++code[3] == 3) {
code[3] = 0;
t = kSgr;
tty->bg = TtyMapTrueColor(code[0], code[1], code[2]);
tty->pr |= kTtyBg;
tty->pr |= kTtyTrue;
}
break;
case kSgrFgXterm:
t = kSgr;
tty->fg = TtyMapXtermColor(code[0]);
tty->pr |= kTtyFg;
tty->pr &= ~kTtyTrue;
break;
case kSgrBgXterm:
t = kSgr;
tty->bg = TtyMapXtermColor(code[0]);
tty->pr |= kTtyBg;
tty->pr &= ~kTtyTrue;
break;
default:
abort();
}
break;
default:
break;
}
}
}
static void TtyCsi(struct Tty *tty) {
switch (tty->esc.s[tty->esc.i - 1]) {
case 'f':
case 'H':
TtySetCursorPosition(tty);
break;
case 'G':
TtySetCursorColumn(tty);
break;
case 'd':
TtySetCursorRow(tty);
break;
case 'F':
tty->x = 0;
/* fallthrough */
case 'A':
TtyMoveCursor(tty, -1, +0);
break;
case 'E':
tty->x = 0;
/* fallthrough */
case 'B':
TtyMoveCursor(tty, +1, +0);
break;
case 'C':
TtyMoveCursor(tty, +0, +1);
break;
case 'D':
TtyMoveCursor(tty, +0, -1);
break;
case 'S':
TtyScrollUp(tty);
break;
case 'T':
TtyScrollDown(tty);
break;
case '@':
TtyInsertCells(tty);
break;
case 'P':
TtyDeleteCells(tty);
break;
case 'L':
TtyInsertLines(tty);
break;
case 'M':
TtyDeleteLines(tty);
break;
case 'J':
TtyEraseDisplay(tty);
break;
case 'K':
TtyEraseLine(tty);
break;
case 'X':
TtyEraseCells(tty);
break;
case 's':
TtySaveCursorPosition(tty);
break;
case 'u':
TtyRestoreCursorPosition(tty);
break;
case 'n':
TtyCsiN(tty);
break;
case 'm':
TtySelectGraphicsRendition(tty);
break;
case 'h':
TtySetMode(tty, true);
break;
case 'l':
TtySetMode(tty, false);
break;
case 'c':
TtyReportPreferredVtType(tty);
break;
case 'q':
TtyLed(tty);
break;
default:
break;
}
}
static void TtyScreenAlignmentDisplay(struct Tty *tty) {
size_t yn = Yn(tty), xn = Xn(tty), y, x;
for (y = 0; y < yn; ++y)
for (x = 0; x < xn; ++x) tty->drawchar(tty, y, x, 'E');
if (Wcs(tty)) wmemset(Wcs(tty), L'E', yn * xn);
}
static void TtyEscHash(struct Tty *tty) {
switch (tty->esc.s[1]) {
case '5':
TtySetXlat(tty, GetXlatAscii());
break;
case '6':
TtySetXlat(tty, GetXlatDoubleWidth());
break;
case '8':
TtyScreenAlignmentDisplay(tty);
break;
default:
break;
}
}
static void TtyEsc(struct Tty *tty) {
switch (tty->esc.s[0]) {
case 'c':
_TtyFullReset(tty);
break;
case '7':
TtySaveCursorPosition(tty);
break;
case '8':
TtyRestoreCursorPosition(tty);
break;
case 'E':
tty->x = 0;
case 'D':
TtyIndex(tty);
break;
case 'M':
TtyReverseIndex(tty);
break;
case 'Z':
TtyReportPreferredVtIdentity(tty);
break;
case '(':
TtySetCodepage(tty, tty->esc.s[1]);
break;
case '#':
TtyEscHash(tty);
break;
default:
break;
}
}
static void TtyCntrl(struct Tty *tty, int c01) {
switch (c01) {
case '\a':
TtyBell(tty);
break;
case 0x85:
case '\f':
case '\v':
case '\n':
TtyNewline(tty);
break;
case '\r':
TtyCarriageReturn(tty);
break;
case '\e':
tty->state = kTtyEsc;
tty->esc.i = 0;
break;
case '\t':
TtyWriteTab(tty);
break;
case 0x7F:
case '\b':
tty->x = MAX(0, tty->x - 1);
break;
case 0x84:
TtyIndex(tty);
break;
case 0x8D:
TtyReverseIndex(tty);
break;
case 0x9B:
tty->state = kTtyCsi;
break;
default:
break;
}
}
static void TtyEscAppend(struct Tty *tty, char c) {
tty->esc.i = MIN(tty->esc.i + 1, ARRAYLEN(tty->esc.s) - 1);
tty->esc.s[tty->esc.i - 1] = c;
tty->esc.s[tty->esc.i - 0] = 0;
}
static void TtyUpdate(struct Tty *tty) {
if (tty->type == PC_VIDEO_TEXT) {
unsigned char start = tty->yc - 2, end = tty->yc - 1;
unsigned short pos = tty->y * Xn(tty) + tty->x;
if ((tty->conf & kTtyNocursor)) start |= 1 << 5;
outb(CRTPORT, 0x0A);
outb(CRTPORT + 1, start);
outb(CRTPORT, 0x0B);
outb(CRTPORT + 1, end);
outb(CRTPORT, 0x0E);
outb(CRTPORT + 1, (unsigned char)(pos >> 8));
outb(CRTPORT, 0x0F);
outb(CRTPORT + 1, (unsigned char)pos);
} else
tty->update(tty);
}
ssize_t _TtyWrite(struct Tty *tty, const void *data, size_t n) {
int i;
wchar_t wc;
const uint8_t *p;
for (p = data, i = 0; i < n; ++i) {
switch (tty->state) {
case kTtyAscii:
if (0x00 <= p[i] && p[i] <= 0x7F) {
if (0x20 <= p[i] && p[i] <= 0x7E) {
if ((wc = tty->xlat[p[i]]) >= 0) {
TtyWriteGlyph(tty, wc, 1);
} else {
TtyWriteGlyph(tty, -wc, 2);
}
} else {
TtyCntrl(tty, p[i]);
}
} else if (!ThomPikeCont(p[i])) {
tty->state = kTtyUtf8;
tty->u8 = ThomPikeByte(p[i]);
tty->n8 = ThomPikeLen(p[i]) - 1;
}
break;
case kTtyUtf8:
if (ThomPikeCont(p[i])) {
tty->u8 = ThomPikeMerge(tty->u8, p[i]);
if (--tty->n8) break;
}
wc = tty->u8;
if ((0x00 <= wc && wc <= 0x1F) || (0x7F <= wc && wc <= 0x9F)) {
TtyCntrl(tty, wc);
} else {
TtyWriteGlyph(tty, wc, wcwidth(wc));
}
tty->state = kTtyAscii;
tty->u8 = 0;
--i;
break;
case kTtyEsc:
if (p[i] == '[') {
tty->state = kTtyCsi;
} else if (0x30 <= p[i] && p[i] <= 0x7E) {
TtyEscAppend(tty, p[i]);
TtyEsc(tty);
tty->state = kTtyAscii;
} else if (0x20 <= p[i] && p[i] <= 0x2F) {
TtyEscAppend(tty, p[i]);
} else {
tty->state = kTtyAscii;
}
break;
case kTtyCsi:
TtyEscAppend(tty, p[i]);
switch (p[i]) {
case ':':
case ';':
case '<':
case '=':
case '>':
case '?':
case '0' ... '9':
break;
case '`':
case '~':
case '^':
case '@':
case '[':
case ']':
case '{':
case '}':
case '_':
case '|':
case '\\':
case 'A' ... 'Z':
case 'a' ... 'z':
TtyCsi(tty);
tty->state = kTtyAscii;
break;
default:
tty->state = kTtyAscii;
continue;
}
break;
default:
unreachable;
}
}
TtyUpdate(tty);
return n;
}
ssize_t _TtyWriteInput(struct Tty *tty, const void *data, size_t n) {
int c;
bool cr;
char *p;
const char *q;
size_t i, j, m;
q = data;
p = tty->input.p;
i = tty->input.i;
cr = i && p[i - 1] == '\r';
for (j = 0; j < n && i < sizeof tty->input.p; ++j) {
c = q[j] & 255;
if (c == '\r') {
cr = true;
} else if (cr) {
if (c != '\n') {
p[i++] = '\n';
}
cr = false;
}
p[i++] = c;
}
if (cr && i < sizeof tty->input.p) {
p[i++] = '\n';
}
#ifdef VGA_PERSNICKETY_STATUS
if (!(tty->conf & kTtyNoecho)) {
_TtyWrite(tty, p + tty->input.i, i - tty->input.i);
}
#endif
tty->input.i = i;
return n;
}
ssize_t _TtyRead(struct Tty *tty, void *buf, size_t size) {
char *p;
size_t n;
n = MIN(size, tty->input.i);
#ifdef VGA_PERSNICKETY_STATUS
if (!(tty->conf & kTtyNocanon)) {
if ((p = memchr(tty->input.p, '\n', n))) {
n = MIN(n, tty->input.p - p + 1);
} else {
n = 0;
}
}
#endif
memcpy(buf, tty->input.p, n);
memcpy(tty->input.p, tty->input.p + n, tty->input.i - n);
tty->input.i -= n;
return n;
}
#endif /* __x86_64__ */
| 34,880 | 1,363 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/tty-graph.inc | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/intrin/newbie.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
#include "libc/vga/vga.internal.h"
/**
* @fileoverview Template for routines to support output in graphical video
* modes for bare metal VGA.
*
* If KLOGTTY is undefined, this file expands to code that writes to a
* separate off-screen canvas buffer â which should be allocated beforehand
* â before drawing to the actual video memory.
*
* If KLOGTTY is defined, this file instead expands to code that can
* implement an emergency console. The graphics routines will directly write
* to video memory. This may result in slower output, but will work even if
* we cannot allocate an off-screen canvas for whatever reason.
*
* @see libc/vga/tty.greg.c
* @see libc/vga/tty-graph.c
* @see libc/vga/tty-klog.greg.c
*/
#ifndef KLOGTTY
static COLOR MAPCOLOR(struct Tty *tty, TtyCanvasColor ic) {
return ic;
}
static void DIRTY(struct Tty *tty, size_t gy1, size_t gx1,
size_t gy2, size_t gx2) {
if (tty->updy1 > gy1) tty->updy1 = gy1;
if (tty->updx1 > gx1) tty->updx1 = gx1;
if (tty->updy2 < gy2) tty->updy2 = gy2;
if (tty->updx2 < gx2) tty->updx2 = gx2;
}
static void RESETDIRTY(struct Tty *tty) {
tty->updy1 = tty->updx1 = tty->updy2 = tty->updx2 = 0;
}
unrollloops void _TtyBgr565Update(struct Tty *tty) {
size_t gy1 = tty->updy1, gy2 = tty->updy2,
gx1 = tty->updx1, gx2 = tty->updx2,
xsfb = tty->xsfb, xs = tty->xs;
if (gy1 < gy2 && gx1 < gx2) {
size_t yleft = gy2 - gy1, xleft;
char *cplotter = tty->fb + gy1 * xsfb + gx1 * sizeof(TtyBgr565Color);
const char *creader = tty->canvas + gy1 * xs
+ gx1 * sizeof(TtyCanvasColor);
RESETDIRTY(tty);
while (yleft-- != 0) {
TtyBgr565Color *plotter = (TtyBgr565Color *)cplotter;
const TtyCanvasColor *reader = (const TtyCanvasColor *)creader;
TtyCanvasColor c;
xleft = gx2 - gx1;
while (xleft-- != 0) {
uint16_t w;
c.w = reader->w;
++reader;
w = htole16(c.bgr.b >> 3 | c.bgr.g >> 2 << 5 | c.bgr.r >> 3 << 11);
*plotter++ = (TtyBgr565Color){w};
}
cplotter += xsfb;
creader += xs;
}
}
}
unrollloops void _TtyBgr555Update(struct Tty *tty) {
size_t gy1 = tty->updy1, gy2 = tty->updy2,
gx1 = tty->updx1, gx2 = tty->updx2,
xsfb = tty->xsfb, xs = tty->xs;
if (gy1 < gy2 && gx1 < gx2) {
size_t yleft = gy2 - gy1, xleft;
char *cplotter = tty->fb + gy1 * xsfb + gx1 * sizeof(TtyBgr555Color);
const char *creader = tty->canvas + gy1 * xs
+ gx1 * sizeof(TtyCanvasColor);
RESETDIRTY(tty);
while (yleft-- != 0) {
TtyBgr555Color *plotter = (TtyBgr555Color *)cplotter;
const TtyCanvasColor *reader = (const TtyCanvasColor *)creader;
TtyCanvasColor c;
xleft = gx2 - gx1;
while (xleft-- != 0) {
uint16_t w;
c.w = reader->w;
++reader;
w = htole16(c.bgr.b >> 3 | c.bgr.g >> 3 << 5 | c.bgr.r >> 3 << 10);
*plotter++ = (TtyBgr555Color){w};
}
cplotter += xsfb;
creader += xs;
}
}
}
unrollloops void _TtyBgrxUpdate(struct Tty *tty) {
size_t gy1 = tty->updy1, gy2 = tty->updy2,
gx1 = tty->updx1, gx2 = tty->updx2,
xsfb = tty->xsfb, xs = tty->xs;
if (gy1 < gy2 && gx1 < gx2) {
size_t yleft = gy2 - gy1, xleft;
char *cplotter = tty->fb + gy1 * xsfb + gx1 * sizeof(TtyBgrxColor);
const char *creader = tty->canvas + gy1 * xs
+ gx1 * sizeof(TtyCanvasColor);
RESETDIRTY(tty);
while (yleft-- != 0) {
TtyBgrxColor *plotter = (TtyBgrxColor *)cplotter;
const TtyCanvasColor *reader = (const TtyCanvasColor *)creader;
xleft = gx2 - gx1;
while (xleft-- != 0) {
TtyCanvasColor c = *reader++;
c.bgr.x = 0xff;
*plotter++ = c;
}
cplotter += xsfb;
creader += xs;
}
}
}
unrollloops void _TtyRgbxUpdate(struct Tty *tty) {
size_t gy1 = tty->updy1, gy2 = tty->updy2,
gx1 = tty->updx1, gx2 = tty->updx2,
xsfb = tty->xsfb, xs = tty->xs;
if (gy1 < gy2 && gx1 < gx2) {
size_t yleft = gy2 - gy1, xleft;
char *cplotter = tty->fb + gy1 * xsfb + gx1 * sizeof(TtyRgbxColor);
const char *creader = tty->canvas + gy1 * xs
+ gx1 * sizeof(TtyCanvasColor);
RESETDIRTY(tty);
while (yleft-- != 0) {
TtyRgbxColor *plotter = (TtyRgbxColor *)cplotter;
const TtyCanvasColor *reader = (const TtyCanvasColor *)creader;
TtyCanvasColor ic;
TtyRgbxColor oc;
xleft = gx2 - gx1;
while (xleft-- != 0) {
ic.w = reader->w;
++reader;
oc = (TtyRgbxColor){.rgb.r = ic.bgr.r, .rgb.g = ic.bgr.g,
.rgb.b = ic.bgr.b, .rgb.x = 0xff};
plotter->w = oc.w;
++plotter;
}
cplotter += xsfb;
creader += xs;
}
}
}
#else /* KLOGTTY */
static COLOR MAPCOLOR(struct Tty *tty, TtyCanvasColor ic) {
#if BPP == 16
if (tty->type == PC_VIDEO_BGR565)
return htole16(ic.bgr.b >> 3 | ic.bgr.g >> 2 << 5 | ic.bgr.r >> 3 << 11);
else
return htole16(ic.bgr.b >> 3 | ic.bgr.g >> 3 << 5 | ic.bgr.r >> 3 << 10);
#else
if (tty->type == PC_VIDEO_BGRX8888)
return ic.w;
else {
TtyRgbxColor oc = (TtyRgbxColor){.rgb.r = ic.bgr.r, .rgb.g = ic.bgr.g,
.rgb.b = ic.bgr.b, .rgb.x = 0xff};
return oc.w;
}
#endif
}
static void DIRTY(struct Tty *tty, size_t gy1, size_t gx1,
size_t gy2, size_t gx2) {
}
static void RESETDIRTY(struct Tty *tty) {
}
void UPDATE(struct Tty *tty) {
}
#endif /* KLOGTTY */
static void DRAWBITMAP(struct Tty *tty, size_t gy, size_t gx,
COLOR fg, COLOR bg, const uint8_t *bitmap,
size_t bm_ht, size_t bm_wid) {
size_t xs = tty->xs;
char *cplotter = tty->canvas + gy * xs + gx * sizeof(COLOR);
size_t yleft = bm_ht, xleft;
while (yleft-- != 0) {
COLOR *plotter = (COLOR *)cplotter;
xleft = bm_wid;
while (xleft >= 8) {
uint8_t bits = *bitmap++;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
xleft -= 8;
}
if (xleft) {
uint8_t bits = *bitmap++;
switch (xleft) {
default:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
/* fall through */
case 6:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
/* fall through */
case 5:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
/* fall through */
case 4:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
/* fall through */
case 3:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
/* fall through */
case 2:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
/* fall through */
case 1:
*plotter++ = __builtin_add_overflow(bits, bits, &bits) ? fg : bg;
}
}
cplotter += xs;
}
DIRTY(tty, gy, gx, gy + bm_ht, gx + bm_wid);
}
static MAYUNROLLLOOPS void FILLRECT(struct Tty *tty, size_t gy, size_t gx,
size_t fill_ht, size_t fill_wid,
COLOR bg) {
size_t xs = tty->xs;
char *cplotter = tty->canvas + gy * xs + gx * sizeof(COLOR);
size_t yleft = fill_ht, xleft;
while (yleft-- != 0) {
COLOR *plotter = (COLOR *)cplotter;
size_t i;
for (i = 0; i < fill_wid; ++i)
*plotter++ = bg;
cplotter += xs;
}
DIRTY(tty, gy, gx, gy + fill_ht, gx + fill_wid);
}
static void MOVERECT(struct Tty *tty, size_t dgy, size_t dgx,
size_t sgy, size_t sgx, size_t ht, size_t wid) {
size_t xs = tty->xs, xm = wid * sizeof(COLOR);
char *canvas = tty->canvas;
DIRTY(tty, dgy, dgx, dgy + ht, dgx + wid);
if (dgy < sgy) {
while (ht-- != 0) {
memmove(canvas + dgy * xs + dgx * sizeof(COLOR),
canvas + sgy * xs + sgx * sizeof(COLOR), xm);
++dgy;
++sgy;
}
} else if (dgy > sgy) {
while (ht-- != 0)
memmove(canvas + (dgy + ht) * xs + dgx * sizeof(COLOR),
canvas + (sgy + ht) * xs + sgx * sizeof(COLOR), xm);
}
}
void DRAWCHAR(struct Tty *tty, size_t y, size_t x, wchar_t wc) {
/* TODO: allow configuring a different font later. */
const uint8_t *glyph;
const size_t glyph_ht = ARRAYLEN(_vga_font_default_direct[0]);
COLOR fg = MAPCOLOR(tty, tty->fg), bg = MAPCOLOR(tty, tty->bg);
if ((tty->pr & kTtyFlip) != 0)
fg = bg, bg = MAPCOLOR(tty, tty->fg);
if (wc < L' ' || wc >= L' ' + ARRAYLEN(_vga_font_default_direct))
glyph = _vga_font_default_direct[0];
else
glyph = _vga_font_default_direct[wc - L' '];
if (glyph_ht >= VGA_ASSUME_CHAR_HEIGHT_PX)
DRAWBITMAP(tty, y * tty->yc, x * tty->xc, fg, bg, glyph,
VGA_ASSUME_CHAR_HEIGHT_PX, 8);
else {
/*
* Glyph is not tall enough. Draw it out, then pad the bottom of the
* character cell with the background color.
*/
DRAWBITMAP(tty, y * tty->yc, x * tty->xc, fg, bg, glyph, glyph_ht, 8);
FILLRECT(tty, y * tty->yc + glyph_ht, x * tty->xc,
VGA_ASSUME_CHAR_HEIGHT_PX - glyph_ht, 8, bg);
}
}
void ERASELINECELLS(struct Tty *tty, size_t y, size_t x, size_t n) {
size_t yc = tty->yc, xc = tty->xc;
FILLRECT(tty, y * yc, x * xc, yc, n * xc, MAPCOLOR(tty, tty->bg));
}
void MOVELINECELLS(struct Tty *tty, size_t dsty, size_t dstx,
size_t srcy, size_t srcx, size_t n) {
size_t yc = tty->yc, xc = tty->xc;
MOVERECT(tty, dsty * yc, dstx * xc, srcy * yc, srcx * xc, yc, n * xc);
}
| 12,915 | 331 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/vga.internal.h | #ifndef COSMOPOLITAN_LIBC_VGA_VGA_INTERNAL_H_
#define COSMOPOLITAN_LIBC_VGA_VGA_INTERNAL_H_
#include "libc/runtime/mman.internal.h"
/** Preferred width of the video screen, in character units. */
#define VGA_PREFER_TTY_HEIGHT 30
/** Preferred width of the video screen, in character units. */
#define VGA_PREFER_TTY_WIDTH 80
/** Assumed height of each character in pixels, in graphics modes. */
#define VGA_ASSUME_CHAR_HEIGHT_PX 16
/** Assumed width of each character in pixels, in graphics modes. */
#define VGA_ASSUME_CHAR_WIDTH_PX 8
/*
* VGA_USE_WCS, VGA_USE_BLINK, & VGA_PERSNICKETY_STATUS are configuration
* knobs which can potentially be used to tweak the features to be compiled
* into our VGA teletypewriter support.
*/
/**
* If VGA_USE_WCS is defined, the tty code can maintain an array of the
* Unicode characters "underlying" the 8-bit (or 9-bit) characters that are
* actually displayed on the text screen. This Unicode character
* information is not used in Cosmopolitan as of now (Sep 2022). A Linux
* mailing list post suggests that such information could be of use to
* applications such as screen readers.
*
* If VGA_USE_WCS is undefined, then the Unicode character information is
* not maintained, & we arrange for the relevant logic to be optimized away
* by the compiler.
*
* @see lkml.kernel.org/lkml/[email protected]/T/
*/
#undef VGA_USE_WCS
/**
* The VGA hardware can be configured â via the IBM BIOS, or via port I/O â
* to either support blinking characters, or support the use of bright
* background colors, but not both. There is a hardware setting that
* controls whether the attribute byte for each plotted character is
* interpreted as
*
* foregroundâââââ
* foreground intensityâââ â
* backgroundâ â â
* blinkingâ â â
* âââ´ââââ´â
* 76543210
*
* or as
*
* foregroundâââââ
* foreground intensityâââ â
* backgroundâ â â
* background intensityâ â â
* âââ´ââââ´â
* 76543210
*
* (NOTE: QEMU 6.2.0 does not emulate the VGA blinking feature. However,
* VirtualBox 6.1 does.)
*
* If VGA_USE_BLINK is defined, our VGA code will use the former mode, &
* will support blinking characters. If VGA_USE_BLINK is undefined, the
* VGA code will instead implement bright background colors.
*
* @see Ralf Brown's Interrupt List, int 0x10, ax = 0x1003
* (https://www.delorie.com/djgpp/doc/rbinter/id/22/1.html)
*/
#undef VGA_USE_BLINK
/**
* If VGA_PERSNICKETY_STATUS is defined, then when deciding how to return
* status response codes (e.g. "\e[0n"), the tty code will pay attention to
* the terminal's termios mode (TODO). If undefined, the tty code will
* simply return any response strings immediately, & will not echo them â
* per the common use case.
*/
#undef VGA_PERSNICKETY_STATUS
/* Flags which are passed to _StartTty(). */
#define kTtyAllocWcs \
0x01 /* allocate Unicode character array \
(if VGA_USE_WCS also defined) */
#define kTtyKlog \
0x02 /* the system might be in an abnormal \
state, & we are setting up the tty \
to show system messages */
/**
* Flags for Tty::pr. These govern properties of individual character cells.
*/
#define kTtyFg 0x0001
#define kTtyBg 0x0002
#define kTtyBold 0x0004
#define kTtyFlip 0x0008
#define kTtyFaint 0x0010
#define kTtyUnder 0x0020
#define kTtyDunder 0x0040
#define kTtyTrue 0x0080
#define kTtyBlink 0x0100
#define kTtyItalic 0x0200
#define kTtyFraktur 0x0400
#define kTtyStrike 0x0800
#define kTtyConceal 0x1000
/**
* Flags for Tty::conf. These govern the current state of the teletypewriter
* as a whole.
*/
#define kTtyBell 0x001
#define kTtyRedzone 0x002
#define kTtyNocursor 0x004
#define kTtyBlinkcursor 0x008
#define kTtyNocanon 0x010
#define kTtyNoecho 0x020
#define kTtyNoopost 0x040
#define kTtyLed1 0x080
#define kTtyLed2 0x100
#define kTtyLed3 0x200
#define kTtyLed4 0x400
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#include "libc/calls/struct/fd.internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
COSMOPOLITAN_C_START_
struct VgaTextCharCell {
uint8_t ch, attr;
};
typedef union {
uint32_t w;
struct {
uint8_t b, g, r, x;
} bgr;
} TtyBgrxColor;
typedef union {
uint32_t w;
struct {
uint8_t r, g, b, x;
} rgb;
} TtyRgbxColor;
typedef union {
uint16_t w;
} TtyBgr565Color;
typedef union {
uint16_t w;
} TtyBgr555Color;
typedef TtyBgrxColor TtyCanvasColor;
struct Tty;
struct Tty {
/**
* Cursor position. (y, x) = (0, 0) means the cursor is on the top left
* character cell of the terminal.
*/
unsigned short y, x;
/** Height and width of terminal, in character units. */
unsigned short yn, xn;
/** Height and width of terminal, in pixels (if in graphics video mode). */
unsigned short yp, xp;
/**
* Number of bytes (NOTE) occupied by each row of pixels, including any
* invisible "pixels", in the video frame buffer.
*/
unsigned short xsfb;
/**
* Number of bytes (NOTE) occupied by each row of pixels, including any
* invisible "pixels", in the canvas.
*/
unsigned short xs;
/** Type of video buffer (from mman::pc_video_type). */
unsigned char type;
uint32_t u8;
uint32_t n8;
uint32_t pr;
TtyCanvasColor fg, bg;
/**
* Height of each character in pixels. In text modes, this is used in
* setting the shape of the hardware cursor.
*/
uint8_t yc;
/**
* Width of each character in pixels. This is mostly useful only in
* graphics modes.
*/
uint8_t xc;
uint32_t conf;
unsigned short savey, savex;
/** Actual video frame buffer as provided by the video card. */
char *fb;
/**
* Canvas to draw into. In text modes, this is simply the frame buffer
* itself. In graphics modes, this should be separate from the frame
* buffer, & possibly allocated from main memory; we must arrange to
* update the frame buffer from the canvas every now & then.
*
* During normal operation, the canvas's pixel format is given by
* _TtyCanvasType(), & may be different from the frame buffer's.
*/
char *canvas;
/**
* Which portions of the canvas have been updated & should later be drawn
* to screen with Tty::update().
*/
unsigned short updy1, updx1, updy2, updx2;
#ifdef VGA_USE_WCS
wchar_t *wcs;
#endif
wchar_t *xlat;
enum TtyState {
kTtyAscii,
kTtyUtf8,
kTtyEsc,
kTtyCsi,
} state;
struct TtyEsc {
unsigned i;
char s[64];
} esc;
struct TtyInput {
size_t i;
char p[256];
} input;
void (*update)(struct Tty *);
void (*drawchar)(struct Tty *, size_t, size_t, wchar_t);
void (*eraselinecells)(struct Tty *, size_t, size_t, size_t);
void (*movelinecells)(struct Tty *, size_t, size_t, size_t, size_t, size_t);
};
forceinline unsigned char _TtyCanvasType(struct Tty *tty) {
return tty->type == PC_VIDEO_TEXT ? PC_VIDEO_TEXT : PC_VIDEO_BGRX8888;
}
forceinline unsigned short _TtyGetY(struct Tty *tty) {
return tty->y;
}
forceinline unsigned short _TtyGetX(struct Tty *tty) {
return tty->x;
}
/* Routines that implement normal graphical console output. */
void _TtyBgrxUpdate(struct Tty *);
void _TtyRgbxUpdate(struct Tty *);
void _TtyBgr565Update(struct Tty *);
void _TtyBgr555Update(struct Tty *);
void _TtyGraphDrawChar(struct Tty *, size_t, size_t, wchar_t);
void _TtyGraphEraseLineCells(struct Tty *, size_t, size_t, size_t);
void _TtyGraphMoveLineCells(struct Tty *, size_t, size_t, size_t, size_t,
size_t);
/*
* Routines that implement emergency or system console output in graphical
* video modes.
*/
void _TtyKlog16Update(struct Tty *);
void _TtyKlog16DrawChar(struct Tty *, size_t, size_t, wchar_t);
void _TtyKlog16EraseLineCells(struct Tty *, size_t, size_t, size_t);
void _TtyKlog16MoveLineCells(struct Tty *, size_t, size_t, size_t, size_t,
size_t);
void _TtyKlog32Update(struct Tty *);
void _TtyKlog32DrawChar(struct Tty *, size_t, size_t, wchar_t);
void _TtyKlog32EraseLineCells(struct Tty *, size_t, size_t, size_t);
void _TtyKlog32MoveLineCells(struct Tty *, size_t, size_t, size_t, size_t,
size_t);
/* High-level teletypewriter routines. */
void _StartTty(struct Tty *, unsigned char, unsigned short, unsigned short,
unsigned short, unsigned short, unsigned short, unsigned char,
unsigned char, void *, unsigned);
ssize_t _TtyRead(struct Tty *, void *, size_t);
ssize_t _TtyWrite(struct Tty *, const void *, size_t);
ssize_t _TtyWriteInput(struct Tty *, const void *, size_t);
void _TtyResetOutputMode(struct Tty *);
void _TtyFullReset(struct Tty *);
void _TtyMoveLineCells(struct Tty *, size_t, size_t, size_t, size_t, size_t);
void _TtyMoveLines(struct Tty *, size_t, size_t, size_t);
void _TtyEraseLineCells(struct Tty *, size_t, size_t, size_t);
void _TtyEraseLines(struct Tty *, size_t, size_t);
void _TtySetY(struct Tty *, unsigned short);
void _TtySetX(struct Tty *, unsigned short);
extern const uint8_t _vga_font_default_direct[95][13];
extern struct Tty _vga_tty;
void _vga_reinit(struct Tty *, unsigned short, unsigned short, unsigned);
void _klog_vga(const char *, size_t);
ssize_t sys_readv_vga(struct Fd *, const struct iovec *, int);
ssize_t sys_writev_vga(struct Fd *, const struct iovec *, int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_VGA_VGA_INTERNAL_H_ */
| 9,788 | 299 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/rlinit-vesa.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "ape/relocations.h"
#include "libc/macros.internal.h"
#include "libc/runtime/mman.internal.h"
#include "libc/vga/vga.internal.h"
#define VGA_PREFER_GRAPH_HEIGHT \
(VGA_PREFER_TTY_HEIGHT * VGA_ASSUME_CHAR_HEIGHT_PX)
#define VGA_PREFER_GRAPH_WIDTH \
(VGA_PREFER_TTY_WIDTH * VGA_ASSUME_CHAR_WIDTH_PX)
#define MAX_VESA_MODES_TO_TRACK 64
// Mode information data structure, used internally.
.set "mi::type",0
.set "mi::bpp",1
.set "mi::width",2
.set "mi::height",4
.set "mi::mode_num",6
.set "mi::stride",8
.set "mi::fb",10
.set "mi::sizeof",14
// Routine to activate additional VESA functionality if the user holds
// down a magic key, when booting from bare metal. Currently this just
// dumps a list of all usable VESA VBE video modes on the console.
//
// TODO: allow user to select a video mode and switch to it
// TODO: implement character drawing in graphics modes
//
// @return CF = 0 if we decided to set a new video mode, CF = 1 otherwise
.real
.code16
_rlinit_vesa:
push %es
pushw $0
testb $0b00000011,0x0417 # read keyboard shift state (as
jnz .doit # given by BIOS's IRQ 1); if Shift
# key pressed, activate code below
push %si # display brief message on magic key
mov $REAL(str.inform),%si
call .puts
pop %si
mov $0x8300,%ax # wait for the magic key for a short
mov $(1000000>>16),%cx # period of time...
mov $(1000000&0xffff),%dx
push %ss
pop %es
mov %sp,%bx
int $0x15
jc .done
.wait: pause
testb $0b00000011,0x0417
jnz .doit2
cmpb $0,%es:(%bx)
jz .wait
call .done_inform
stc
.done: pop %ax
pop %es
ret
.doit2: mov $0x8301,%ax # we got the magic key; cancel the
int $0x15 # wait timer, & erase message
call .done_inform
.doit: pop %ax # we got the magic key; do stuff
pop %es
// fall through
.endfn _rlinit_vesa,globl,hidden
.do_vesa_rlinit:
push %eax
push %bx
push %edx
push %bp
sub $2+MAX_VESA_MODES_TO_TRACK*"mi::sizeof",%sp
mov %sp,%bp
call .gather_vesa_modes # gather list of VESA modes
jc 8f
call .get_default_mode # choose a default mode to use
jc 6f
call .choose_mode # allow user to select different mode
movw %bx,%bp
call .snooze
mov "mi::mode_num"(%bp),%bx
mov $0x4f02,%ax
int $0x10
cmp $0x004f,%ax
jnz 9f
mov "mi::type"(%bp),%al
.set mm,0x0500
mov %al,mm+"struct mman::pc_video_type"
mov "mi::width"(%bp),%ax
mov %ax,mm+"struct mman::pc_video_width"
movzwl "mi::height"(%bp),%edx
mov %dx,mm+"struct mman::pc_video_height"
mov "mi::fb"(%bp),%eax
mov %eax,mm+"struct mman::pc_video_framebuffer"
movzwl "mi::stride"(%bp),%eax
mov %ax,mm+"struct mman::pc_video_stride"
imul %edx,%eax
mov %eax,mm+"struct mman::pc_video_framebuffer_size"
xor %eax,%eax
mov %eax,mm+"struct mman::pc_video_framebuffer"+4
mov %eax,mm+"struct mman::pc_video_framebuffer_size"+4
clc
5: lahf
add $2+MAX_VESA_MODES_TO_TRACK*"mi::sizeof",%sp
sahf
pop %bp
pop %edx
pop %bx
pop %eax
ret
6: mov $REAL(str.no_mode),%si
7: call .puts
8: call .snooze
stc
jmp 5b
9: mov $REAL(str.bad_mode),%si
jmp 7b
.endfn .do_vesa_rlinit
// Clear the informational message on the magic key.
.done_inform:
mov $0x0a00|' ',%ax
mov $7,%bx
mov $str.inform.end-str.inform-1,%cx
int $0x10
ret
// Preliminarily choose a "default" VESA screen mode from a list of
// gathered screen modes.
//
// @return %bx is such that %ss:(%bx) = internal struc. for default mode
// @return CF = 1 if no available modes, CF = 0 otherwise
.get_default_mode:
push %eax
push %cx
push %edx
push %edi
push %bp
mov (%bp),%cx
jcxz 8f
inc %bp
inc %bp
or $-1,%esi # %esi = best fit screen size + penalty
# (to be recalculated later)
mov %bp,%bx # %bx = pointer to best info. struct.
1: mov "mi::type"(%bp),%ax # load mode type & bits per pixel
ror %ah # convert bpp into penalty value:
movzbl %ah,%edi # fewer bpp are better, but prefer
# 16 bpp over 15 bpp
cmp $PC_VIDEO_TEXT,%al # handle text modes specially
jz 9f
movzwl "mi::width"(%bp),%eax
jz 9f
cmp $VGA_PREFER_GRAPH_WIDTH,%ax # calculate screen size
jb 3f
movzwl "mi::height"(%bp),%edx
cmp $VGA_PREFER_GRAPH_HEIGHT,%dx
jb 3f
imul %edx,%eax
2: add %edi,%eax
jc 3f
cmp %esi,%eax
jnb 3f
mov %eax,%esi
mov %bp,%bx
3: add $"mi::sizeof",%bp
loop 1b
clc
7: pop %bp
pop %edi
pop %edx
pop %cx
pop %eax
ret
8: stc
jmp 7b
9: imul $VGA_ASSUME_CHAR_WIDTH_PX,%eax
cmp $VGA_PREFER_GRAPH_WIDTH,%eax
jb 2b
movzwl "mi::height"(%bp),%edx
imul $VGA_ASSUME_CHAR_HEIGHT_PX,%edx
cmp $VGA_PREFER_GRAPH_HEIGHT,%edx
jb 3b
imul %edx,%eax
jo 3b
mov $1<<31,%edi # severely disparage text modes
jmp 2b
.endfn .get_default_mode
// Allow the user to choose a VESA screen mode to use.
//
// @return %bx is such that ss:(%bx) = internal struc. for chosen mode
.choose_mode:
push %ax
push %si
push %di
mov (%bp),%di
imul $"mi::sizeof",%di
lea 2(%bp,%di),%di
1: mov $REAL(str.choose_mode),%si
call .puts
mov %ss:("mi::mode_num")(%bx),%ax
call .putx
mov %ss:("mi::width")(%bx),%ax
call .putd
mov %ss:("mi::height")(%bx),%ax
call .putd
mov %ss:("mi::bpp")(%bx),%al
call .putdb
mov $0,%ah
int $0x16
#define UPSCN 0x48
#define DNSCN 0x50
#define CRSCN 0x1c
cmp $DNSCN,%ah
jz 3f
cmp $CRSCN,%ah
jz 4f
cmp $UPSCN,%ah
jnz 1b
lea 2(%bp),%ax # up arrow pressed
cmp %ax,%bx
jz 1b
2: sub $"mi::sizeof",%bx
jmp 1b
3: add $"mi::sizeof",%bx # down arrow pressed
cmp %di,%bx
jnz 1b
jmp 2b
4: call .putnl # Enter pressed
pop %di
pop %si
pop %ax
ret
.endfn .choose_mode
.snooze:
push %ax
push %cx
push %dx
mov $0x86,%ah # do a(nother) short few-second wait
mov $(2000000>>16),%cx
mov $(2000000&0xffff),%dx
int $0x15
pop %dx
pop %cx
pop %ax
ret
.endfn .snooze
// Dump a list of all the VESA VBE video modes that are usable on the
// target machine. Also gather a list of video modes and basic
// information about these modes at %ss:(%bp).
.gather_vesa_modes:
push %ds
push %es
push %si
push %di
push %ss # allocate 0x200 bytes on stack
pop %es # for general VESA information
sub $0x200,%sp
mov $0x200/2,%cx
mov %sp,%di
cld
xor %ax,%ax
rep stosw
mov $0x4f00,%ax # get general VESA information
mov %sp,%di
movl $/*"VBE2"*/0x32454256,%es:(%di)
int $0x10
cmp $0x004f,%ax # if this fails, complain
jnz .fail2
mov $REAL(str.mode_list_start),%si
call .puts # otherwise start iterating through
lds %es:0xe(%di),%si # the returned video mode list
movw $0,(%bp)
cld
.iter1: lodsw
inc %ax
jz .done2
dec %ax
call .munge # process mode number
jc .iter1
.iter2: lodsw
inc %ax
jz .nl
dec %ax
call .munge # process another mode number
jc .iter2
.iter3: lodsw
inc %ax
jz .nl
dec %ax
call .munge # process another mode number
jc .iter3
call .putnl
jmp .iter1 # ...and so on
.nl: call .putnl
clc
.done2: add $0x200,%sp # OK, we are finally done
pop %di
pop %si
pop %es
pop %ds
ret
.fail2: mov $REAL(str.no_vesa),%si
call .puts
stc
jmp .done2
.endfn .gather_vesa_modes
// Display information on one video mode number, which should be in %ax.
// If %ax is a mode which we can use, also update the mode information
// buffer at %ss:(%bp). Assume %es = %ss.
//
// @return CF = 0 if video mode is usable, CF = 1 otherwise
.munge: push %ax
push %bx
push %cx
push %si
push %di
or $1<<14,%ax # force frame buffer mode
xchg %ax,%si # remember mode number
sub $0x100,%sp # allocate 0x100 stack bytes for
mov $0x100/2,%cx # information on this mode; clear
mov %sp,%di # the bytes
cld
xor %ax,%ax
rep stosw
mov %si,%cx # get information on one mode
mov $0x4f01,%ax
mov %sp,%di
int $0x10
cmp $0x004f,%ax # if error, skip mode
jnz .fail3
mov %es:(%di),%al
mov %al,%cl
and $0b00001011,%al # also skip if mode is unusable, or
cmp $0b00001011,%al # extra information unavailable, or
jnz .fail3 # is monochrome, or is graphics w/o
mov %cl,%al # linear frame buffer
and $0b10010000,%al
cmp $0b00010000,%al
jz .fail3
call .video_type # check if we know about the video
jc .fail3 # buffer type, & what exact type it is
mov (%bp),%bx # if we are already tracking too
cmp $MAX_VESA_MODES_TO_TRACK,%bx # VESA modes, also skip
jnb .fail3
inc %bx # otherwise start noting down mode
mov %bx,(%bp) # information...
imul $"mi::sizeof",%bx
lea 2-"mi::sizeof"(%ebp,%ebx),%bx
mov %al,%ss:("mi::type")(%bx) # ...starting from frame buffer type
call .putsp # echo and remember mode information
call .putsp
test $0b00010000,%cl # first, echo mode attributes
setnz %al
imul $'G'-'T',%ax,%ax # - 'G': graphics; 'T': text mode
add $'T',%al
call .putc
call .putsp
xchg %ax,%si # then process
mov %ax,%ss:("mi::mode_num")(%bx) # - mode number
call .putx
mov %es:0x12(%di),%ax # - mode width
mov %ax,%ss:("mi::width")(%bx)
call .putd
mov %es:0x14(%di),%ax # - mode height
mov %ax,%ss:("mi::height")(%bx)
call .putd
mov %es:0x19(%di),%al # - bits per pixel
mov %al,%ss:("mi::bpp")(%bx)
call .putdb
mov %es:0x10(%di),%ax # - mode stride
mov %ax,%ss:("mi::stride")(%bx)
testb $0b00010000,%cl
jz .txt
mov %es:0x28(%di),%eax
.fb: mov %eax,%ss:("mi::fb")(%bx) # - frame buffer address
clc
.done3: lea 0x100(%esp),%sp
pop %di
pop %si
pop %cx
pop %bx
pop %ax
ret
.fail3: stc
jmp .done3
.txt: movzwl %es:8(%di),%eax # for text mode, use window A as
shl $4,%eax # frame buffer
jmp .fb
.endfn .munge
// Check if the given video mode information uses a video buffer type
// we know about, and say what type of video buffer it is.
//
// @param %es:(%di) = video mode information from int 0x10, %ax = 0x4f01
// @param %cl = low byte of video mode attributes (= %es:(%di))
// @return %al = video buffer type (for mman::pc_video_type)
// @return CF = 0 if video mode is usable, CF = 1 otherwise
.video_type:
push %bx
push %cx
push %edx
mov $PC_VIDEO_TEXT,%al # if text mode, simply say so
test $0b00010000,%cl
jz .ok4
cmp $6,%es:0x1b(%di) # if graphics mode, check if direct
jnz .fail4 # color; bail out if not
mov %es:0x19(%di),%cl # check actual color fields & bits
mov %es:0x1f(%di),%ax # per pixel, against a list
mov %es:0x21(%di),%edx
mov $REAL(.type_list),%bx
.iter4: cmp %edx,%cs:4(%bx)
jnz .next
cmp %cl,%cs:1(%bx)
jnz .next
cmp %ax,%cs:2(%bx)
jz .found
.next: add $8,%bx
cmp $REAL(.type_list_end),%bx
jnz .iter4
.fail4: stc # unsupported mode; return failure
jmp .done4
.found: mov %cs:(%bx),%al # this mode is supported; return the
.ok4: clc # corresponding type code
.done4: pop %edx
pop %cx
pop %bx
ret
// Output a string via BIOS.
.puts: cld
push %si
0: lodsb
test %al,%al
jz 1f
call .putc
jmp 0b
1: pop %si
ret
.endfn .puts
// Output a 16-bit number in decimal via BIOS.
.putd: push %ax
push %cx
push %dx
push %si
push %ds
push %ss
pop %ds
sub $8,%sp
lea 4(%esp),%si
mov $10,%cx
xor %dx,%dx
div %cx
add $'0'|' '<<8,%dx
mov %dx,(%si)
movb $0,2(%si)
1: mov $' ',%dl
test %ax,%ax
jz 2f
xor %dx,%dx
div %cx
add $'0',%dl
2: dec %si
mov %dl,(%si)
cmp %sp,%si
jnz 1b
call .puts
add $8,%sp
pop %ds
pop %si
pop %dx
pop %cx
pop %ax
ret
.endfn .putd
// Output an 8-bit number in decimal via BIOS.
.putdb: push %ax
mov %al,%ah
cmp $100,%al
jnb 3f
mov $' ',%al
1: call .putc
mov %ah,%al
aam
testb %ah,%ah
jz 5f
add $'0'|'0'<<8,%ax
2: xchg %al,%ah
call .putc
mov %ah,%al
call .putc
pop %ax
ret
3: cmp $200,%al
jnb 4f
sub $100,%ah
mov $'1',%al
jmp 1b
4: sub $200,%ah
mov $'2',%al
jmp 1b
5: add $'0'|' '<<8,%ax
jmp 2b
// Output a number in hexadecimal via BIOS.
.putx: push %ax
push %bx
push %cx
xchg %ax,%bx
mov $'0',%al
call .putc
mov $'x',%al
call .putc
mov $4,%cx
0: rol $4,%bx
mov %bl,%al
and $0b00001111,%al
add $'0',%al
cmp $'9',%al
jna 1f
add $'a'-'9'-1,%al
1: call .putc
loop 0b
pop %cx
pop %bx
pop %ax
.endfn .putx
// fall through
// Output a character via BIOS.
.putsp: mov $' ',%al
.endfn .putsp
// fall through
.putc: push %ax
push %bx
mov $7,%bx
mov $0x0e,%ah
int $0x10
pop %bx
pop %ax
ret
.endfn .putc
.putnl:
mov $'\r',%al
call .putc
mov $'\n',%al
jmp .putc
.endfn .putnl
str.inform:
#define SHGLYPH "\x7f"
.ascii "\rinfo: press ",SHGLYPH,"Shift "
.asciz "to switch video mode\r"
str.inform.end:
.endobj str.inform
str.no_vesa:
.asciz "info: no VESA\r\n"
.endobj str.no_vesa
str.choose_mode:
#define UPGLYPH "\x18"
#define DNGLYPH "\x19"
#define CRGLYPH "\x1b\xd9"
.ascii "\rchoose video mode (",UPGLYPH," ",DNGLYPH," ",CRGLYPH
.asciz "): "
.endobj str.choose_mode
str.no_mode:
.asciz "info: no usable video mode\r\n"
.endobj str.no_mode
str.bad_mode:
.asciz "info: mode switch fail\r\n"
.endobj str.bad_mode
str.mode_list_start:
.ascii "info: VESA video modes:\r\n"
.ascii " mode# X Y bpp"
.ascii " mode# X Y bpp"
.asciz " mode# X Y bpp\r\n"
.endobj str.mode_list_start
.type_list:
// âvalue to use for mman::pc_video_type
// â âbits per pixel
// â â âred field size (in bits)
// â â â âred field position (bits)
// â â â â âgreen field size
// â â â â â âgreen field position
// â â â â â â âblue field size
// â â â â â â â âblue field position
// â â â â â â â â
.byte PC_VIDEO_BGR565, 16, 5,11, 6, 5, 5, 0
.byte PC_VIDEO_BGR555, 15, 5,10, 5, 5, 5, 0
.byte PC_VIDEO_BGR555, 16, 5,10, 5, 5, 5, 0
.byte PC_VIDEO_RGBX8888,32, 8, 0, 8, 8, 8,16
.byte PC_VIDEO_BGRX8888,32, 8,16, 8, 8, 8, 0
.endobj .type_list
.type_list_end:
.previous
| 16,124 | 634 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/writev-vga.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/calls/struct/fd.internal.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/iovec.internal.h"
#include "libc/dce.h"
#include "libc/vga/vga.internal.h"
#ifdef __x86_64__
ssize_t sys_writev_vga(struct Fd *fd, const struct iovec *iov, int iovlen) {
size_t i, wrote = 0;
ssize_t res = 0;
for (i = 0; i < iovlen; ++i) {
void *output = iov[i].iov_base;
size_t len = iov[i].iov_len;
res = _TtyWrite(&_vga_tty, output, len);
if (res < 0) break;
wrote += res;
if (res != len) return wrote;
}
if (!wrote) return res;
return wrote;
}
#endif /* __x86_64__ */
| 3,134 | 51 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/rlinit-init-vga.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/macros.internal.h"
#include "libc/runtime/mman.internal.h"
#include "libc/vga/vga.internal.h"
// Code snippet for initializing the VGA video mode for bare metal.
//
// If a program requests VGA support (by yoinking vga_console),
// and it is started in bare metal mode, then try to ensure that
// the VGA monitor is in a known mode. This is easier to do while
// the program is still running in real mode.
//
// This module also ropes in the sys_writev_vga routine, which
// implements the actual VGA console output under x86-64 long mode.
//
// @see rlinit & .sort.text.real.init.* (ape/ape.S)
// @see ape/ape.lds
// @see sys_writev_vga (libc/vga/writev-vga.c)
.section .sort.text.real.init.2,"ax",@progbits
.code16
call _rlinit_vesa
jnc 9f
mov $0x4f03,%ax # get current video mode via VESA
int $0x10
cmp $0x004f,%ax # is VESA a thing here?
jz 1f
mov $0x0f,%ah # if not, get the video mode via a
int $0x10 # classical BIOS call
cbtw
xchgw %ax,%bx
1: mov $0x0003,%ax # check if we are in a 80 Ã ? Ã 16
cmp %ax,%bx # text mode
jnz 2f
cmpb $25-1,0x0484 # check if number of screen rows
jnz 2f # (BDA.ROWS + 1) is 25; if so, then
mov $0x0500,%ax # just make sure we are on display
# page 0
2: int $0x10 # otherwise, change the video mode
.set mm,0x0500 # note down video mode parameters
movb $PC_VIDEO_TEXT,mm+"struct mman::pc_video_type"
movw $160,mm+"struct mman::pc_video_stride"
movw $80,mm+"struct mman::pc_video_width"
movw $25,mm+"struct mman::pc_video_height"
movl $0xb8000,mm+"struct mman::pc_video_framebuffer"
movl $0x8000,mm+"struct mman::pc_video_framebuffer_size"
xor %eax,%eax
mov %eax,mm+"struct mman::pc_video_framebuffer"+4
mov %eax,mm+"struct mman::pc_video_framebuffer_size"+4
mov $0x1003,%ax # enable/disable VGA text blinking
#ifdef VGA_USE_BLINK
mov $1,%bx
#else
xor %bx,%bx
#endif
int $0x10
9: mov 0x0450,%dx # note down cursor position
movzbw %dh,%ax
mov %ax,mm+"struct mman::pc_video_curs_info"
mov %dl,%al
mov %ax,mm+"struct mman::pc_video_curs_info"+2
mov 0x0486,%ax # ...& character height
mov %ax,mm+"struct mman::pc_video_char_height"
.previous
.code64
.section .rodata,"a",@progbits
vga_console:
.endobj vga_console,globl,hidden
.previous
.init.start 305,_init_vga
push %rdi
push %rsi
call _vga_init
pop %rsi
pop %rdi
.init.end 305,_init_vga
.yoink sys_writev_vga
.yoink sys_readv_vga
| 4,923 | 103 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/vga.mk | #-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-â
#âââvi: set et ft=make ts=8 tw=8 fenc=utf-8 :viââââââââââââââââââââââââ
PKGS += LIBC_VGA
LIBC_VGA_ARTIFACTS += LIBC_VGA_A
LIBC_VGA_A = o/$(MODE)/libc/vga/vga.a
LIBC_VGA_A_FILES := $(wildcard libc/vga/*)
LIBC_VGA_A_HDRS = $(filter %.h,$(LIBC_VGA_A_FILES))
LIBC_VGA_A_SRCS_S = $(filter %.S,$(LIBC_VGA_A_FILES))
LIBC_VGA_A_SRCS_C = $(filter %.c,$(LIBC_VGA_A_FILES))
LIBC_VGA = \
$(LIBC_VGA_A_DEPS) \
$(LIBC_VGA_A)
LIBC_VGA_A_SRCS = \
$(LIBC_VGA_A_SRCS_S) \
$(LIBC_VGA_A_SRCS_C)
LIBC_VGA_A_OBJS = \
$(LIBC_VGA_A_SRCS_S:%.S=o/$(MODE)/%.o) \
$(LIBC_VGA_A_SRCS_C:%.c=o/$(MODE)/%.o)
LIBC_VGA_A_CHECKS = \
$(LIBC_VGA_A).pkg \
$(LIBC_VGA_A_HDRS:%=o/$(MODE)/%.ok)
LIBC_VGA_A_DIRECTDEPS = \
LIBC_NEXGEN32E \
LIBC_SYSV \
LIBC_STR \
LIBC_INTRIN \
LIBC_STUBS \
LIBC_FMT
LIBC_VGA_A_DEPS := \
$(call uniq,$(foreach x,$(LIBC_VGA_A_DIRECTDEPS),$($(x))))
$(LIBC_VGA_A):libc/vga/ \
$(LIBC_VGA_A).pkg \
$(LIBC_VGA_A_OBJS)
$(LIBC_VGA_A).pkg: \
$(LIBC_VGA_A_OBJS) \
$(foreach x,$(LIBC_VGA_A_DIRECTDEPS),$($(x)_A).pkg)
LIBC_VGA_LIBS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)))
LIBC_VGA_SRCS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)_SRCS))
LIBC_VGA_HDRS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)_HDRS))
LIBC_VGA_BINS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)_BINS))
LIBC_VGA_CHECKS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)_CHECKS))
LIBC_VGA_OBJS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)_OBJS))
LIBC_VGA_TESTS = $(foreach x,$(LIBC_VGA_ARTIFACTS),$($(x)_TESTS))
$(LIBC_VGA_OBJS): $(BUILD_FILES) libc/vga/vga.mk
.PHONY: o/$(MODE)/libc/vga
o/$(MODE)/libc/vga: $(LIBC_VGA_CHECKS)
| 1,788 | 59 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/tty-klog.greg.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â This is free and unencumbered software released into the public domain. â
â â
â Anyone is free to copy, modify, publish, use, compile, sell, or â
â distribute this software, either in source code form or as a compiled â
â binary, for any purpose, commercial or non-commercial, and by any â
â means. â
â â
â In jurisdictions that recognize copyright laws, the author or authors â
â of this software dedicate any and all copyright interest in the â
â software to the public domain. We make this dedication for the benefit â
â of the public at large and to the detriment of our heirs and â
â successors. We intend this dedication to be an overt act of â
â relinquishment in perpetuity of all present and future rights to this â
â software under copyright law. â
â â
â 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 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 "libc/intrin/newbie.h"
#include "libc/macros.internal.h"
#include "libc/runtime/mman.internal.h"
#include "libc/str/str.h"
#include "libc/vga/vga.internal.h"
#ifdef __x86_64__
/*
* @fileoverview Instantiation of routines for emergency or system console
* output in graphical video modes.
*
* @see libc/vga/tty-graph.inc
*/
#pragma GCC optimize("s")
#define KLOGTTY
#define MAYUNROLLLOOPS /* do not unroll loops; keep the code small! */
/* Instantiate output routines for 16-bit pixel formats. */
#define COLOR uint16_t
#define BPP 16
#define MAPCOLOR TtyKlog16MapColor
#define DIRTY TtyKlog16Dirty
#define UPDATE _TtyKlog16Update
#define RESETDIRTY TtyKlog16ResetDirty
#define DRAWBITMAP TtyKlog16DrawBitmap
#define FILLRECT TtyKlog16FillRect
#define MOVERECT TtyKlog16MoveRect
#define DRAWCHAR _TtyKlog16DrawChar
#define ERASELINECELLS _TtyKlog16EraseLineCells
#define MOVELINECELLS _TtyKlog16MoveLineCells
#include "libc/vga/tty-graph.inc"
#undef COLOR
#undef BPP
#undef MAPCOLOR
#undef BG
#undef DIRTY
#undef UPDATE
#undef RESETDIRTY
#undef DRAWBITMAP
#undef FILLRECT
#undef MOVERECT
#undef DRAWCHAR
#undef ERASELINECELLS
#undef MOVELINECELLS
/* Instantiate output routines for 32-bit pixel formats. */
#define COLOR uint32_t
#define BPP 32
#define MAPCOLOR TtyKlog32MapColor
#define DIRTY TtyKlog32Dirty
#define UPDATE _TtyKlog32Update
#define RESETDIRTY TtyKlog32ResetDirty
#define DRAWBITMAP TtyKlog32DrawBitmap
#define FILLRECT TtyKlog32FillRect
#define MOVERECT TtyKlog32MoveRect
#define DRAWCHAR _TtyKlog32DrawChar
#define ERASELINECELLS _TtyKlog32EraseLineCells
#define MOVELINECELLS _TtyKlog32MoveLineCells
#include "libc/vga/tty-graph.inc"
static unsigned short klog_y = 0, klog_x = 0;
privileged void _klog_vga(const char *b, size_t n) {
struct Tty tty;
_vga_reinit(&tty, klog_y, klog_x, kTtyKlog);
_TtyWrite(&tty, b, n);
klog_y = _TtyGetY(&tty);
klog_x = _TtyGetX(&tty);
}
#endif /* __x86_64__ */
| 4,601 | 102 | jart/cosmopolitan | false |
cosmopolitan/libc/vga/vga-font-default.c | /* ****** AUTOMATICALLY GENERATED ******
* by bdf2c-in-awk https://gitlab.com/tkchia/bdf2c-in-awk
*
* Command line arguments:
* NONASCII=0 SPARSE=1 COSMO=1 X=_vga_ C=... .../8x13B.bdf
*
* Font information:
* COMMENT "$ucs-fonts: 8x13B.bdf,v 1.28 2002-11-15 18:23:23+00 mgk25 Rel $"
* COMMENT "Send bug reports to Markus Kuhn <http://www.cl.cam.ac.uk/~mgk25/>"
* COPYRIGHT "Public domain font. Share and enjoy."
*
* Extra comments:
* + xorg.freedesktop.org/releases/individual/font/font-misc-misc-1.1.1.tar.bz2
*/
const uint8_t _vga_font_default_direct[95][13] =
{
[0] =
{
/* 32 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[1] =
{
/* 33 */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[2] =
{
/* 34 */
0x00, /* ........ */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[3] =
{
/* 35 */
0x00, /* ........ */
0x00, /* ........ */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0xfe, /* #######. */
0xfe, /* #######. */
0x6c, /* .##.##.. */
0xfe, /* #######. */
0xfe, /* #######. */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x00, /* ........ */
0x00, /* ........ */
},
[4] =
{
/* 36 */
0x00, /* ........ */
0x10, /* ...#.... */
0x7c, /* .#####.. */
0xd6, /* ##.#.##. */
0xd0, /* ##.#.... */
0xf0, /* ####.... */
0x7c, /* .#####.. */
0x1e, /* ...####. */
0x16, /* ...#.##. */
0xd6, /* ##.#.##. */
0x7c, /* .#####.. */
0x10, /* ...#.... */
0x00, /* ........ */
},
[5] =
{
/* 37 */
0x00, /* ........ */
0xe6, /* ###..##. */
0xa6, /* #.#..##. */
0xec, /* ###.##.. */
0x18, /* ...##... */
0x18, /* ...##... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x6e, /* .##.###. */
0xca, /* ##..#.#. */
0xce, /* ##..###. */
0x00, /* ........ */
0x00, /* ........ */
},
[6] =
{
/* 38 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x78, /* .####... */
0xcc, /* ##..##.. */
0xcc, /* ##..##.. */
0x78, /* .####... */
0xce, /* ##..###. */
0xcc, /* ##..##.. */
0x7e, /* .######. */
0x00, /* ........ */
0x00, /* ........ */
},
[7] =
{
/* 39 */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[8] =
{
/* 40 */
0x00, /* ........ */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x00, /* ........ */
},
[9] =
{
/* 41 */
0x00, /* ........ */
0x60, /* .##..... */
0x30, /* ..##.... */
0x18, /* ...##... */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0x00, /* ........ */
},
[10] =
{
/* 42 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x10, /* ...#.... */
0x10, /* ...#.... */
0xfe, /* #######. */
0x38, /* ..###... */
0x38, /* ..###... */
0x6c, /* .##.##.. */
0x44, /* .#...#.. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[11] =
{
/* 43 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x7e, /* .######. */
0x7e, /* .######. */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[12] =
{
/* 44 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x3c, /* ..####.. */
0x1c, /* ...###.. */
0x1c, /* ...###.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x00, /* ........ */
},
[13] =
{
/* 45 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7e, /* .######. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[14] =
{
/* 46 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[15] =
{
/* 47 */
0x00, /* ........ */
0x02, /* ......#. */
0x06, /* .....##. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0x80, /* #....... */
0x00, /* ........ */
0x00, /* ........ */
},
[16] =
{
/* 48 */
0x00, /* ........ */
0x38, /* ..###... */
0x6c, /* .##.##.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x6c, /* .##.##.. */
0x38, /* ..###... */
0x00, /* ........ */
0x00, /* ........ */
},
[17] =
{
/* 49 */
0x00, /* ........ */
0x18, /* ...##... */
0x38, /* ..###... */
0x78, /* .####... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x7e, /* .######. */
0x00, /* ........ */
0x00, /* ........ */
},
[18] =
{
/* 50 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0xc0, /* ##...... */
0xfe, /* #######. */
0x00, /* ........ */
0x00, /* ........ */
},
[19] =
{
/* 51 */
0x00, /* ........ */
0xfe, /* #######. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[20] =
{
/* 52 */
0x00, /* ........ */
0x0c, /* ....##.. */
0x1c, /* ...###.. */
0x3c, /* ..####.. */
0x6c, /* .##.##.. */
0xcc, /* ##..##.. */
0xcc, /* ##..##.. */
0xfe, /* #######. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x00, /* ........ */
0x00, /* ........ */
},
[21] =
{
/* 53 */
0x00, /* ........ */
0xfe, /* #######. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xfc, /* ######.. */
0xe6, /* ###..##. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[22] =
{
/* 54 */
0x00, /* ........ */
0x3c, /* ..####.. */
0x60, /* .##..... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xfc, /* ######.. */
0xe6, /* ###..##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xe6, /* ###..##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[23] =
{
/* 55 */
0x00, /* ........ */
0xfe, /* #######. */
0x06, /* .....##. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x18, /* ...##... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x00, /* ........ */
0x00, /* ........ */
},
[24] =
{
/* 56 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[25] =
{
/* 57 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xce, /* ##..###. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xce, /* ##..###. */
0x7e, /* .######. */
0x06, /* .....##. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x78, /* .####... */
0x00, /* ........ */
0x00, /* ........ */
},
[26] =
{
/* 58 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[27] =
{
/* 59 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x18, /* ...##... */
0x00, /* ........ */
0x3c, /* ..####.. */
0x1c, /* ...###.. */
0x1c, /* ...###.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x00, /* ........ */
},
[28] =
{
/* 60 */
0x00, /* ........ */
0x00, /* ........ */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0x30, /* ..##.... */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x06, /* .....##. */
0x00, /* ........ */
0x00, /* ........ */
},
[29] =
{
/* 61 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7e, /* .######. */
0x00, /* ........ */
0x00, /* ........ */
0x7e, /* .######. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[30] =
{
/* 62 */
0x00, /* ........ */
0x00, /* ........ */
0x60, /* .##..... */
0x30, /* ..##.... */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0x00, /* ........ */
0x00, /* ........ */
},
[31] =
{
/* 63 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[32] =
{
/* 64 */
0x00, /* ........ */
0x00, /* ........ */
0x7c, /* .#####.. */
0xfe, /* #######. */
0xce, /* ##..###. */
0xde, /* ##.####. */
0xd2, /* ##.#..#. */
0xd2, /* ##.#..#. */
0xde, /* ##.####. */
0xe0, /* ###..... */
0x7e, /* .######. */
0x00, /* ........ */
0x00, /* ........ */
},
[33] =
{
/* 65 */
0x00, /* ........ */
0x38, /* ..###... */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xfe, /* #######. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[34] =
{
/* 66 */
0x00, /* ........ */
0xfc, /* ######.. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x7c, /* .#####.. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0xfc, /* ######.. */
0x00, /* ........ */
0x00, /* ........ */
},
[35] =
{
/* 67 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xe6, /* ###..##. */
0xc6, /* ##...##. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc6, /* ##...##. */
0xe6, /* ###..##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[36] =
{
/* 68 */
0x00, /* ........ */
0xfc, /* ######.. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0xfc, /* ######.. */
0x00, /* ........ */
0x00, /* ........ */
},
[37] =
{
/* 69 */
0x00, /* ........ */
0xfe, /* #######. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xf8, /* #####... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xfe, /* #######. */
0x00, /* ........ */
0x00, /* ........ */
},
[38] =
{
/* 70 */
0x00, /* ........ */
0xfe, /* #######. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xf8, /* #####... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0x00, /* ........ */
0x00, /* ........ */
},
[39] =
{
/* 71 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xce, /* ##..###. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[40] =
{
/* 72 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xfe, /* #######. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[41] =
{
/* 73 */
0x00, /* ........ */
0x3c, /* ..####.. */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[42] =
{
/* 74 */
0x00, /* ........ */
0x0e, /* ....###. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[43] =
{
/* 75 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xcc, /* ##..##.. */
0xd8, /* ##.##... */
0xf0, /* ####.... */
0xf0, /* ####.... */
0xd8, /* ##.##... */
0xcc, /* ##..##.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[44] =
{
/* 76 */
0x00, /* ........ */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc2, /* ##....#. */
0xfe, /* #######. */
0x00, /* ........ */
0x00, /* ........ */
},
[45] =
{
/* 77 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xee, /* ###.###. */
0xfe, /* #######. */
0xd6, /* ##.#.##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[46] =
{
/* 78 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xe6, /* ###..##. */
0xe6, /* ###..##. */
0xf6, /* ####.##. */
0xde, /* ##.####. */
0xce, /* ##..###. */
0xce, /* ##..###. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[47] =
{
/* 79 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[48] =
{
/* 80 */
0x00, /* ........ */
0xfc, /* ######.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xfc, /* ######.. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0x00, /* ........ */
0x00, /* ........ */
},
[49] =
{
/* 81 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xde, /* ##.####. */
0x7c, /* .#####.. */
0x06, /* .....##. */
0x00, /* ........ */
},
[50] =
{
/* 82 */
0x00, /* ........ */
0xfc, /* ######.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xfc, /* ######.. */
0xf8, /* #####... */
0xcc, /* ##..##.. */
0xcc, /* ##..##.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[51] =
{
/* 83 */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc0, /* ##...... */
0x7c, /* .#####.. */
0x06, /* .....##. */
0x06, /* .....##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[52] =
{
/* 84 */
0x00, /* ........ */
0x7e, /* .######. */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[53] =
{
/* 85 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[54] =
{
/* 86 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x44, /* .#...#.. */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x38, /* ..###... */
0x38, /* ..###... */
0x10, /* ...#.... */
0x00, /* ........ */
0x00, /* ........ */
},
[55] =
{
/* 87 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xd6, /* ##.#.##. */
0xd6, /* ##.#.##. */
0xfe, /* #######. */
0x6c, /* .##.##.. */
0x00, /* ........ */
0x00, /* ........ */
},
[56] =
{
/* 88 */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x38, /* ..###... */
0x38, /* ..###... */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[57] =
{
/* 89 */
0x00, /* ........ */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x66, /* .##..##. */
0x3c, /* ..####.. */
0x3c, /* ..####.. */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[58] =
{
/* 90 */
0x00, /* ........ */
0xfe, /* #######. */
0x06, /* .....##. */
0x06, /* .....##. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xfe, /* #######. */
0x00, /* ........ */
0x00, /* ........ */
},
[59] =
{
/* 91 */
0x00, /* ........ */
0x7c, /* .#####.. */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x7c, /* .#####.. */
0x00, /* ........ */
},
[60] =
{
/* 92 */
0x00, /* ........ */
0x80, /* #....... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0x60, /* .##..... */
0x30, /* ..##.... */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x06, /* .....##. */
0x06, /* .....##. */
0x02, /* ......#. */
0x00, /* ........ */
0x00, /* ........ */
},
[61] =
{
/* 93 */
0x00, /* ........ */
0x7c, /* .#####.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x7c, /* .#####.. */
0x00, /* ........ */
},
[62] =
{
/* 94 */
0x00, /* ........ */
0x10, /* ...#.... */
0x38, /* ..###... */
0x6c, /* .##.##.. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[63] =
{
/* 95 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xfe, /* #######. */
0x00, /* ........ */
},
[64] =
{
/* 96 */
0x00, /* ........ */
0x30, /* ..##.... */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
[65] =
{
/* 97 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7c, /* .#####.. */
0x06, /* .....##. */
0x7e, /* .######. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xce, /* ##..###. */
0x76, /* .###.##. */
0x00, /* ........ */
0x00, /* ........ */
},
[66] =
{
/* 98 */
0x00, /* ........ */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xdc, /* ##.###.. */
0xe6, /* ###..##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xe6, /* ###..##. */
0xdc, /* ##.###.. */
0x00, /* ........ */
0x00, /* ........ */
},
[67] =
{
/* 99 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7c, /* .#####.. */
0xe6, /* ###..##. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xe6, /* ###..##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[68] =
{
/* 100 */
0x00, /* ........ */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0x76, /* .###.##. */
0xce, /* ##..###. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xce, /* ##..###. */
0x76, /* .###.##. */
0x00, /* ........ */
0x00, /* ........ */
},
[69] =
{
/* 101 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xfe, /* #######. */
0xc0, /* ##...... */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[70] =
{
/* 102 */
0x00, /* ........ */
0x3c, /* ..####.. */
0x66, /* .##..##. */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0xfc, /* ######.. */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x00, /* ........ */
0x00, /* ........ */
},
[71] =
{
/* 103 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7e, /* .######. */
0xcc, /* ##..##.. */
0xcc, /* ##..##.. */
0xcc, /* ##..##.. */
0x78, /* .####... */
0xf0, /* ####.... */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
},
[72] =
{
/* 104 */
0x00, /* ........ */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xdc, /* ##.###.. */
0xe6, /* ###..##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[73] =
{
/* 105 */
0x00, /* ........ */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x38, /* ..###... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[74] =
{
/* 106 */
0x00, /* ........ */
0x00, /* ........ */
0x06, /* .....##. */
0x06, /* .....##. */
0x00, /* ........ */
0x0e, /* ....###. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0x06, /* .....##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
},
[75] =
{
/* 107 */
0x00, /* ........ */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xcc, /* ##..##.. */
0xd8, /* ##.##... */
0xf0, /* ####.... */
0xf0, /* ####.... */
0xd8, /* ##.##... */
0xcc, /* ##..##.. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[76] =
{
/* 108 */
0x00, /* ........ */
0x38, /* ..###... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x3c, /* ..####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[77] =
{
/* 109 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x6c, /* .##.##.. */
0xfe, /* #######. */
0xd6, /* ##.#.##. */
0xd6, /* ##.#.##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[78] =
{
/* 110 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xdc, /* ##.###.. */
0xe6, /* ###..##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[79] =
{
/* 111 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[80] =
{
/* 112 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xdc, /* ##.###.. */
0xe6, /* ###..##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xe6, /* ###..##. */
0xdc, /* ##.###.. */
0xc0, /* ##...... */
0xc0, /* ##...... */
},
[81] =
{
/* 113 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x76, /* .###.##. */
0xce, /* ##..###. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xce, /* ##..###. */
0x76, /* .###.##. */
0x06, /* .....##. */
0x06, /* .....##. */
},
[82] =
{
/* 114 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xdc, /* ##.###.. */
0xe6, /* ###..##. */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0xc0, /* ##...... */
0x00, /* ........ */
0x00, /* ........ */
},
[83] =
{
/* 115 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x7c, /* .#####.. */
0xc6, /* ##...##. */
0x60, /* .##..... */
0x38, /* ..###... */
0x0c, /* ....##.. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[84] =
{
/* 116 */
0x00, /* ........ */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0xfc, /* ######.. */
0x60, /* .##..... */
0x60, /* .##..... */
0x60, /* .##..... */
0x66, /* .##..##. */
0x3c, /* ..####.. */
0x00, /* ........ */
0x00, /* ........ */
},
[85] =
{
/* 117 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xce, /* ##..###. */
0x76, /* .###.##. */
0x00, /* ........ */
0x00, /* ........ */
},
[86] =
{
/* 118 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x6c, /* .##.##.. */
0x6c, /* .##.##.. */
0x38, /* ..###... */
0x00, /* ........ */
0x00, /* ........ */
},
[87] =
{
/* 119 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xd6, /* ##.#.##. */
0xd6, /* ##.#.##. */
0xfe, /* #######. */
0x6c, /* .##.##.. */
0x00, /* ........ */
0x00, /* ........ */
},
[88] =
{
/* 120 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x6c, /* .##.##.. */
0x38, /* ..###... */
0x6c, /* .##.##.. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0x00, /* ........ */
0x00, /* ........ */
},
[89] =
{
/* 121 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xc6, /* ##...##. */
0xce, /* ##..###. */
0x76, /* .###.##. */
0x06, /* .....##. */
0xc6, /* ##...##. */
0x7c, /* .#####.. */
},
[90] =
{
/* 122 */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0xfe, /* #######. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x30, /* ..##.... */
0x60, /* .##..... */
0xc0, /* ##...... */
0xfe, /* #######. */
0x00, /* ........ */
0x00, /* ........ */
},
[91] =
{
/* 123 */
0x00, /* ........ */
0x1e, /* ...####. */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x18, /* ...##... */
0x70, /* .###.... */
0x18, /* ...##... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x30, /* ..##.... */
0x1e, /* ...####. */
0x00, /* ........ */
},
[92] =
{
/* 124 */
0x00, /* ........ */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x18, /* ...##... */
0x00, /* ........ */
0x00, /* ........ */
},
[93] =
{
/* 125 */
0x00, /* ........ */
0x78, /* .####... */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x18, /* ...##... */
0x0e, /* ....###. */
0x18, /* ...##... */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x0c, /* ....##.. */
0x78, /* .####... */
0x00, /* ........ */
},
[94] =
{
/* 126 */
0x00, /* ........ */
0x00, /* ........ */
0x72, /* .###..#. */
0xfe, /* #######. */
0x9c, /* #..###.. */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
0x00, /* ........ */
},
};
| 52,853 | 1,633 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/abort.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/sig.h"
/**
* Terminates program abnormally.
*
* This function first tries to trigger your SIGABRT handler. If the
* signal handler returns, then `signal(SIGABRT, SIG_DFL)` is called
* before SIGABRT is raised again.
*
* @asyncsignalsafe
* @noreturn
*/
wontreturn void abort(void) {
sigset_t m;
sigemptyset(&m);
sigaddset(&m, SIGABRT);
sigprocmask(SIG_UNBLOCK, &m, 0);
raise(SIGABRT);
signal(SIGABRT, SIG_DFL);
raise(SIGABRT);
notpossible;
}
| 2,473 | 45 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/isdynamicexecutable.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/elf/def.h"
#include "libc/elf/elf.h"
#include "libc/elf/struct/ehdr.h"
#include "libc/elf/struct/phdr.h"
#include "libc/errno.h"
#include "libc/intrin/bits.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
/**
* Returns true if ELF executable uses dynamic loading magic.
*/
bool _IsDynamicExecutable(const char *prog) {
bool res;
Elf64_Ehdr *e;
Elf64_Phdr *p;
struct stat st;
int i, fd, err;
BLOCK_CANCELLATIONS;
fd = -1;
err = errno;
e = MAP_FAILED;
if ((fd = open(prog, O_RDONLY)) == -1) {
res = false;
goto Finish;
}
if (fstat(fd, &st) == -1 || st.st_size < 64) {
res = false;
goto Finish;
}
if ((e = mmap(0, st.st_size, PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED) {
res = false;
goto Finish;
}
if (READ32LE(e->e_ident) != READ32LE(ELFMAG)) {
res = false;
goto Finish;
}
if (e->e_type == ET_DYN) {
res = true;
goto Finish;
}
for (i = 0; i < e->e_phnum; ++i) {
p = GetElfSegmentHeaderAddress(e, st.st_size, i);
if (p->p_type == PT_INTERP || p->p_type == PT_DYNAMIC) {
res = true;
goto Finish;
}
}
res = false;
goto Finish;
Finish:
if (e != MAP_FAILED) munmap(e, st.st_size);
if (fd != -1) close(fd);
errno = err;
ALLOW_CANCELLATIONS;
return res;
}
| 3,325 | 82 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/stackuse.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/promises.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
static char stacklog[1024];
size_t GetStackUsage(char *s, size_t n) {
// RHEL5 MAP_GROWSDOWN seems to only grow to 68kb :'(
// So we count non-zero bytes down from the top
// First clear 64 bytes is considered the end
long *p;
size_t got;
p = (long *)(s + n);
got = 0;
for (;;) {
p -= 8;
if (p[0] | p[1] | p[2] | p[3] | p[4] | p[5] | p[6] | p[7]) {
++got;
} else {
break;
}
}
return got * 8 * sizeof(long);
}
static textexit void LogStackUse(void) {
bool quote;
char *p, *q;
int i, e, fd;
size_t n, usage;
if (!PLEDGED(STDIO) || !PLEDGED(WPATH) || !PLEDGED(CPATH)) return;
usage = GetStackUsage((char *)GetStackAddr(), GetStackSize());
e = errno;
if ((fd = open(stacklog, O_APPEND | O_CREAT | O_WRONLY, 0644)) != -1) {
p = FormatUint64(stacklog, usage);
for (i = 0; i < __argc; ++i) {
n = strlen(__argv[i]);
if ((q = memchr(__argv[i], '\n', n))) n = q - __argv[i];
if (p - stacklog + 1 + 1 + n + 1 + 1 < sizeof(stacklog)) {
quote = !!memchr(__argv[i], ' ', n);
*p++ = ' ';
if (quote) *p++ = '\'';
p = mempcpy(p, __argv[i], n);
if (quote) *p++ = '\'';
} else {
break;
}
}
*p++ = '\n';
write(fd, stacklog, p - stacklog);
close(fd);
}
errno = e;
}
static textstartup void LogStackUseInit(void) {
if (!PLEDGED(WPATH)) return;
if (isdirectory("o/" MODE) &&
getcwd(stacklog, sizeof(stacklog) - strlen("/o/" MODE "/stack.log"))) {
strcat(stacklog, "/o/" MODE "/stack.log");
atexit(LogStackUse);
}
}
const void *const stack_usage_logging[] initarray = {
LogStackUseInit,
};
| 3,803 | 93 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/cosmo.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/macros.internal.h"
#include "libc/notice.inc"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/consts/map.h"
#include "libc/intrin/strace.internal.h"
#include "libc/sysv/consts/map.h"
#include "libc/dce.h"
#ifdef __x86_64__
.text.startup
// Cosmopolitan runtime.
//
// @param edi is argc
// @param rsi is argv
// @param rdx is environ
// @param rcx is auxv
// @noreturn
cosmo: push %rbp
mov %rsp,%rbp
mov %edi,%r12d
mov %rsi,%r13
mov %rdx,%r14
mov %rcx,%r15
#ifdef SYSDEBUG
call __strace_init
mov %eax,%r12d
#endif /* SYSDEBUG */
// Windows always initializes FPU to douuble precision.
// WSL breaks Linux ABI by initializing FPU to double precision.
// This code makes long double long again.
//
// @see System V Application Binary Interface NexGen32e Architecture
// Processor Supplement, Version 1.0, December 5th, 2018
// Section 3.4.1: Initial Stack and Register State
fldcw 1f(%rip)
.rodata
.balign 2
// 8087 FPU Control Word
// IM: Invalid Operation ââââââââââââââââ
// DM: Denormal Operand âââââââââââââââââ
// ZM: Zero Divide ââââââââââââââââââââââ
// OM: Overflow âââââââââââââââââââââââââ
// UM: Underflow ââââââââââââââââââââââââ
// PM: Precision ââââââââââââââââââââââââ
// PC: Precision Control ââââââââ ââââââ
// {float,â
,double,long double}â ââââââ
// RC: Rounding Control âââââââ â ââââââ
// {even, â-â, â+â, â0} ââ⤠ââââââ
// ââ¤ââ ââââââ
// dâââârrââââââ
1: .short 0b00000000000000000001101111111
.previous
#ifdef __FAST_MATH__
push %rax
stmxcsr (%rsp)
orl $0x8040,(%rsp)
ldmxcsr (%rsp)
pop %rax
#endif
// run assembly init
call _init
// call constructors
ezlea __init_array_end,ax // static ctors in forward order
.weak __init_array_end // could be called multiple times
ezlea __init_array_start,cx // idempotency recommended
.weak __init_array_start // @see ape/ape.lds
1: cmp %rax,%rcx
je 2f
sub $8,%rax
push %rax
push %rcx
call .Largs
call *(%rax)
pop %rcx
pop %rax
jmp 1b
// call main()
2: call .Largs
.weak main
call main
xchg %eax,%edi
call exit
.Largs: mov %r12d,%edi
mov %r13,%rsi
mov %r14,%rdx
mov %r15,%rcx
ret
.endfn cosmo,weak
// Enables Thread Local Storage.
.init.start 304,_init_tls
push %rdi
push %rsi
call __enable_tls
pop %rsi
pop %rdi
.init.end 304,_init_tls
#if !IsTiny()
// Creates deterministically addressed stack we can use
//
// This helps debugging be more comprehensible, because
// when diagnosing low-level problems when error report
// isn't working, sometimes numbers are all you have to
// go on, and we can't use them if kernel hardening has
// configured that meaningful data to be randomized.
//
// Having deterministic addresses is also key to ensure
// builds, execution, and other things are reproducible
.init.start 304,_init_stack
testb IsWindows()
jnz 9f
testb IsMetal()
jnz 9f
push %rdi
push %rsi
// allocate stack
movabs $ape_stack_vaddr,%rdi
mov $ape_stack_memsz,%esi
mov $ape_stack_prot,%edx
mov $MAP_STACK,%ecx
or MAP_ANONYMOUS,%ecx
or $-1,%r8
xor %r9d,%r9d
push %rsi
push %rsi
call mmap
pop %r8
pop %r8
pop %rsi
pop %rdi
cmp $-1,%rax
je 9f
// switch stacks
//
// we subtract 8 because the openbsd kernel always checks rsp
// is on a MAP_STACK interval non-inclusively of stack + size
leave
pop %rcx // return address
sub $8,%r8d // openbsd:stackbound
lea (%rax,%r8),%rsp
mov $ape_stack_align,%eax
neg %rax
and %rax,%rsp
push %rcx
push %rbp
mov %rsp,%rbp
9: nop
.init.end 304,_init_stack
.weak ape_stack_prot
.weak ape_stack_vaddr
.weak ape_stack_memsz
.weak ape_stack_align
#endif
#if IsAsan()
.init.start 305,_init_symbols
push %rdi
push %rsi
call __init_symbols
pop %rsi
pop %rdi
.init.end 305,_init_symbols
#endif
#ifdef __PG__
.init.start 306,_init_ftrace
push %rdi
push %rsi
call ftrace_init
mov %eax,%r12d
pop %rsi
pop %rdi
.init.end 306,_init_ftrace
#endif
#if IsModeDbg()
#ifdef SYSDEBUG
.init.start 307,_init_printargs
cmpl $0,__strace(%rip)
jz 1f
push %rdi
push %rsi
loadstr STRACE_PROLOGUE,di
call __printargs
pop %rsi
pop %rdi
1: .init.end 307,_init_printargs
#endif
#endif
#endif /* __x86_64__ */
| 6,447 | 221 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/isheap.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/macros.internal.h"
#include "libc/runtime/memtrack.internal.h"
#include "libc/runtime/runtime.h"
/**
* Returns true if address isn't stack and was malloc'd or mmap'd.
*
* @assume stack addresses are always greater than heap addresses
* @assume stack memory isn't stored beneath %rsp (-mno-red-zone)
*/
optimizesize noasan bool _isheap(void *p) {
intptr_t x, y;
x = kAutomapStart;
y = x + kAutomapSize;
return x <= (intptr_t)p && (intptr_t)p < y;
}
| 2,313 | 35 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/cocmd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/timespec.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/conv.h"
#include "libc/fmt/itoa.h"
#include "libc/fmt/magnumstrs.internal.h"
#include "libc/intrin/_getenv.internal.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/weaken.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/timer.h"
#include "third_party/awk/cmd.h"
#include "third_party/musl/glob.h"
#include "third_party/sed/cmd.h"
#include "third_party/tr/cmd.h"
#include "tool/curl/cmd.h"
/**
* @fileoverview Cosmopolitan Command Interpreter
*
* This is a lightweight command interpreter for GNU Make. It has just
* enough shell script language support to support our build config.
*/
#define STATE_CMD 0
#define STATE_VAR 1
#define STATE_SINGLE 2
#define STATE_QUOTED 3
#define STATE_QUOTED_VAR 4
#define STATE_WHITESPACE 5
#define TOMBSTONE ((char *)-1)
#define READ24(s) READ32LE(s "\0")
static char *p;
static char *q;
static char *r;
static int envi;
static int vari;
static size_t n;
static char *cmd;
static char *assign;
static char var[32];
static int lastchild;
static int exitstatus;
static char *envs[500];
static char *args[3000];
static const char *prog;
static char errbuf[512];
static char argbuf[ARG_MAX];
static bool unsupported[256];
static ssize_t Write(int fd, const char *s) {
return write(fd, s, strlen(s));
}
static void Log(const char *s, ...) {
va_list va;
va_start(va, s);
errbuf[0] = 0;
do {
strlcat(errbuf, s, sizeof(errbuf));
} while ((s = va_arg(va, const char *)));
strlcat(errbuf, "\n", sizeof(errbuf));
Write(2, errbuf);
va_end(va);
}
static wontreturn void Wexit(int rc, const char *s, ...) {
va_list va;
va_start(va, s);
errbuf[0] = 0;
do {
strlcat(errbuf, s, sizeof(errbuf));
} while ((s = va_arg(va, const char *)));
Write(2, errbuf);
va_end(va);
_Exit(rc);
}
static wontreturn void UnsupportedSyntax(unsigned char c) {
char ibuf[13], cbuf[2] = {c};
FormatOctal32(ibuf, c, true);
Wexit(4, prog, ": unsupported syntax '", cbuf, "' (", ibuf, "): ", cmd, "\n",
0);
}
static wontreturn void SysExit(int rc, const char *call, const char *thing) {
int err;
char ibuf[12];
const char *estr;
err = errno;
FormatInt32(ibuf, err);
estr = _strerdoc(err);
if (!estr) estr = "EUNKNOWN";
Wexit(rc, thing, ": ", call, "() failed: ", estr, " (", ibuf, ")\n", 0);
}
static void Open(const char *path, int fd, int flags) {
const char *err;
close(fd);
if (open(path, flags, 0644) == -1) {
SysExit(7, "open", path);
}
}
static wontreturn void Exec(void) {
_unassert(args[0][0]);
if (!n) Wexit(5, prog, ": error: too few args\n", 0);
execvpe(args[0], args, envs);
SysExit(127, "execve", args[0]);
}
static int GetSignalByName(const char *s) {
for (int i = 0; kSignalNames[i].x != MAGNUM_TERMINATOR; ++i) {
if (!strcmp(s, MAGNUM_STRING(kSignalNames, i) + 3)) {
return MAGNUM_NUMBER(kSignalNames, i);
}
}
return 0;
}
static void PutEnv(char **p, const char *kv) {
struct Env e;
e = _getenv(p, kv);
p[e.i] = kv;
if (!e.s) p[e.i + 1] = 0;
}
static void Append(int c) {
_npassert(q + 1 < argbuf + sizeof(argbuf));
*q++ = c;
}
static char *Finish(void) {
char *s = r;
Append(0);
r = q;
if (!assign) {
return s;
} else {
PutEnv(envs, s);
assign = 0;
return TOMBSTONE;
}
}
static int True(void) {
return 0;
}
static int False(void) {
return 1;
}
static wontreturn void Exit(void) {
_Exit(n > 1 ? atoi(args[1]) : 0);
}
static int Wait(void) {
char ibuf[12];
int e, rc, ws, pid;
if (n > 1) {
if (waitpid(atoi(args[1]), &ws, 0) == -1) {
SysExit(22, "waitpid", prog);
}
rc = WIFEXITED(ws) ? WEXITSTATUS(ws) : 128 + WTERMSIG(ws);
exitstatus = rc;
} else {
for (e = errno;;) {
if (waitpid(-1, &ws, 0) == -1) {
if (errno == ECHILD) {
errno = e;
break;
}
SysExit(22, "waitpid", prog);
}
}
rc = 0;
}
return rc;
}
static int Echo(void) {
int i = 1;
bool once = false;
const char *l = " ";
if (i < n && !strcmp(args[i], "-l")) {
++i, l = "\n";
}
for (; i < n; ++i) {
if (once) {
Write(1, l);
} else {
once = true;
}
Write(1, args[i]);
}
Write(1, "\n");
return 0;
}
static int Read(void) {
unsigned char c;
int i, j, rc = 1;
for (i = 1; i < n; ++i) {
if (args[i][0] != '-') break;
if (args[i][1] == 'p' && !args[i][2] && i + 1 < n) {
Write(1, args[++i]);
}
}
if (i >= n) return 1;
for (j = 0; args[i][j]; ++j) {
Append(args[i][j]);
}
Append('=');
while (read(0, &c, 1) > 0) {
if (c == '\n') break;
Append(c);
rc = 0;
}
PutEnv(envs, Finish());
return rc;
}
static int Cd(void) {
const char *s;
if ((s = n > 1 ? args[1] : _getenv(envs, "HOME").s)) {
if (!chdir(s)) {
return 0;
} else {
Log("chdir: ", s, ": ", _strerdoc(errno), NULL);
return 1;
}
} else {
Log("chdir: missing argument", NULL);
return 1;
}
}
static int Mkdir(void) {
int i = 1;
int (*f)(const char *, unsigned) = mkdir;
if (n >= 3 && !strcmp(args[1], "-p")) ++i, f = makedirs;
for (; i < n; ++i) {
if (f(args[i], 0755)) {
Log("mkdir: ", args[i], ": ", _strerdoc(errno), NULL);
return errno;
}
}
return 0;
}
static int Kill(void) {
int sig, rc = 0, i = 1;
if (i < n && args[i][0] == '-') {
sig = GetSignalByName(args[i++] + 1);
if (!sig) return -1; // fallback to system kill command
} else {
sig = SIGTERM;
}
for (; i < n; ++i) {
if (kill(atoi(args[i]), sig)) {
Log("kill: ", args[i], ": ", _strerdoc(errno), NULL);
rc = 1;
}
}
return rc;
}
static int Toupper(void) {
int i, n;
char b[512];
while ((n = read(0, b, 512)) > 0) {
for (i = 0; i < n; ++i) {
b[i] = toupper(b[i]);
}
write(1, b, n);
}
return 0;
}
static int Usleep(void) {
int f;
struct timespec t;
if (n > 1) {
f = 0;
t = timespec_frommicros(atoi(args[1]));
} else {
f = TIMER_ABSTIME;
t = timespec_max;
}
return clock_nanosleep(0, f, &t, 0);
}
static int Test(void) {
int w, m = n;
struct stat st;
if (m && READ16LE(args[m - 1]) == READ16LE("]")) --m;
if (m == 4) {
w = READ32LE(args[2]) & 0x00ffffff;
if ((w & 65535) == READ16LE("=")) return !!strcmp(args[1], args[3]);
if (w == READ24("==")) return !!strcmp(args[1], args[3]);
if (w == READ24("!=")) return !strcmp(args[1], args[3]);
} else if (m == 3) {
w = READ32LE(args[1]) & 0x00ffffff;
if (w == READ24("-n")) return !(strlen(args[2]) > 0);
if (w == READ24("-z")) return !(strlen(args[2]) == 0);
if (w == READ24("-e")) return !!stat(args[2], &st);
if (w == READ24("-f")) return !(!stat(args[2], &st) && S_ISREG(st.st_mode));
if (w == READ24("-d")) return !(!stat(args[2], &st) && S_ISDIR(st.st_mode));
if (w == READ24("-h")) return !(!stat(args[2], &st) && S_ISLNK(st.st_mode));
}
return -1; // fall back to system test command
}
static int Rm(void) {
int i;
if (n > 1 && args[1][0] != '-') {
for (i = 1; i < n; ++i) {
if (unlink(args[i])) {
Log("rm: ", args[i], ": ", _strerdoc(errno), NULL);
return 1;
}
}
return 0;
} else {
return -1; // fall back to system rm command
}
}
static int Rmdir(void) {
int i;
if (n > 1 && args[1][0] != '-') {
for (i = 1; i < n; ++i) {
if (rmdir(args[i])) {
Log("rmdir: ", args[i], ": ", _strerdoc(errno), NULL);
return 1;
}
}
return 0;
} else {
return -1; // fall back to system rmdir command
}
}
static int Touch(void) {
int i;
if (n > 1 && args[1][0] != '-') {
for (i = 1; i < n; ++i) {
if (touch(args[i], 0644)) {
Log("touch: ", args[i], ": ", _strerdoc(errno), NULL);
return 1;
}
}
return 0;
} else {
return -1; // fall back to system rmdir command
}
}
static int Fake(int main(int, char **)) {
int exitstatus, ws, pid;
if ((pid = fork()) == -1) SysExit(21, "vfork", prog);
if (!pid) {
// TODO(jart): Maybe nuke stdio state somehow?
environ = envs;
exit(main(n, args));
}
if (waitpid(pid, &ws, 0) == -1) SysExit(22, "waitpid", prog);
exitstatus = WIFEXITED(ws) ? WEXITSTATUS(ws) : 128 + WTERMSIG(ws);
return n = 0, exitstatus;
}
static int TryBuiltin(void) {
if (!n) return exitstatus;
if (!strcmp(args[0], "exit")) Exit();
if (!strcmp(args[0], "cd")) return Cd();
if (!strcmp(args[0], "rm")) return Rm();
if (!strcmp(args[0], "[")) return Test();
if (!strcmp(args[0], "wait")) return Wait();
if (!strcmp(args[0], "echo")) return Echo();
if (!strcmp(args[0], "read")) return Read();
if (!strcmp(args[0], "true")) return True();
if (!strcmp(args[0], "test")) return Test();
if (!strcmp(args[0], "kill")) return Kill();
if (!strcmp(args[0], "touch")) return Touch();
if (!strcmp(args[0], "rmdir")) return Rmdir();
if (!strcmp(args[0], "mkdir")) return Mkdir();
if (!strcmp(args[0], "false")) return False();
if (!strcmp(args[0], "usleep")) return Usleep();
if (!strcmp(args[0], "toupper")) return Toupper();
if (_weaken(_tr) && !strcmp(args[0], "tr")) return Fake(_weaken(_tr));
if (_weaken(_sed) && !strcmp(args[0], "sed")) return Fake(_weaken(_sed));
if (_weaken(_awk) && !strcmp(args[0], "awk")) return Fake(_weaken(_awk));
if (_weaken(_curl) && !strcmp(args[0], "curl")) return Fake(_weaken(_curl));
return -1;
}
static wontreturn void Launch(void) {
int rc;
if ((rc = TryBuiltin()) != -1) _Exit(rc);
Exec();
}
static void Pipe(void) {
int pid, pfds[2];
if (pipe2(pfds, O_CLOEXEC)) SysExit(8, "pipe2", prog);
if ((pid = fork()) == -1) SysExit(9, "vfork", prog);
if (!pid) {
_unassert(dup2(pfds[1], 1) == 1);
// we can't rely on cloexec because builtins
if (pfds[0] != 1) _unassert(!close(pfds[0]));
if (pfds[1] != 1) _unassert(!close(pfds[1]));
Launch();
}
_unassert(!dup2(pfds[0], 0));
if (pfds[1]) _unassert(!close(pfds[1]));
n = 0;
}
static int Run(void) {
int exitstatus, ws, pid;
if ((exitstatus = TryBuiltin()) == -1) {
if ((pid = vfork()) == -1) SysExit(21, "vfork", prog);
if (!pid) Exec();
if (waitpid(pid, &ws, 0) == -1) SysExit(22, "waitpid", prog);
exitstatus = WIFEXITED(ws) ? WEXITSTATUS(ws) : 128 + WTERMSIG(ws);
}
n = 0;
return exitstatus;
}
static void Async(void) {
if ((lastchild = fork()) == -1) SysExit(21, "vfork", prog);
if (!lastchild) Launch();
n = 0;
}
static const char *IntToStr(int x) {
static char ibuf[12];
FormatInt32(ibuf, x);
return ibuf;
}
static const char *GetVar(const char *key) {
static char vbuf[PATH_MAX];
if (key[0] == '$' && !key[1]) {
return IntToStr(getpid());
} else if (key[0] == '!' && !key[1]) {
return IntToStr(lastchild);
} else if (key[0] == '?' && !key[1]) {
return IntToStr(exitstatus);
} else if (!strcmp(key, "PWD")) {
_npassert(getcwd(vbuf, sizeof(vbuf)));
return vbuf;
} else if (!strcmp(key, "UID")) {
FormatInt32(vbuf, getuid());
return vbuf;
} else if (!strcmp(key, "GID")) {
FormatInt32(vbuf, getgid());
return vbuf;
} else if (!strcmp(key, "EUID")) {
FormatInt32(vbuf, geteuid());
return vbuf;
} else {
return _getenv(envs, key).s;
}
}
static bool IsVarName(int c) {
return isalnum(c) || c == '_' ||
(!vari && (c == '?' || c == '!' || c == '$'));
}
static bool CopyVar(void) {
size_t j;
const char *s;
if (IsVarName(*p)) {
_npassert(vari + 1 < sizeof(var));
var[vari++] = *p;
var[vari] = 0;
return false;
}
if ((s = GetVar(var))) {
if ((j = strlen(s))) {
_npassert(q + j < argbuf + sizeof(argbuf));
q = mempcpy(q, s, j);
}
}
return true;
}
static char *Tokenize(void) {
const char *s;
int c, t, j, k, rc;
for (t = STATE_WHITESPACE;; ++p) {
switch (t) {
case STATE_WHITESPACE:
if (!*p) return 0;
if (*p == ' ' || *p == '\t' || *p == '\n' ||
(p[0] == '\\' && p[1] == '\n')) {
continue;
}
t = STATE_CMD;
// fallthrough
case STATE_CMD:
if (unsupported[*p & 255]) {
UnsupportedSyntax(*p);
}
if (!*p || *p == ' ' || *p == '\t') {
return Finish();
} else if (*p == '"') {
t = STATE_QUOTED;
} else if (*p == '\'') {
t = STATE_SINGLE;
} else if (*p == '$') {
t = STATE_VAR;
var[(vari = 0)] = 0;
} else if (*p == '\\') {
if (!p[1]) UnsupportedSyntax(*p);
Append(*++p);
} else if (*p == '=') {
if (!n && q > r) assign = r;
Append(*p);
} else if (*p == '|') {
if (q > r) {
return Finish();
} else if (p[1] == '|') {
rc = Run();
if (!rc) {
_Exit(0);
} else {
++p;
t = STATE_WHITESPACE;
}
} else {
Pipe();
t = STATE_WHITESPACE;
}
} else if (*p == ';' || *p == '\n') {
if (q > r) {
return Finish();
} else {
exitstatus = Run();
t = STATE_WHITESPACE;
}
} else if (*p == '>') {
Append(*p);
if (p[1] == '&') {
Append(*++p);
}
} else if (*p == '&') {
if (q > r) {
return Finish();
} else if (p[1] == '&') {
rc = Run();
if (!rc) {
++p;
t = STATE_WHITESPACE;
} else {
_Exit(rc);
}
} else {
Async();
t = STATE_WHITESPACE;
}
} else {
Append(*p);
}
break;
case STATE_VAR:
// XXX: we need to find a simple elegant way to break up
// unquoted variable expansions into multiple args.
if (CopyVar()) t = STATE_CMD, --p;
break;
case STATE_SINGLE:
if (!*p) goto UnterminatedString;
if (*p == '\'') {
t = STATE_CMD;
} else {
*q++ = *p;
}
break;
UnterminatedString:
Wexit(6, "cmd: error: unterminated string\n", 0);
case STATE_QUOTED_VAR:
if (!*p) goto UnterminatedString;
if (CopyVar()) t = STATE_QUOTED, --p;
break;
case STATE_QUOTED:
if (!*p) goto UnterminatedString;
if (*p == '"') {
t = STATE_CMD;
} else if (p[0] == '$') {
t = STATE_QUOTED_VAR;
var[(vari = 0)] = 0;
} else if (p[0] == '\\') {
switch ((c = *++p)) {
case 0:
UnsupportedSyntax('\\');
case '\n':
break;
case '$':
case '`':
case '"':
*q++ = c;
break;
default:
*q++ = '\\';
*q++ = c;
break;
}
} else {
*q++ = *p;
}
break;
default:
unreachable;
}
}
}
static const char *GetRedirectArg(const char *prog, const char *arg, int n) {
if (arg[n]) {
return arg + n;
} else if ((arg = Tokenize())) {
return arg;
} else {
Wexit(14, prog, ": error: redirect missing path\n", 0);
}
}
int _cocmd(int argc, char **argv, char **envp) {
char *arg;
size_t i, j;
size_t globCount = 0;
int globFlags = 0;
glob_t globTheBuilder;
prog = argc > 0 ? argv[0] : "cocmd.com";
for (i = 1; i < 32; ++i) {
unsupported[i] = true;
}
unsupported['\t'] = false;
unsupported['\n'] = false;
unsupported[0177] = true;
unsupported['~'] = true;
unsupported['`'] = true;
unsupported['#'] = true;
unsupported['('] = true;
unsupported[')'] = true;
unsupported['{'] = true;
unsupported['}'] = false; // Perl t/op/exec.t depends on unpaired } being
// passed from the shell to Perl
if (!_weaken(glob)) {
unsupported['*'] = true;
unsupported['?'] = true;
}
if (argc != 3) {
Wexit(10, prog, ": error: wrong number of args\n", 0);
}
if (strcmp(argv[1], "-c")) {
Wexit(11, prog, ": error: argv[1] should -c\n", 0);
}
p = cmd = argv[2];
if (strlen(cmd) >= ARG_MAX) {
Wexit(12, prog, ": error: cmd too long: ", cmd, "\n", 0);
}
// copy environment variables
envi = 0;
if (envp) {
for (; envp[envi]; ++envi) {
_npassert(envi + 1 < ARRAYLEN(envs));
envs[envi] = envp[envi];
}
}
envs[envi] = 0;
// get command line arguments
n = 0;
r = q = argbuf;
while ((arg = Tokenize())) {
if (arg == TOMBSTONE) continue;
if (n + 1 < ARRAYLEN(args)) {
if (isdigit(arg[0]) && arg[1] == '>' && arg[2] == '&' &&
isdigit(arg[3])) {
dup2(arg[3] - '0', arg[0] - '0');
} else if (arg[0] == '>' && arg[1] == '&' && isdigit(arg[2])) {
dup2(arg[2] - '0', 1);
} else if (isdigit(arg[0]) && arg[1] == '>' && arg[2] == '>') {
Open(GetRedirectArg(prog, arg, 3), arg[0] - '0',
O_WRONLY | O_CREAT | O_APPEND);
} else if (arg[0] == '>' && arg[1] == '>') {
Open(GetRedirectArg(prog, arg, 2), 1, O_WRONLY | O_CREAT | O_APPEND);
} else if (isdigit(arg[0]) && arg[1] == '>') {
Open(GetRedirectArg(prog, arg, 2), arg[0] - '0',
O_WRONLY | O_CREAT | O_TRUNC);
} else if (arg[0] == '>') {
Open(GetRedirectArg(prog, arg, 1), 1, O_WRONLY | O_CREAT | O_TRUNC);
} else if (arg[0] == '<') {
Open(GetRedirectArg(prog, arg, 1), 0, O_RDONLY);
} else {
int globrc = GLOB_NOMATCH;
if (_weaken(glob)) {
globrc = _weaken(glob)(arg, globFlags, NULL, &globTheBuilder);
if (globrc == 0) {
for (; globCount < globTheBuilder.gl_pathc; globCount++) {
args[n++] = globTheBuilder.gl_pathv[globCount];
}
} else if (globrc != GLOB_NOMATCH) {
Wexit(16, prog, ": error: with glob\n", 0);
}
globFlags |= GLOB_APPEND;
}
if (globrc == GLOB_NOMATCH) {
args[n++] = arg;
}
args[n] = 0;
}
} else {
Wexit(13, prog, ": error: too many args\n", 0);
}
}
Launch();
}
| 20,516 | 766 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/symbolic.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_SYMBOLIC_H_
#define COSMOPOLITAN_LIBC_RUNTIME_SYMBOLIC_H_
#ifdef __ASSEMBLER__
/* clang-format off */
#define SYMBOLIC(NAME) NAME(%rip)
#define LITERALLY(NAME) $NAME
/* clang-format on */
#else
#define SYMBOLIC(NAME) NAME
#define LITERALLY(NAME) NAME
#endif
#endif /* COSMOPOLITAN_LIBC_RUNTIME_SYMBOLIC_H_ */
| 346 | 15 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/runtime.mk | #-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-â
#âââvi: set et ft=make ts=8 tw=8 fenc=utf-8 :viââââââââââââââââââââââââ
#
# SYNOPSIS
#
# Cosmopolitan Runtime
#
# DESCRIPTION
#
# This package exports essential routines for userspace process
# initialization.
PKGS += LIBC_RUNTIME
LIBC_RUNTIME = $(LIBC_RUNTIME_A_DEPS) $(LIBC_RUNTIME_A)
LIBC_RUNTIME_ARTIFACTS += LIBC_RUNTIME_A
LIBC_RUNTIME_A = o/$(MODE)/libc/runtime/runtime.a
LIBC_RUNTIME_A_FILES := $(wildcard libc/runtime/*)
LIBC_RUNTIME_A_HDRS = $(filter %.h,$(LIBC_RUNTIME_A_FILES))
LIBC_RUNTIME_A_SRCS_S = $(filter %.S,$(LIBC_RUNTIME_A_FILES))
LIBC_RUNTIME_A_SRCS_C = $(filter %.c,$(LIBC_RUNTIME_A_FILES))
LIBC_RUNTIME_A_SRCS = \
$(LIBC_RUNTIME_A_SRCS_S) \
$(LIBC_RUNTIME_A_SRCS_C)
LIBC_RUNTIME_A_OBJS = \
$(LIBC_RUNTIME_A_SRCS_S:%.S=o/$(MODE)/%.o) \
$(LIBC_RUNTIME_A_SRCS_C:%.c=o/$(MODE)/%.o)
LIBC_RUNTIME_A_CHECKS = \
$(LIBC_RUNTIME_A).pkg \
$(LIBC_RUNTIME_A_HDRS:%=o/$(MODE)/%.ok)
LIBC_RUNTIME_A_DIRECTDEPS = \
LIBC_CALLS \
LIBC_ELF \
LIBC_FMT \
LIBC_INTRIN \
LIBC_NEXGEN32E \
LIBC_NT_ADVAPI32 \
LIBC_NT_KERNEL32 \
LIBC_NT_SYNCHRONIZATION \
LIBC_STR \
LIBC_STUBS \
LIBC_SYSV \
LIBC_SYSV_CALLS \
THIRD_PARTY_PUFF \
THIRD_PARTY_XED
LIBC_RUNTIME_A_DEPS := \
$(call uniq,$(foreach x,$(LIBC_RUNTIME_A_DIRECTDEPS),$($(x))))
$(LIBC_RUNTIME_A): \
libc/runtime/ \
$(LIBC_RUNTIME_A).pkg \
$(LIBC_RUNTIME_A_OBJS)
$(LIBC_RUNTIME_A).pkg: \
$(LIBC_RUNTIME_A_OBJS) \
$(foreach x,$(LIBC_RUNTIME_A_DIRECTDEPS),$($(x)_A).pkg)
# we can't use asan and ubsan because:
# asan and ubsan can be function traced
# we can't use function tracing because:
# this is the function tracing runtime
o/$(MODE)/libc/runtime/cosmo2.o: private \
OVERRIDE_CFLAGS += -O0
o/$(MODE)/libc/runtime/ftracer.o: private \
OVERRIDE_CFLAGS += \
-x-no-pg \
$(MNO_FENTRY) \
-ffreestanding \
-fno-sanitize=all
o/$(MODE)/libc/runtime/cosmo2.o \
o/$(MODE)/libc/runtime/fork-nt.o \
o/$(MODE)/libc/runtime/printmemoryintervals.o \
o/$(MODE)/libc/runtime/arememoryintervalsok.o \
o/$(MODE)/libc/runtime/findmemoryinterval.o \
o/$(MODE)/libc/runtime/sys_mprotect.greg.o \
o/$(MODE)/libc/runtime/getdosargv.o \
o/$(MODE)/libc/runtime/getdosenviron.o \
o/$(MODE)/libc/runtime/hook.greg.o \
o/$(MODE)/libc/runtime/ismemtracked.greg.o \
o/$(MODE)/libc/runtime/memtracknt.o \
o/$(MODE)/libc/runtime/memtrack.greg.o \
o/$(MODE)/libc/runtime/metalprintf.greg.o \
o/$(MODE)/libc/runtime/printargs.greg.o \
o/$(MODE)/libc/runtime/mman.greg.o \
o/$(MODE)/libc/runtime/print.greg.o \
o/$(MODE)/libc/runtime/stackchkfail.o \
o/$(MODE)/libc/runtime/stackchkfaillocal.o \
o/$(MODE)/libc/runtime/winmain.greg.o \
o/$(MODE)/libc/runtime/opensymboltable.o: private \
OVERRIDE_CFLAGS += \
-Os \
-ffreestanding \
$(NO_MAGIC)
# must use alloca()
# can't use asan or any runtime services
o/$(MODE)/libc/runtime/fork-nt.o: private \
OVERRIDE_CPPFLAGS += \
-DSTACK_FRAME_UNLIMITED
o/$(MODE)/libc/runtime/qsort.o: private \
OVERRIDE_CFLAGS += \
-Og
# make always linked runtimes less huge when it's profitable
o//libc/runtime/mmap.o \
o//libc/runtime/munmap.o \
o//libc/runtime/memtrack.greg.o \
o//libc/runtime/opensymboltable.greg.o: private \
OVERRIDE_CFLAGS += \
-Os
ifeq ($(ARCH), aarch64)
o/$(MODE)/libc/runtime/mmap.o \
o/$(MODE)/libc/runtime/enable_tls.o: private \
OVERRIDE_CFLAGS += \
-mcmodel=large
endif
# these assembly files are safe to build on aarch64
o/$(MODE)/libc/runtime/init.o: libc/runtime/init.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/runtime/wipe.o: libc/runtime/wipe.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/runtime/vfork.o: libc/runtime/vfork.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/runtime/clone-linux.o: libc/runtime/clone-linux.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/runtime/ftrace-hook.o: libc/runtime/ftrace-hook.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
o/$(MODE)/libc/runtime/dsohandle.o: libc/runtime/dsohandle.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) -c $<
LIBC_RUNTIME_LIBS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)))
LIBC_RUNTIME_SRCS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)_SRCS))
LIBC_RUNTIME_HDRS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)_HDRS))
LIBC_RUNTIME_BINS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)_BINS))
LIBC_RUNTIME_CHECKS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)_CHECKS))
LIBC_RUNTIME_OBJS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)_OBJS))
LIBC_RUNTIME_TESTS = $(foreach x,$(LIBC_RUNTIME_ARTIFACTS),$($(x)_TESTS))
$(LIBC_RUNTIME_OBJS): $(BUILD_FILES) libc/runtime/runtime.mk
.PHONY: o/$(MODE)/libc/runtime
o/$(MODE)/libc/runtime: $(LIBC_RUNTIME_CHECKS)
| 5,075 | 152 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/clktck.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_CLKTCK_H_
#define COSMOPOLITAN_LIBC_RUNTIME_CLKTCK_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define CLK_TCK (__clk_tck())
int __clk_tck(void) pureconst;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_CLKTCK_H_ */
| 328 | 13 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/ezmap.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/intrin/safemacros.internal.h"
#include "libc/limits.h"
#include "libc/log/libfatal.internal.h"
#include "libc/runtime/ezmap.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
// TODO(jart): DELETE
_Hide int MapFileRead(const char *filename, struct MappedFile *mf) {
mf->addr = MAP_FAILED;
if ((mf->fd = open(filename, O_RDONLY)) != -1 &&
(mf->size = getfiledescriptorsize(mf->fd)) < INT_MAX &&
(mf->addr = mf->size ? mmap(NULL, mf->size, PROT_READ,
MAP_PRIVATE | MAP_POPULATE, mf->fd, 0)
: NULL) != MAP_FAILED) {
return 0;
} else {
UnmapFile(mf);
return -1;
}
}
_Hide int UnmapFile(struct MappedFile *mf) {
int rc;
rc = 0;
if (mf->addr && mf->addr != MAP_FAILED) {
rc |= munmap(mf->addr, mf->size);
mf->addr = MAP_FAILED;
}
if (mf->fd != -1) {
rc |= close(mf->fd);
mf->fd = -1;
}
mf->size = 0;
return rc;
}
| 2,912 | 59 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/runtime.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_RUNTIME_H_
#define COSMOPOLITAN_LIBC_RUNTIME_RUNTIME_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/*ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â cosmopolitan § runtime ââ¬âââ¼
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#ifdef __x86_64__
typedef long jmp_buf[8];
#elif defined(__aarch64__)
typedef long jmp_buf[22];
#elif defined(__powerpc64__)
typedef unsigned __int128 jmp_buf[32];
#elif defined(__s390x__)
typedef unsigned long jmp_buf[18];
#elif defined(__riscv)
typedef unsigned long jmp_buf[26];
#endif
typedef long sigjmp_buf[12];
extern char **environ; /* CRT */
extern int __argc; /* CRT */
extern char **__argv; /* CRT */
extern char **__envp; /* CRT */
extern unsigned long *__auxv; /* CRT */
extern intptr_t __oldstack; /* CRT */
extern uint64_t __nosync; /* SYS */
extern int __strace; /* SYS */
extern int __ftrace; /* SYS */
extern char *program_invocation_name; /* RII */
extern char *program_invocation_short_name; /* RII */
extern uint64_t __syscount; /* RII */
extern uint64_t kStartTsc; /* RII */
extern char kTmpPath[]; /* RII */
extern const char kNtSystemDirectory[]; /* RII */
extern const char kNtWindowsDirectory[]; /* RII */
extern size_t __virtualmax;
extern bool __isworker;
void mcount(void);
int daemon(int, int);
int _freestack(void *);
void _bt(const char *, ...);
int _cocmd(int, char **, char **);
unsigned long getauxval(unsigned long);
void *_mapanon(size_t) attributeallocsize((1)) mallocesque;
void *_mapshared(size_t) attributeallocsize((1)) mallocesque;
void *_mapstack(void) returnsaligned((FRAMESIZE)) mallocesque;
int setjmp(jmp_buf)
libcesque returnstwice paramsnonnull();
void longjmp(jmp_buf, int) libcesque wontreturn paramsnonnull();
axdx_t setlongerjmp(jmp_buf)
libcesque returnstwice paramsnonnull();
void longerjmp(jmp_buf, intptr_t) libcesque wontreturn paramsnonnull();
int _setjmp(jmp_buf)
libcesque returnstwice paramsnonnull();
int sigsetjmp(sigjmp_buf, int) libcesque returnstwice paramsnonnull();
void siglongjmp(sigjmp_buf, int) libcesque wontreturn paramsnonnull();
void _longjmp(jmp_buf, int) libcesque wontreturn paramsnonnull();
void exit(int) wontreturn;
void _exit(int) libcesque wontreturn;
void _Exit(int) libcesque wontreturn;
void _Exitr(int) libcesque wontreturn;
void _Exit1(int) libcesque wontreturn;
void quick_exit(int) wontreturn;
void abort(void) wontreturn;
int __cxa_atexit(void *, void *, void *) libcesque;
int atfork(void *, void *) libcesque;
int atexit(void (*)(void)) libcesque;
char *getenv(const char *) nosideeffect libcesque;
int putenv(char *) paramsnonnull();
int setenv(const char *, const char *, int);
int unsetenv(const char *);
int clearenv(void);
void fpreset(void);
void *mmap(void *, uint64_t, int32_t, int32_t, int32_t, int64_t);
void *mremap(void *, size_t, size_t, int, ...);
int munmap(void *, uint64_t);
int mprotect(void *, uint64_t, int) privileged;
int msync(void *, size_t, int);
int mlock(const void *, size_t);
int munlock(const void *, size_t);
void *sbrk(intptr_t);
int brk(void *);
long gethostid(void);
int sethostid(long);
char *getlogin(void);
int getlogin_r(char *, size_t);
int login_tty(int);
int getpagesize(void);
int syncfs(int);
int vhangup(void);
int getdtablesize(void);
int sethostname(const char *, size_t);
int acct(const char *);
void _intsort(int *, size_t);
void _longsort(long *, size_t);
bool _isheap(void *);
int NtGetVersion(void) pureconst;
int _getcpucount(void) pureconst;
long _missingno();
void __oom_hook(size_t);
void _loadxmm(void *);
void _peekall(void);
void _savexmm(void *);
void _weakfree(void *);
int _OpenExecutable(void);
int ftrace_install(void);
int ftrace_enabled(int);
int strace_enabled(int);
long _GetResourceLimit(int);
long _GetMaxFd(void);
char *GetProgramExecutableName(void);
char *GetInterpreterExecutableName(char *, size_t);
void __printargs(const char *);
void __paginate(int, const char *);
int __arg_max(void);
void __print_maps(void);
void __warn_if_powersave(void);
const char *__describe_os(void);
bool _IsDynamicExecutable(const char *);
void _restorewintty(void);
const char *GetCpuidOs(void);
const char *GetCpuidEmulator(void);
void GetCpuidBrand(char[13], uint32_t);
bool IsGenuineBlink(void);
bool IsCygwin(void);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_RUNTIME_H_ */
| 5,061 | 134 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/morph_tls.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "ape/sections.internal.h"
#include "libc/dce.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/morph.h"
#include "libc/thread/tls.h"
typedef char xmm_t __attribute__((__vector_size__(16), __aligned__(1)));
privileged void __morph_tls(void) {
#ifdef __x86_64__
// We need to rewrite SysV _Thread_local code. You MUST use the
// -mno-tls-direct-seg-refs flag which generates code like this
//
// 64 48 8b 0R4 25 00 00 00 00 mov %fs:0,%R
// 64 48 03 0R4 25 00 00 00 00 add %fs:0,%R
//
// Which on Mac we can replace with this:
//
// 65 48 8b 0R4 25 30 00 00 00 mov %gs:0x30,%R
//
// Since we have no idea where the TLS instructions exist in the
// binary, we need to disassemble the whole program image. This'll
// potentially take a few milliseconds for some larger programs.
//
// We check `_tls_content` which is generated by the linker script
// since it lets us determine ahead of time if _Thread_local vars
// have actually been linked into this program.
if (IsWindows() || IsXnu()) {
int n;
uint64_t w;
sigset_t mask;
unsigned m, dis;
unsigned char *p;
__morph_begin(&mask);
if (IsXnu()) {
// Apple is quite straightforward to patch. We basically
// just change the segment register, and the linear slot
// address 0x30 was promised to us, according to Go team
// https://github.com/golang/go/issues/23617
dis = 0x30;
} else {
// MSVC __declspec(thread) generates binary code for this
// %gs:0x1480 abi. So long as TlsAlloc() isn't called >64
// times we should be good.
dis = 0x1480 + __tls_index * 8;
}
// iterate over modifiable code looking for 9 byte instruction
// this would take 30 ms using xed to enable tls on python.com
for (p = _ereal; p + 9 <= __privileged_start; p += n) {
// use sse to zoom zoom to fs register prefixes
// that way it'll take 1 ms to morph python.com
while (p + 9 + 16 <= __privileged_start) {
if ((m = __builtin_ia32_pmovmskb128(
*(xmm_t *)p == (xmm_t){0144, 0144, 0144, 0144, 0144, 0144,
0144, 0144, 0144, 0144, 0144, 0144,
0144, 0144, 0144, 0144}))) {
m = __builtin_ctzll(m);
p += m;
break;
} else {
p += 16;
}
}
// we're checking for the following expression:
// 0144 == p[0] && // %fs
// 0110 == (p[1] & 0373) && // rex.w (and ignore rex.r)
// (0213 == p[2] || // mov reg/mem â reg (word-sized)
// 0003 == p[2]) && // add reg/mem â reg (word-sized)
// 0004 == (p[3] & 0307) && // mod/rm (4,reg,0) means sib â reg
// 0045 == p[4] && // sib (5,4,0) â (rbp,rsp,0) â disp32
// 0000 == p[5] && // displacement (von Neumann endian)
// 0000 == p[6] && // displacement
// 0000 == p[7] && // displacement
// 0000 == p[8] // displacement
w = READ64LE(p) & READ64LE("\377\373\377\307\377\377\377\377");
if ((w == READ64LE("\144\110\213\004\045\000\000\000") ||
w == READ64LE("\144\110\003\004\045\000\000\000")) &&
!p[8]) {
// now change the code
p[0] = 0145; // change %fs to %gs
p[5] = (dis & 0x000000ff) >> 000; // displacement
p[6] = (dis & 0x0000ff00) >> 010; // displacement
p[7] = (dis & 0x00ff0000) >> 020; // displacement
p[8] = (dis & 0xff000000) >> 030; // displacement
// advance to the next instruction
n = 9;
} else {
n = 1;
}
}
__morph_end(&mask);
}
#endif
}
| 5,705 | 122 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/exit.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/runtime.h"
/**
* Exits process with grace.
*
* This calls functions registered by atexit() before terminating
* the current process, and any associated threads. It also calls
* all the legacy linker registered destructors in reversed order
*
* This implementation allows exit() to be called recursively via
* atexit() handlers.
*
* @param exitcode is masked with 255
* @see _Exit()
* @noreturn
*/
wontreturn void exit(int exitcode) {
const uintptr_t *p;
STRACE("exit(%d)", exitcode);
if (_weaken(__cxa_finalize)) {
_weaken(__cxa_finalize)(NULL);
}
for (p = __fini_array_end; p > __fini_array_start;) {
((void (*)(void))(*--p))();
}
#if SupportsWindows()
_Exitr(exitcode);
#else
_Exit(exitcode);
#endif
}
| 2,731 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/daemon.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/nt/enum/processcreationflags.h"
#include "libc/paths.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/o.h"
/**
* Runs process in background.
*
* On Unix this calls fork() and setsid(). On Windows this is
* implemented using CreateProcess(kNtDetachedProcess).
*
* @return 0 on success, or -1 w/ errno
*/
int daemon(int nochdir, int noclose) {
int fd;
switch (_fork(kNtDetachedProcess)) {
case -1:
return -1;
case 0:
break;
default:
_Exit(0);
}
if (!IsWindows()) {
if (setsid() == -1) {
return -1;
}
}
if (!nochdir) {
_unassert(!chdir("/"));
}
if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR)) != -1) {
_unassert(dup2(fd, 0) == 0);
_unassert(dup2(fd, 1) == 1);
_unassert(dup2(fd, 2) == 2);
if (fd > 2) {
_unassert(!close(fd));
}
}
return 0;
}
| 2,846 | 69 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/grow.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=8 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/fmt/conv.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/weaken.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/errfuns.h"
/* TODO(jart): DELETE */
#define GUARANTEE_TERMINATOR 1
#define INITIAL_CAPACITY (32 - GUARANTEE_TERMINATOR)
/**
* Grows array.
* @deprecated favor realloc
*/
bool __grow(void *pp, size_t *capacity, size_t itemsize, size_t extra) {
void **p, *p1, *p2;
size_t n1, n2;
size_t t1, t2;
extra += GUARANTEE_TERMINATOR;
p = (void **)pp;
_unassert(itemsize);
_unassert((*p && *capacity) || (!*p && !*capacity));
_unassert(!_isheap(*p) || ((intptr_t)*p & 15) == 0);
p1 = _isheap(*p) ? *p : NULL;
p2 = NULL;
n1 = *capacity;
n2 = (*p ? n1 + (n1 >> 1) : MAX(4, INITIAL_CAPACITY / itemsize)) + extra;
if (!__builtin_mul_overflow(n1, itemsize, &t1) &&
!__builtin_mul_overflow(n2, itemsize, &t2)) {
if (_weaken(realloc) && (p2 = _weaken(realloc)(p1, ROUNDUP(t2, 32)))) {
if (!p1 && *p) memcpy(p2, *p, t1);
bzero((char *)p2 + t1, t2 - t1);
*capacity = n2;
*p = p2;
return true;
} else {
enomem();
}
} else {
eoverflow();
}
return false;
}
| 3,124 | 67 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/pc.internal.h | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=8 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
â âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ£
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
âââââââââââââ ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
â αcϵαlly pδrÏαblε εxεcµÏαblε § ibm personal computer â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#ifndef COSMOPOLITAN_LIBC_RUNTIME_PC_H_
#define COSMOPOLITAN_LIBC_RUNTIME_PC_H_
#include "libc/runtime/e820.internal.h"
#include "libc/runtime/mman.internal.h"
#define BANE -140737488355328
#define BOOTSIG 0xaa55 /* master boot record signature */
#define PC_BIOS_DATA_AREA 0x400
#define kInterruptFlag (1u << 9)
/* FPU Status Word (x87)
@see Intel Manual V1 §8.1.3
IE: Invalid Operation âââââââââââââââââ
DE: Denormalized Operand ââââââââââââââ
ZE: Zero Divide âââââââââââââââââââââââ
OE: Overflow Flag âââââââââââââââââââââ
UE: Underflow Flag ââââââââââââââââââââ
PE: Precision Flag ââââââââââââââââââââ
SF: Stack Fault âââââââââââââââââââââââ
ES: Exception Summary Status ââââââââââ
C0-3: Condition Codes âââ¬âââââ ââââââââ
TOP of Stack Pointer ââââââ â ââââââââ
B: FPU Busy âââââââââââââ â â ââââââââ
ââââ´âââ¼âââââââââ
âââ ââââââââââââ*/
#define FPU_IE 0b0000000000000000000000001
#define FPU_DE 0b0000000000000000000000010
#define FPU_ZE 0b0000000000000000000000100
#define FPU_OE 0b0000000000000000000001000
#define FPU_UE 0b0000000000000000000010000
#define FPU_PE 0b0000000000000000000100000
#define FPU_SF 0b0000000000000000001000000
#define FPU_C0 0b0000000000000000100000000
#define FPU_C1 0b0000000000000001000000000
#define FPU_C2 0b0000000000000010000000000
#define FPU_C3 0b0000000000100000000000000
#define CR0_PE 0x01 /* protected mode enabled */
#define CR0_MP 0x02 /* monitor coprocessor */
#define CR0_EM 0x04 /* no x87 fpu present if set */
#define CR0_TS 0x08 /* task switched x87 */
#define CR0_ET 0x10 /* extension type 287 or 387 */
#define CR0_NE 0x20 /* enable x87 error reporting */
#define CR0_WP 0x00010000 /* write protect read-only pages @pl0 */
#define CR0_AM 0x00040000 /* alignment mask */
#define CR0_NW 0x20000000 /* global write-through cache disable */
#define CR0_CD 0x40000000 /* global cache disable */
#define CR0_PG 0x80000000 /* paging enabled */
#define CR4_VME 0x01 /* virtual 8086 mode extension */
#define CR4_PVI 0x02 /* protected mode virtual interrupts */
#define CR4_TSD 0x04 /* time stamp disable (rdtsc) */
#define CR4_DE 0x08 /* debugging extensions */
#define CR4_PSE 0x10 /* page size extension */
#define CR4_PAE 0x20 /* physical address extension */
#define CR4_MCE 0x40 /* machine check exception */
#define CR4_PGE 0x80 /* page global enabled */
#define CR4_OSFXSR 0x0200 /* enable SSE and fxsave/fxrestor */
#define CR4_OSXMMEXCPT 0x0400 /* enable unmasked SSE exceptions */
#define CR4_LA57 0x1000 /* enable level-5 paging */
#define CR4_VMXE 0x2000 /* enable VMX operations */
#define CR4_SMXE 0x4000 /* enable SMX operations */
#define CR4_FSGSBASE 0x00010000 /* enable *FSBASE and *GSBASE instructions */
#define CR4_PCIDE 0x00020000 /* enable process-context identifiers */
#define CR4_OSXSAVE 0x00040000 /* enable XSAVE */
#define XCR0_X87 0x01
#define XCR0_SSE 0x02
#define XCR0_AVX 0x04
#define XCR0_BNDREG 0x08
#define XCR0_BNDCSR 0x10
#define XCR0_OPMASK 0x20
#define XCR0_ZMM_HI256 0x40
#define XCR0_HI16_ZMM 0x80
#define EFER 0xc0000080 /* extended feature enable register */
#define EFER_SCE 0x01 /* system call extensions */
#define EFER_LME 0x0100 /* long mode enable */
#define EFER_LMA 0x0400 /* long mode active */
#define EFER_NXE 0x0800 /* no-execute enable */
#define GDT_REAL_CODE 8
#define GDT_REAL_DATA 16
#define GDT_LEGACY_CODE 24
#define GDT_LEGACY_DATA 32
#define GDT_LONG_CODE 40
#define GDT_LONG_DATA 48
#define GDT_LONG_TSS 56
#define PIC1 0x20 /* IO base address for master PIC */
#define PIC2 0xA0 /* IO base address for slave PIC */
#define PIC1_CMD PIC1
#define PIC1_DATA (PIC1 + 1)
#define PIC2_CMD PIC2
#define PIC2_DATA (PIC2 + 1)
#define PIC_EOI 0x20 /* End-of-interrupt command code */
#define PIC_READ_IRR 0x0a /* OCW3 irq ready next CMD read */
#define PIC_READ_ISR 0x0b /* OCW3 irq service next CMD read */
/* Long Mode Paging
@see Intel Manual V.3A §4.1 §4.5
IsValid (ignored on CR3) Vâ
âXD:No Inst. Fetches (if NXE) IsWritable (ignored on CR3) RWââ
â Permit User-Mode Access - uâââ
â Page-level Write-Through - PWTââââ
â Page-level Cache Disable - PCDâââââ
â Set if has been read - Accessedââââââ
â Set if has been written - Dirtyâââââââ
â IsPage 2MB/1GB (if PDPTE/PDE) or PAT (if PT)ââââââââ
â (If this maps page and CR4.PGE) Globalâââââââââ
â (If IsPage 2MB/1GB, see Intel V3A § 11.12) PAT âââââââââ
â â âââââââââ
â ââââââââââââââââââââââââââââââââââââââ⤠âââââââââ
â Must Be 0ââ Next Page Table Address (!IsPage) â âââââââââ
â âââââââââââââââââââââââââââââââââââââââ⤠âââââââââ
â ââ Physical Address 4KB â âââââââââ
âââââââââââââââââââââââââââââââââââââââââââ âignâââââââââ
ââPKââ ign âââ Physical Address 2MB â âââ´ââââââââââ
ââ ââ âââââââââââââââââââââââ â ââ ââââââââââ
ââ ââ âââ Phys. Addr. 1GB â â ââ ââââââââââ
ââ ââ âââ â â ââ ââââââââââ
6666555555555544444444443333333333222222222211111111110000000000
3210987654321098765432109876543210987654321098765432109876543210*/
#define PAGE_V /* */ 0b000000000001
#define PAGE_RW /* */ 0b000000000010
#define PAGE_U /* */ 0b000000000100
#define PAGE_PS /* */ 0b000010000000
#define PAGE_G /* */ 0b000100000000
#define PAGE_IGN1 /* */ 0b111000000000
#define PAGE_RSRV /* blinkenlights/libc reservation */ 0b001000000000
#define PAGE_GROD /* blinkenlights MAP_GROWSDOWN */ 0b010000000000
#define PAGE_TA 0x00007ffffffff000
#define PAGE_PA2 0x00007fffffe00000
#define PAGE_IGN2 0x07f0000000000000
#define PAGE_REFC PAGE_IGN2 /* libc reference counting */
#define PAGE_1REF 0x0010000000000000 /* libc reference counting */
#define PAGE_XD 0x8000000000000000
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#define invlpg(p) asm volatile("invlpg\t(%0)" : : "r"(p) : "memory")
struct IdtDescriptor {
uint16_t offset_1; /* offset bits 0..15 */
uint16_t selector; /* a code segment selector in GDT or LDT */
uint8_t ist; /* bits 0..2 hold stack table offset, rest are zero */
uint8_t type_attr; /* type and attributes */
uint16_t offset_2; /* offset bits 16..31 */
uint32_t offset_3; /* offset bits 32..63 */
uint32_t zero; /* reserved */
};
uint64_t *__get_virtual(struct mman *, uint64_t *, int64_t, bool);
uint64_t __clear_page(uint64_t);
uint64_t __new_page(struct mman *);
uint64_t *__invert_memory_area(struct mman *, uint64_t *, uint64_t, uint64_t,
uint64_t);
void __map_phdrs(struct mman *, uint64_t *, uint64_t, uint64_t);
void __reclaim_boot_pages(struct mman *, uint64_t, uint64_t);
void __ref_page(struct mman *, uint64_t *, uint64_t);
void __ref_pages(struct mman *, uint64_t *, uint64_t, uint64_t);
void __unref_page(struct mman *, uint64_t *, uint64_t);
forceinline unsigned char inb(unsigned short port) {
unsigned char al;
asm volatile("inb\t%1,%0" : "=a"(al) : "dN"(port));
return al;
}
forceinline void outb(unsigned short port, unsigned char byte) {
asm volatile("outb\t%0,%1"
: /* no inputs */
: "a"(byte), "dN"(port));
}
#define __clear_page(page) \
({ \
long di, cx; \
uintptr_t Page = (uintptr_t)(page); \
asm("rep stosb" \
: "=D"(di), "=c"(cx), "=m"(*(char(*)[4096])Page) \
: "0"(Page), "1"(4096), "a"(0)); \
Page; \
})
#define __get_pml4t() \
({ \
intptr_t cr3; \
asm("mov\t%%cr3,%0" : "=r"(cr3)); \
(uint64_t *)(BANE + cr3); \
})
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_PC_H_ */
| 15,539 | 230 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/peekall.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "ape/relocations.h"
#include "libc/macros.internal.h"
// Loads all pages from program image into memory.
_peekall:
.leafprologue
ezlea __executable_start,si
ezlea _etext,cx
add $0x1000,%rsi
0: xor (%rsi),%eax
add $PAGESIZE,%rsi
cmp %rcx,%rsi
jb 0b
ezlea _etext,si
ezlea _end,cx
add $0x1000,%rsi
0: incq (%rsi)
decq (%rsi)
add $PAGESIZE,%rsi
cmp %rcx,%rsi
jb 0b
.leafepilogue
.endfn _peekall,globl
.weak __executable_start
.weak _etext
.weak _end
| 2,312 | 46 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/fpathconf.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/errno.h"
#include "libc/limits.h"
#include "libc/runtime/pathconf.h"
#include "libc/sysv/consts/_posix.h"
#include "libc/sysv/consts/limits.h"
#include "libc/sysv/errfuns.h"
long fpathconf(int fd, int name) {
if (name == _PC_LINK_MAX) return _POSIX_LINK_MAX;
if (name == _PC_MAX_CANON) return _POSIX_MAX_CANON;
if (name == _PC_MAX_INPUT) return _POSIX_MAX_INPUT;
if (name == _PC_NAME_MAX) return NAME_MAX;
if (name == _PC_PATH_MAX) return PATH_MAX;
if (name == _PC_PIPE_BUF) return PIPE_BUF;
if (name == _PC_CHOWN_RESTRICTED) return 1;
if (name == _PC_NO_TRUNC) return 1;
if (name == _PC_VDISABLE) return 0;
if (name == _PC_SYNC_IO) return 1;
if (name == _PC_ASYNC_IO) return -1;
if (name == _PC_PRIO_IO) return -1;
if (name == _PC_SOCK_MAXBUF) return -1;
if (name == _PC_FILESIZEBITS) return FILESIZEBITS;
if (name == _PC_REC_INCR_XFER_SIZE) return 4096;
if (name == _PC_REC_MAX_XFER_SIZE) return 4096;
if (name == _PC_REC_MIN_XFER_SIZE) return 4096;
if (name == _PC_REC_XFER_ALIGN) return 4096;
if (name == _PC_ALLOC_SIZE_MIN) return 4096;
if (name == _PC_SYMLINK_MAX) return -1;
if (name == _PC_2_SYMLINKS) return 1;
return einval();
}
long pathconf(const char *path, int name) {
return fpathconf(-1, name);
}
| 3,112 | 54 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/fesetround.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/runtime/fenv.h"
/**
* Sets rounding mode.
*
* This configures the x87 FPU as well as SSE.
*
* @param mode may be FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, or FE_TOWARDZERO
* @return 0 on success, or -1 on error
*/
int fesetround(int r) {
switch (r) {
case FE_TONEAREST:
case FE_DOWNWARD:
case FE_UPWARD:
case FE_TOWARDZERO:
return __fesetround(r);
default:
return -1;
}
}
| 2,263 | 40 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/progname.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 sw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/macros.internal.h"
// Provides argv[0] The BSD Way.
.initbss 300,_init___progname
__progname:
.quad 0
.endobj __progname,globl,hidden
.previous
.init.start 300,_init___progname
mov %r13,%rax
stosq
.init.end 300,_init___progname
| 2,089 | 32 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/unwind.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_UNWIND_H_
#define COSMOPOLITAN_LIBC_RUNTIME_UNWIND_H_
#define UNW_TDEP_CURSOR_LEN 127
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
typedef enum {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8
} _Unwind_Reason_Code;
typedef uint64_t unw_word_t;
typedef struct unw_cursor {
unw_word_t opaque[UNW_TDEP_CURSOR_LEN];
} unw_cursor_t;
struct _Unwind_Context {
unw_cursor_t cursor;
int end_of_stack;
};
typedef _Unwind_Reason_Code (*_Unwind_Trace_Fn)(struct _Unwind_Context *,
void *);
uintptr_t _Unwind_GetCFA(struct _Unwind_Context *);
uintptr_t _Unwind_GetIP(struct _Unwind_Context *);
_Unwind_Reason_Code _Unwind_Backtrace(_Unwind_Trace_Fn, void *);
void *_Unwind_FindEnclosingFunction(void *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_UNWIND_H_ */
| 1,124 | 43 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/wipe.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2023 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/nexgen32e/x86feature.h"
#include "libc/macros.internal.h"
// Zeroes as many registers as possible.
//
// Each caller should declare an appropriate prototype.
//
// @param is return value
// @return is copied from parameter
__wipe:
#ifdef __x86_64__
mov %rdi,%rax
xor %edi,%edi
xor %esi,%esi
xor %edx,%edx
xor %ecx,%ecx
xor %r8d,%r8d
xor %r9d,%r9d
xor %r10d,%r10d
xor %r11d,%r11d
testb X86_HAVE(AVX)+kCpuids(%rip)
jz .Lsse
vpxor %xmm0,%xmm0,%xmm0
vpxor %xmm1,%xmm1,%xmm1
vpxor %xmm2,%xmm2,%xmm2
vpxor %xmm3,%xmm3,%xmm3
vpxor %xmm4,%xmm4,%xmm4
vpxor %xmm5,%xmm5,%xmm5
vpxor %xmm6,%xmm6,%xmm6
vpxor %xmm7,%xmm7,%xmm7
ret
.Lsse: xorps %xmm0,%xmm0
xorps %xmm1,%xmm1
xorps %xmm2,%xmm2
xorps %xmm3,%xmm3
xorps %xmm4,%xmm4
xorps %xmm5,%xmm5
xorps %xmm6,%xmm6
xorps %xmm7,%xmm7
ret
#elif defined(__aarch64__)
mov x1,#0
mov x2,#0
mov x3,#0
mov x4,#0
mov x5,#0
mov x6,#0
mov x7,#0
mov x9,#0
mov x10,#0
mov x11,#0
mov x12,#0
mov x13,#0
mov x14,#0
mov x15,#0
movi v0.16b,#0
movi v1.16b,#0
movi v2.16b,#0
movi v3.16b,#0
movi v4.16b,#0
movi v5.16b,#0
movi v6.16b,#0
movi v7.16b,#0
ret
#endif
.endfn __wipe,globl,hidden
| 3,008 | 85 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/clone.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/sysv/consts/clone.h"
#include "libc/assert.h"
#include "libc/atomic.h"
#include "libc/calls/calls.h"
#include "libc/calls/struct/ucontext-netbsd.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/intrin/asan.internal.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
#include "libc/nt/runtime.h"
#include "libc/nt/synchronization.h"
#include "libc/nt/thread.h"
#include "libc/nt/thunk/msabi.h"
#include "libc/runtime/clone.internal.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/syslib.internal.h"
#include "libc/sock/internal.h"
#include "libc/stdalign.internal.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/futex.h"
#include "libc/sysv/consts/nr.h"
#include "libc/sysv/consts/nrlinux.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/freebsd.internal.h"
#include "libc/thread/openbsd.internal.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
#include "libc/thread/tls2.h"
#include "libc/thread/xnu.internal.h"
#define kMaxThreadIds 32768
#define kMinThreadId 262144
#define __NR_thr_new 455
#define __NR_clone_linux 56
#define __NR__lwp_create 309
#define __NR_getcontext_netbsd 307
#define __NR_bsdthread_create 0x02000168
#define __NR_thread_fast_set_cthread_self 0x03000003
#define PTHREAD_START_CUSTOM_XNU 0x01000000
#define LWP_DETACHED 0x00000040
#define LWP_SUSPENDED 0x00000080
struct CloneArgs {
_Alignas(16) union {
struct {
int tid;
int this;
};
uint32_t utid;
int64_t tid64;
};
int *ptid;
int *ctid;
int *ztid;
char *tls;
int (*func)(void *, int);
void *arg;
};
static struct CloneArgs *AllocateCloneArgs(char *stk, size_t stksz) {
return (struct CloneArgs *)(((uintptr_t)(stk + stksz) -
sizeof(struct CloneArgs)) &
-16);
}
#ifdef __x86_64__
////////////////////////////////////////////////////////////////////////////////
// THE NEW TECHNOLOGY
__msabi extern typeof(TlsSetValue) *const __imp_TlsSetValue;
__msabi extern typeof(ExitThread) *const __imp_ExitThread;
__msabi extern typeof(WakeByAddressAll) *const __imp_WakeByAddressAll;
int WinThreadLaunch(void *arg, // rdi
int tid, // rsi
int (*func)(void *, int), // rdx
intptr_t rsp); // rcx
// we can't log this function because:
// 1. windows owns the backtrace pointer right now
// 2. ftrace unwinds rbp to determine depth
// 3. tid in tls for ftrace isn't set yet
// we can't use address sanitizer because:
// 1. __asan_handle_no_return wipes stack
// 2. windows owns the stack memory right now
// we need win32 raw imports because:
// 1. generated thunks are function logged
noasan noinstrument static textwindows wontreturn void //
WinThreadEntry(int rdi, // rcx
int rsi, // rdx
int rdx, // r8
struct CloneArgs *wt) { // r9
int rc;
if (wt->tls) __set_tls_win32(wt->tls);
*wt->ctid = wt->tid;
rc = WinThreadLaunch(wt->arg, wt->tid, wt->func, (intptr_t)wt);
// we can now clear ctid directly since we're no longer using our own
// stack memory, which can now be safely free'd by the parent thread.
*wt->ztid = 0;
__imp_WakeByAddressAll(wt->ztid);
// since we didn't indirect this function through NT2SYSV() it's not
// safe to simply return, and as such, we need ExitThread().
__imp_ExitThread(rc);
notpossible;
}
static textwindows errno_t CloneWindows(int (*func)(void *, int), char *stk,
size_t stksz, int flags, void *arg,
void *tls, int *ptid, int *ctid) {
int64_t h;
struct CloneArgs *wt;
wt = AllocateCloneArgs(stk, stksz);
wt->ctid = flags & CLONE_CHILD_SETTID ? ctid : &wt->tid;
wt->ztid = flags & CLONE_CHILD_CLEARTID ? ctid : &wt->tid;
wt->func = func;
wt->arg = arg;
wt->tls = flags & CLONE_SETTLS ? tls : 0;
if ((h = CreateThread(0, 4096, (void *)WinThreadEntry, wt, 0, &wt->utid))) {
CloseHandle(h);
if (flags & CLONE_PARENT_SETTID) {
*ptid = wt->tid;
}
return 0;
} else {
return __dos2errno(GetLastError());
}
}
////////////////////////////////////////////////////////////////////////////////
// XNU'S NOT UNIX
void XnuThreadThunk(void *pthread, // rdi x0
int machport, // rsi x1
void *(*func)(void *), // rdx x2
void *arg, // rcx x3
intptr_t *stack, // r8 x4
unsigned xnuflags); // r9 x5
asm("XnuThreadThunk:\n\t"
"xor\t%ebp,%ebp\n\t"
"mov\t%r8,%rsp\n\t"
"push\t%rax\n\t"
"jmp\tXnuThreadMain\n\t"
".size\tXnuThreadThunk,.-XnuThreadThunk");
__attribute__((__used__, __no_reorder__))
static wontreturn void
XnuThreadMain(void *pthread, // rdi
int tid, // rsi
int (*func)(void *arg, int tid), // rdx
void *arg, // rcx
struct CloneArgs *wt, // r8
unsigned xnuflags) { // r9
int ax;
wt->tid = tid;
*wt->ctid = tid;
*wt->ptid = tid;
if (wt->tls) {
// XNU uses the same 0x30 offset as the WIN32 TIB x64. They told the
// Go team at Google that they Apply stands by our ability to use it
// https://github.com/golang/go/issues/23617#issuecomment-376662373
asm volatile("syscall"
: "=a"(ax)
: "0"(__NR_thread_fast_set_cthread_self), "D"(wt->tls - 0x30)
: "rcx", "rdx", "r8", "r9", "r10", "r11", "memory", "cc");
}
func(arg, tid);
// we no longer use the stack after this point
// %rax = int bsdthread_terminate(%rdi = void *stackaddr,
// %rsi = size_t freesize,
// %rdx = uint32_t port,
// %r10 = uint32_t sem);
asm volatile("movl\t$0,%0\n\t" // *wt->ztid = 0
"xor\t%%r10d,%%r10d\n\t" // sem = 0
"syscall" // __bsdthread_terminate()
: "=m"(*wt->ztid)
: "a"(0x2000000 | 361), "D"(0), "S"(0), "d"(0L)
: "rcx", "r10", "r11", "memory");
notpossible;
}
static errno_t CloneXnu(int (*fn)(void *), char *stk, size_t stksz, int flags,
void *arg, void *tls, int *ptid, int *ctid) {
int rc;
bool failed;
static bool once;
struct CloneArgs *wt;
if (!once) {
_npassert(sys_bsdthread_register(XnuThreadThunk, 0, 0, 0, 0, 0, 0) != -1);
once = true;
}
wt = AllocateCloneArgs(stk, stksz);
wt->ptid = flags & CLONE_PARENT_SETTID ? ptid : &wt->tid;
wt->ctid = flags & CLONE_CHILD_SETTID ? ctid : &wt->tid;
wt->ztid = flags & CLONE_CHILD_CLEARTID ? ctid : &wt->tid;
wt->tls = flags & CLONE_SETTLS ? tls : 0;
return sys_clone_xnu(fn, arg, wt, 0, PTHREAD_START_CUSTOM_XNU);
}
////////////////////////////////////////////////////////////////////////////////
// FREE BESIYATA DISHMAYA
static wontreturn void FreebsdThreadMain(void *p) {
struct CloneArgs *wt = p;
*wt->ctid = wt->tid;
wt->func(wt->arg, wt->tid);
// we no longer use the stack after this point
// void thr_exit(%rdi = long *state);
asm volatile("movl\t$0,%0\n\t" // *wt->ztid = 0
"syscall\n\t" // _umtx_op(wt->ztid, WAKE, INT_MAX)
"movl\t$431,%%eax\n\t" // thr_exit(long *nonzeroes_and_wake)
"xor\t%%edi,%%edi\n\t" // sad we can't use this free futex op
"syscall\n\t" // exit1() fails if thread is orphaned
"movl\t$1,%%eax\n\t" // exit()
"syscall" //
: "=m"(*wt->ztid)
: "a"(454), "D"(wt->ztid), "S"(UMTX_OP_WAKE), "d"(INT_MAX)
: "rcx", "r8", "r9", "r10", "r11", "memory");
notpossible;
}
static errno_t CloneFreebsd(int (*func)(void *, int), char *stk, size_t stksz,
int flags, void *arg, void *tls, int *ptid,
int *ctid) {
int ax;
bool failed;
int64_t tid;
struct CloneArgs *wt;
wt = AllocateCloneArgs(stk, stksz);
wt->ctid = flags & CLONE_CHILD_SETTID ? ctid : &wt->tid;
wt->ztid = flags & CLONE_CHILD_CLEARTID ? ctid : &wt->tid;
wt->tls = tls;
wt->func = func;
wt->arg = arg;
struct thr_param params = {
.start_func = FreebsdThreadMain,
.arg = wt,
.stack_base = stk,
.stack_size = (uintptr_t)wt - (uintptr_t)stk,
.tls_base = flags & CLONE_SETTLS ? tls : 0,
.tls_size = 64,
.child_tid = &wt->tid64,
.parent_tid = &tid,
};
asm volatile(CFLAG_ASM("syscall")
: CFLAG_CONSTRAINT(failed), "=a"(ax)
: "1"(__NR_thr_new), "D"(¶ms), "S"(sizeof(params))
: "rcx", "rdx", "r8", "r9", "r10", "r11", "memory");
if (failed) return ax;
if (flags & CLONE_PARENT_SETTID) *ptid = tid;
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// OPEN BESIYATA DISHMAYA
// we can't use address sanitizer because:
// 1. __asan_handle_no_return wipes stack [todo?]
noasan static wontreturn void OpenbsdThreadMain(void *p) {
struct CloneArgs *wt = p;
*wt->ctid = wt->tid;
wt->func(wt->arg, wt->tid);
asm volatile("mov\t%2,%%rsp\n\t" // so syscall can validate stack exists
"movl\t$0,(%%rdi)\n\t" // *wt->ztid = 0 (old stack now free'd)
"syscall\n\t" // futex(int*, op, val) will wake wait0
"xor\t%%edi,%%edi\n\t" // so kernel doesn't write to old stack
"mov\t$302,%%eax\n\t" // __threxit(int *notdead) doesn't wake
"syscall"
: "=m"(*wt->ztid)
: "a"(83), "m"(__oldstack), "D"(wt->ztid),
"S"(2 /* FUTEX_WAKE */), "d"(INT_MAX)
: "rcx", "r11", "memory");
notpossible;
}
static errno_t CloneOpenbsd(int (*func)(void *, int), char *stk, size_t stksz,
int flags, void *arg, void *tls, int *ptid,
int *ctid) {
int rc;
intptr_t sp;
struct __tfork *tf;
struct CloneArgs *wt;
sp = (intptr_t)stk + stksz;
sp -= sizeof(struct __tfork);
sp &= -alignof(struct __tfork);
tf = (struct __tfork *)sp;
sp -= sizeof(struct CloneArgs);
sp &= -alignof(struct CloneArgs);
wt = (struct CloneArgs *)sp;
wt->ctid = flags & CLONE_CHILD_SETTID ? ctid : &wt->tid;
wt->ztid = flags & CLONE_CHILD_CLEARTID ? ctid : &wt->tid;
wt->arg = arg;
wt->func = func;
tf->tf_stack = (char *)wt - 8;
tf->tf_tcb = flags & CLONE_SETTLS ? tls : 0;
tf->tf_tid = &wt->tid;
if ((rc = __tfork_thread(tf, sizeof(*tf), OpenbsdThreadMain, wt)) >= 0) {
_npassert(rc);
if (flags & CLONE_PARENT_SETTID) {
*ptid = rc;
}
return 0;
} else {
return -rc;
}
}
////////////////////////////////////////////////////////////////////////////////
// NET BESIYATA DISHMAYA
static wontreturn void NetbsdThreadMain(void *arg, // rdi
int (*func)(void *, int), // rsi
int *tid, // rdx
int *ctid, // rcx
int *ztid) { // r9
int ax, dx;
// TODO(jart): Why are we seeing flakes where *tid is zero?
// ax = *tid;
ax = sys_gettid();
*ctid = ax;
func(arg, ax);
// we no longer use the stack after this point
// %eax = int __lwp_exit(void);
asm volatile("movl\t$0,%2\n\t" // *wt->ztid = 0
"syscall" // __lwp_exit()
: "=a"(ax), "=d"(dx), "=m"(*ztid)
: "0"(310)
: "rcx", "r11", "memory");
notpossible;
}
static int CloneNetbsd(int (*func)(void *, int), char *stk, size_t stksz,
int flags, void *arg, void *tls, int *ptid, int *ctid) {
// NetBSD has its own clone() and it works, but it's technically a
// second-class API, intended to help Linux folks migrate to this.
bool failed;
int ax, *tid;
intptr_t dx, sp;
static bool once;
struct ucontext_netbsd *ctx;
static struct ucontext_netbsd netbsd_clone_template;
// memoize arbitrary valid processor state structure
if (!once) {
asm volatile(CFLAG_ASM("syscall")
: CFLAG_CONSTRAINT(failed), "=a"(ax)
: "1"(__NR_getcontext_netbsd), "D"(&netbsd_clone_template)
: "rcx", "rdx", "r8", "r9", "r10", "r11", "memory");
_npassert(!failed);
once = true;
}
sp = (intptr_t)(stk + stksz);
// allocate memory for tid
sp -= sizeof(int);
sp = sp & -alignof(int);
tid = (int *)sp;
*tid = 0;
// align the stack
sp = sp & -16;
// simulate call to misalign stack and ensure backtrace looks good
sp -= 8;
*(intptr_t *)sp = (intptr_t)CloneNetbsd + 1;
// place the giant 784 byte ucontext structure in the red zone!
// it only has to live long enough for the thread to come alive
ctx = (struct ucontext_netbsd *)((sp - sizeof(struct ucontext_netbsd)) &
-alignof(struct ucontext_netbsd));
// pass parameters in process state
memcpy(ctx, &netbsd_clone_template, sizeof(*ctx));
ctx->uc_link = 0;
ctx->uc_mcontext.rbp = 0;
ctx->uc_mcontext.rsp = sp;
ctx->uc_mcontext.rip = (intptr_t)NetbsdThreadMain;
ctx->uc_mcontext.rdi = (intptr_t)arg;
ctx->uc_mcontext.rsi = (intptr_t)func;
ctx->uc_mcontext.rdx = (intptr_t)tid;
ctx->uc_mcontext.rcx = (intptr_t)(flags & CLONE_CHILD_SETTID ? ctid : tid);
ctx->uc_mcontext.r8 = (intptr_t)(flags & CLONE_CHILD_CLEARTID ? ctid : tid);
ctx->uc_flags |= _UC_STACK;
ctx->uc_stack.ss_sp = stk;
ctx->uc_stack.ss_size = stksz;
ctx->uc_stack.ss_flags = 0;
if (flags & CLONE_SETTLS) {
ctx->uc_flags |= _UC_TLSBASE;
ctx->uc_mcontext._mc_tlsbase = (intptr_t)tls;
}
// perform the system call
asm volatile(CFLAG_ASM("syscall")
: CFLAG_CONSTRAINT(failed), "=a"(ax), "=d"(dx)
: "1"(__NR__lwp_create), "D"(ctx), "S"(LWP_DETACHED), "2"(tid)
: "rcx", "r8", "r9", "r10", "r11", "memory");
if (!failed) {
_npassert(*tid);
if (flags & CLONE_PARENT_SETTID) {
*ptid = *tid;
}
return 0;
} else {
return ax;
}
}
#endif /* __x86_64__ */
#ifdef __aarch64__
////////////////////////////////////////////////////////////////////////////////
// APPLE SILICON
static void *SiliconThreadMain(void *arg) {
register struct CloneArgs *wt asm("x21") = arg;
*wt->ctid = wt->this;
register void *x0 asm("x0") = wt->arg;
register int x1 asm("w1") = wt->this;
register void *x28 asm("x28") = wt->tls;
asm volatile("mov\tx19,x29\n\t" // save frame pointer
"mov\tx20,sp\n\t" // save stack pointer
"mov\tx29,#0\n\t" // reset backtrace
"mov\tsp,%3\n\t" // switch stack
"blr\t%2\n\t" // wt->func(wt->arg, tid)
"mov\tx29,x19\n\t" // restore frame pointer
"mov\tsp,x20" // restore stack pointer
: "+r"(x0)
: "r"(x1), "r"(wt->func), "r"(wt), "r"(x28)
: "x19", "x20", "memory");
*wt->ztid = 0;
return 0;
}
static errno_t CloneSilicon(int (*fn)(void *, int), char *stk, size_t stksz,
int flags, void *arg, void *tls, int *ptid,
int *ctid) {
errno_t res;
unsigned tid;
pthread_t th;
struct CloneArgs *wt;
static atomic_uint tids;
wt = AllocateCloneArgs(stk, stksz);
tid = atomic_fetch_add_explicit(&tids, 1, memory_order_acq_rel);
wt->this = tid = (tid & (kMaxThreadIds - 1)) + kMinThreadId;
wt->ctid = flags & CLONE_CHILD_SETTID ? ctid : &wt->tid;
wt->ztid = flags & CLONE_CHILD_CLEARTID ? ctid : &wt->tid;
wt->tls = flags & CLONE_SETTLS ? tls : 0;
wt->func = fn;
wt->arg = arg;
if (!(res = __syslib->pthread_create(&th, 0, SiliconThreadMain, wt)) &&
(flags & CLONE_PARENT_SETTID)) {
*ptid = tid;
}
return res;
}
#endif /* __aarch64__ */
////////////////////////////////////////////////////////////////////////////////
// GNU/SYSTEMD
int sys_clone_linux(int flags, // rdi
long sp, // rsi
int *ptid, // rdx
int *ctid, // rcx
void *tls, // r8
void *func, // r9
void *arg); // 8(rsp)
static int CloneLinux(int (*func)(void *arg, int rc), char *stk, size_t stksz,
int flags, void *arg, void *tls, int *ptid, int *ctid) {
int rc;
long sp;
sp = (intptr_t)(stk + stksz);
if (~flags & CLONE_CHILD_SETTID) {
flags |= CLONE_CHILD_SETTID;
sp -= sizeof(int);
sp = sp & -alignof(int);
ctid = (int *)sp;
sp -= 8; // experiment
}
// align the stack
#ifdef __aarch64__
sp = sp & -128; // for kernel 4.6 and earlier
#else
sp = sp & -16;
#endif
if ((rc = sys_clone_linux(flags, sp, ptid, ctid, tls, func, arg)) >= 0) {
// clone() is documented as setting ptid before return
return 0;
} else {
return -rc;
}
}
////////////////////////////////////////////////////////////////////////////////
// COSMOPOLITAN
/**
* Creates thread without malloc being linked.
*
* If you use clone() you're on you're own, e.g.
*
* int worker(void *arg) { return 0; }
* struct CosmoTib tib = {.tib_self = &tib, .tib_tid = -1};
* atomic_int tid;
* char *stk = _mapstack();
* clone(worker, stk, GetStackSize() - 16,
* CLONE_VM | CLONE_THREAD | CLONE_FS | CLONE_FILES |
* CLONE_SYSVSEM | CLONE_SIGHAND | CLONE_PARENT_SETTID |
* CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS,
* arg, &tid, &tib, &tib.tib_tid);
* while (atomic_load(&tid) == 0) sched_yield();
* // thread is known
* while (atomic_load(&tib.tib_tid) < 0) sched_yield();
* // thread is running
* while (atomic_load(&tib.tib_tid) > 0) sched_yield();
* // thread has terminated
* _freestack(stk);
*
* Threads are created in a detached manner. They currently can't be
* synchronized using wait() or posix signals. Threads created by this
* function should be synchronized using shared memory operations.
*
* Any memory that's required by this system call wrapper is allocated
* to the top of your stack. This shouldn't be more than 128 bytes.
*
* Your function is called from within the stack you specify. A return
* address is pushed onto your stack, that causes returning to jump to
* _Exit1() which terminates the thread. Even though the callback says
* it supports a return code, that'll only work on Linux and Windows.
*
* This function follows the same ABI convention as the Linux userspace
* libraries, with a few small changes. The varargs has been removed to
* help prevent broken code, and the stack size and tls size parameters
* are introduced for compatibility with FreeBSD.
*
* To keep this system call lightweight, only the thread creation use
* case is polyfilled across platforms. For example, if you want fork
* that works on OpenBSD for example, don't do it with clone(SIGCHLD)
* and please just call fork(). Even if you do that on Linux, it will
* effectively work around libc features like atfork(), so that means
* other calls like getpid() may return incorrect values.
*
* @param func is your callback function, which this wrapper requires
* not be null, otherwise EINVAL is raised. It is passed two args
* within the child thread: (1) the caller-supplied `arg` and (2)
* the new tid is always passed in the second arg for convenience
*
* @param stk points to the bottom of a caller allocated stack, which
* must be allocated via mmap() using the MAP_STACK flag, or else
* you won't get optimal performance and it won't work on OpenBSD
*
* @param stksz is the size of that stack in bytes, we recommend that
* that this be set to GetStackSize() or else memory safety tools
* like kprintf() can't do as good and quick of a job; this value
* must be 16-aligned plus it must be at least 4192 bytes in size
* and it's advised to have the bottom-most page, be a guard page
*
* @param flags which SHOULD always have all of these flags:
*
* - `CLONE_THREAD`
* - `CLONE_VM`
* - `CLONE_FS`
* - `CLONE_FILES`
* - `CLONE_SIGHAND`
* - `CLONE_SYSVSEM`
*
* This system call wrapper is intended for threads, and as such, we
* won't polyfill Linux's ability to simulate unrelated calls (e.g.
* fork, vfork) via clone() on other platforms. Please just call
* fork() and vfork() when that's what you want.
*
* Your `flags` may also optionally also additionally bitwise-OR any
* combination of the following additional flags:
*
* - `CLONE_CHILD_SETTID` must be specified if you intend to set the
* `ctid` argument, which will updated with the child tid once the
* child has started.
*
* - `CLONE_PARENT_SETTID` must be specified if you intend to set
* the `ptid` argument, which is updated at the most opportune
* moment. On all platforms except XNU, this happens before
* clone() returns. On XNU, it happens once the thread starts.
*
* - `CLONE_CHILD_CLEARTID` causes `*ctid = 0` upon child thread
* termination. This is used to implement join so that the parent
* may know when it's safe to free the child's stack memory, and
* as such, is guaranteed to happen AFTER the child thread has
* either terminated or has finished using its stack memory
*
* - `CLONE_SETTLS` is needed if you intend to specify the `tls`
* argument, which after thread creation may be accessed using
* __get_tls(). Doing this means that `errno`, gettid(), etc.
* correctly work. Caveat emptor if you choose not to do this.
*
* @param arg is passed as an argument to `func` in the child thread
* @param tls may be used to set the thread local storage segment;
* this parameter is ignored if `CLONE_SETTLS` is not set
* @param ctid lets the child receive its thread id without having to
* call gettid() and is ignored if `CLONE_CHILD_SETTID` isn't set
* @return 0 on success, or errno on errno
* @threadsafe
*/
errno_t clone(void *func, void *stk, size_t stksz, int flags, void *arg,
void *ptid, void *tls, void *ctid) {
int rc;
if (flags & CLONE_THREAD) {
__enable_threads();
}
if (!func) {
rc = EINVAL;
} else if (!IsTiny() &&
((flags & CLONE_VM) && (stksz < PAGESIZE || (stksz & 15)))) {
rc = EINVAL;
} else if (IsAsan() &&
(((flags & CLONE_SETTLS) && !__asan_is_valid(tls, 64)) ||
((flags & CLONE_PARENT_SETTID) &&
!__asan_is_valid(ptid, sizeof(int))) ||
((flags & CLONE_CHILD_SETTID) &&
!__asan_is_valid(ctid, sizeof(int))))) {
rc = EFAULT;
} else if (IsLinux()) {
rc = CloneLinux(func, stk, stksz, flags, arg, tls, ptid, ctid);
} else if (!IsTiny() &&
(flags & ~(CLONE_SETTLS | CLONE_PARENT_SETTID |
CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID)) !=
(CLONE_THREAD | CLONE_VM | CLONE_FS | CLONE_FILES |
CLONE_SIGHAND | CLONE_SYSVSEM)) {
STRACE("cosmo clone() is picky about flags, see clone.c");
rc = EINVAL;
} else if (IsXnu()) {
#ifdef __x86_64__
rc = CloneXnu(func, stk, stksz, flags, arg, tls, ptid, ctid);
#elif defined(__aarch64__)
rc = CloneSilicon(func, stk, stksz, flags, arg, tls, ptid, ctid);
#else
#error "unsupported architecture"
#endif
#ifdef __x86_64__
} else if (IsFreebsd()) {
rc = CloneFreebsd(func, stk, stksz, flags, arg, tls, ptid, ctid);
} else if (IsNetbsd()) {
rc = CloneNetbsd(func, stk, stksz, flags, arg, tls, ptid, ctid);
} else if (IsOpenbsd()) {
rc = CloneOpenbsd(func, stk, stksz, flags, arg, tls, ptid, ctid);
} else if (IsWindows()) {
rc = CloneWindows(func, stk, stksz, flags, arg, tls, ptid, ctid);
#endif /* __x86_64__ */
} else {
rc = ENOSYS;
}
STRACE("clone(%t, %p, %'zu, %#x, %p, %p, %p, %p) â %s", func, stk, stksz,
flags, arg, ptid, tls, ctid, DescribeErrno(rc));
return rc;
}
| 26,808 | 690 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/syslib.internal.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_SYSLIB_H_
#define COSMOPOLITAN_LIBC_RUNTIME_SYSLIB_H_
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/sigset.h"
#include "libc/calls/struct/timespec.h"
#include "libc/thread/thread.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/**
* @fileoverview System DSO interfaces provided by APE loader.
*
* These functions are owned by the platform C library. Regardless of
* platform, POSIX APIs returning `long` will follow the Linux Kernel
* `-errno` convention, and hence should be wrapped with `_sysret()`.
*/
#define SYSLIB_MAGIC ('s' | 'l' << 8 | 'i' << 16 | 'b' << 24)
#define SYSLIB_VERSION 1
typedef uint64_t dispatch_time_t;
typedef uint64_t dispatch_semaphore_t;
struct Syslib {
int magic;
int version;
long (*fork)(void);
long (*pipe)(int[2]);
long (*clock_gettime)(int, struct timespec *);
long (*nanosleep)(const struct timespec *, struct timespec *);
long (*mmap)(void *, size_t, int, int, int, int64_t);
int (*pthread_jit_write_protect_supported_np)(void);
void (*pthread_jit_write_protect_np)(int);
void (*sys_icache_invalidate)(void *, size_t);
int (*pthread_create)(pthread_t *, const pthread_attr_t *, void *(*)(void *),
void *);
void (*pthread_exit)(void *);
int (*pthread_kill)(pthread_t, int);
int (*pthread_sigmask)(int, const sigset_t *restrict, sigset_t *restrict);
int (*pthread_setname_np)(const char *);
dispatch_semaphore_t (*dispatch_semaphore_create)(long);
long (*dispatch_semaphore_signal)(dispatch_semaphore_t);
long (*dispatch_semaphore_wait)(dispatch_semaphore_t, dispatch_time_t);
dispatch_time_t (*dispatch_walltime)(const struct timespec *, int64_t);
};
extern struct Syslib *__syslib;
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_SYSLIB_H_ */
| 1,881 | 52 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/fork-nt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/internal.h"
#include "libc/calls/ntspawn.h"
#include "libc/calls/state.internal.h"
#include "libc/calls/syscall-nt.internal.h"
#include "libc/calls/syscall_support-nt.internal.h"
#include "libc/calls/wincrash.internal.h"
#include "libc/errno.h"
#include "libc/fmt/itoa.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/directmap.internal.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/weaken.h"
#include "libc/macros.internal.h"
#include "libc/mem/alloca.h"
#include "libc/mem/mem.h"
#include "libc/nexgen32e/nt2sysv.h"
#include "libc/nt/console.h"
#include "libc/nt/createfile.h"
#include "libc/nt/enum/accessmask.h"
#include "libc/nt/enum/creationdisposition.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/filemapflags.h"
#include "libc/nt/enum/pageflags.h"
#include "libc/nt/enum/processcreationflags.h"
#include "libc/nt/enum/startf.h"
#include "libc/nt/ipc.h"
#include "libc/nt/memory.h"
#include "libc/nt/process.h"
#include "libc/nt/runtime.h"
#include "libc/nt/signals.h"
#include "libc/nt/struct/ntexceptionpointers.h"
#include "libc/runtime/internal.h"
#include "libc/runtime/memtrack.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/prot.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/tls.h"
#ifdef __x86_64__
STATIC_YOINK("_check_sigchld");
extern int64_t __wincrashearly;
bool32 __onntconsoleevent_nt(uint32_t);
void kmalloc_unlock(void);
static textwindows wontreturn void AbortFork(const char *func) {
STRACE("fork() %s() failed %d", func, GetLastError());
ExitProcess(177);
}
static textwindows char16_t *ParseInt(char16_t *p, int64_t *x) {
*x = 0;
while (*p == ' ') p++;
while ('0' <= *p && *p <= '9') {
*x *= 10;
*x += *p++ - '0';
}
return p;
}
static inline textwindows ssize_t ForkIo(int64_t h, char *p, size_t n,
bool32 (*f)()) {
size_t i;
uint32_t x;
for (i = 0; i < n; i += x) {
if (!f(h, p + i, n - i, &x, NULL)) {
return __winerr();
}
}
return i;
}
static dontinline textwindows bool ForkIo2(int64_t h, void *buf, size_t n,
bool32 (*fn)(), const char *sf,
bool ischild) {
ssize_t rc = ForkIo(h, buf, n, fn);
if (ischild) __tls_enabled_set(false); // prevent tls crash in kprintf
NTTRACE("%s(%ld, %p, %'zu) â %'zd% m", sf, h, buf, n, rc);
return rc != -1;
}
static dontinline textwindows bool WriteAll(int64_t h, void *buf, size_t n) {
return ForkIo2(h, buf, n, WriteFile, "WriteFile", false);
}
static textwindows dontinline void ReadOrDie(int64_t h, void *buf, size_t n) {
if (!ForkIo2(h, buf, n, ReadFile, "ReadFile", true)) {
AbortFork("ReadFile");
}
}
static textwindows int64_t MapOrDie(uint32_t prot, uint64_t size) {
int64_t h;
if ((h = CreateFileMapping(-1, 0, prot, size >> 32, size, 0))) {
return h;
} else {
AbortFork("MapOrDie");
}
}
static textwindows void ViewOrDie(int64_t h, uint32_t access, size_t pos,
size_t size, void *base) {
void *got;
got = MapViewOfFileEx(h, access, pos >> 32, pos, size, base);
if (!got || (base && got != base)) {
AbortFork("ViewOrDie");
}
}
static textwindows int OnForkCrash(struct NtExceptionPointers *ep) {
kprintf("error: fork() child crashed!%n"
"\tExceptionCode = %#x%n"
"\tRip = %x%n",
ep->ExceptionRecord->ExceptionCode,
ep->ContextRecord ? ep->ContextRecord->Rip : -1);
ExitProcess(73);
}
textwindows void WinMainForked(void) {
bool ok;
jmp_buf jb;
int64_t reader;
char *addr, *shad;
struct DirectMap dm;
uint64_t size, upsize;
int64_t oncrash, savetsc;
struct MemoryInterval *maps;
char16_t fvar[21 + 1 + 21 + 1];
uint32_t i, varlen, oldprot, savepid;
long mapcount, mapcapacity, specialz;
// check to see if the process was actually forked
// this variable should have the pipe handle numba
varlen = GetEnvironmentVariable(u"_FORK", fvar, ARRAYLEN(fvar));
if (!varlen || varlen >= ARRAYLEN(fvar)) return;
NTTRACE("WinMainForked()");
SetEnvironmentVariable(u"_FORK", NULL);
#ifdef SYSDEBUG
oncrash = AddVectoredExceptionHandler(1, NT2SYSV(OnForkCrash));
#endif
ParseInt(fvar, &reader);
// read the cpu state from the parent process & plus
// read the list of mappings from the parent process
// this is stored in a special secretive memory map!
// read ExtendMemoryIntervals for further details :|
maps = (void *)kMemtrackStart;
ReadOrDie(reader, jb, sizeof(jb));
ReadOrDie(reader, &mapcount, sizeof(_mmi.i));
ReadOrDie(reader, &mapcapacity, sizeof(_mmi.n));
specialz = ROUNDUP(mapcapacity * sizeof(_mmi.p[0]), kMemtrackGran);
ViewOrDie(MapOrDie(kNtPageReadwrite, specialz), kNtFileMapWrite, 0, specialz,
maps);
ReadOrDie(reader, maps, mapcount * sizeof(_mmi.p[0]));
if (IsAsan()) {
shad = (char *)(((intptr_t)maps >> 3) + 0x7fff8000);
size = ROUNDUP(specialz >> 3, FRAMESIZE);
ViewOrDie(MapOrDie(kNtPageReadwrite, size), kNtFileMapWrite, 0, size, maps);
ReadOrDie(reader, shad, (mapcount * sizeof(_mmi.p[0])) >> 3);
}
// read the heap mappings from the parent process
for (i = 0; i < mapcount; ++i) {
addr = (char *)((uint64_t)maps[i].x << 16);
size = maps[i].size;
if ((maps[i].flags & MAP_TYPE) != MAP_SHARED) {
upsize = ROUNDUP(size, FRAMESIZE);
// we don't need to close the map handle because sys_mmap_nt
// doesn't mark it inheritable across fork() for MAP_PRIVATE
ViewOrDie((maps[i].h = MapOrDie(kNtPageExecuteReadwrite, upsize)),
kNtFileMapWrite | kNtFileMapExecute, 0, upsize, addr);
ReadOrDie(reader, addr, size);
} else {
// we can however safely inherit MAP_SHARED with zero copy
ViewOrDie(maps[i].h,
maps[i].readonlyfile ? kNtFileMapRead | kNtFileMapExecute
: kNtFileMapWrite | kNtFileMapExecute,
maps[i].offset, size, addr);
}
}
// read the .data and .bss program image sections
savepid = __pid;
savetsc = kStartTsc;
ReadOrDie(reader, __data_start, __data_end - __data_start);
ReadOrDie(reader, __bss_start, __bss_end - __bss_start);
__pid = savepid;
kStartTsc = savetsc;
__threaded = false;
__tls_index = 0;
__tls_enabled_set(false);
// apply fixups and reapply memory protections
_mmi.p = maps;
_mmi.n = specialz / sizeof(_mmi.p[0]);
for (i = 0; i < mapcount; ++i) {
if (!VirtualProtect((void *)((uint64_t)maps[i].x << 16), maps[i].size,
__prot2nt(maps[i].prot, maps[i].iscow), &oldprot)) {
AbortFork("VirtualProtect");
}
}
// mitosis complete
if (!CloseHandle(reader)) {
AbortFork("CloseHandle");
}
// rewrap the stdin named pipe hack
// since the handles closed on fork
struct Fds *fds = VEIL("r", &g_fds);
fds->p[0].handle = GetStdHandle(kNtStdInputHandle);
fds->p[1].handle = GetStdHandle(kNtStdOutputHandle);
fds->p[2].handle = GetStdHandle(kNtStdErrorHandle);
// untrack children of parent since we specify with both
// CreateProcess() and CreateThread() as non-inheritable
for (i = 0; i < fds->n; ++i) {
if (fds->p[i].kind == kFdProcess) {
fds->p[i].kind = 0;
atomic_store_explicit(&fds->f, MIN(i, fds->f), memory_order_relaxed);
}
}
// restore the crash reporting stuff
#ifdef SYSDEBUG
RemoveVectoredExceptionHandler(oncrash);
#endif
if (_weaken(__wincrash_nt)) {
if (!IsTiny()) {
RemoveVectoredExceptionHandler(__wincrashearly);
}
AddVectoredExceptionHandler(1, (void *)_weaken(__wincrash_nt));
}
if (_weaken(__onntconsoleevent_nt)) {
SetConsoleCtrlHandler(_weaken(__onntconsoleevent_nt), 1);
}
// jump back into function below
longjmp(jb, 1);
}
textwindows int sys_fork_nt(uint32_t dwCreationFlags) {
jmp_buf jb;
uint32_t oldprot;
char ok, threaded;
char **args, **args2;
struct CosmoTib *tib;
char16_t pipename[64];
int64_t reader, writer;
struct NtStartupInfo startinfo;
int i, n, pid, untrackpid, rc = -1;
char *p, forkvar[6 + 21 + 1 + 21 + 1];
struct NtProcessInformation procinfo;
threaded = __threaded;
tib = __tls_enabled ? __get_tls() : 0;
if (!setjmp(jb)) {
pid = untrackpid = __reservefd_unlocked(-1);
reader = CreateNamedPipe(CreatePipeName(pipename),
kNtPipeAccessInbound | kNtFileFlagOverlapped,
kNtPipeTypeMessage | kNtPipeReadmodeMessage, 1,
65536, 65536, 0, &kNtIsInheritable);
writer = CreateFile(pipename, kNtGenericWrite, 0, 0, kNtOpenExisting,
kNtFileFlagOverlapped, 0);
if (pid != -1 && reader != -1 && writer != -1) {
p = stpcpy(forkvar, "_FORK=");
p = FormatUint64(p, reader);
bzero(&startinfo, sizeof(startinfo));
startinfo.cb = sizeof(struct NtStartupInfo);
startinfo.dwFlags = kNtStartfUsestdhandles;
startinfo.hStdInput = __getfdhandleactual(0);
startinfo.hStdOutput = __getfdhandleactual(1);
startinfo.hStdError = __getfdhandleactual(2);
args = __argv;
#ifdef SYSDEBUG
// If --strace was passed to this program, then propagate it the
// forked process since the flag was removed by __intercept_flag
if (strace_enabled(0) > 0) {
for (n = 0; args[n];) ++n;
args2 = alloca((n + 2) * sizeof(char *));
for (i = 0; i < n; ++i) args2[i] = args[i];
args2[i++] = "--strace";
args2[i] = 0;
args = args2;
}
#endif
if (ntspawn(GetProgramExecutableName(), args, environ, forkvar, 0, 0,
true, dwCreationFlags, 0, &startinfo, &procinfo) != -1) {
CloseHandle(procinfo.hThread);
ok = WriteAll(writer, jb, sizeof(jb)) &&
WriteAll(writer, &_mmi.i, sizeof(_mmi.i)) &&
WriteAll(writer, &_mmi.n, sizeof(_mmi.n)) &&
WriteAll(writer, _mmi.p, _mmi.i * sizeof(_mmi.p[0]));
if (IsAsan() && ok) {
ok = WriteAll(writer, (char *)(((intptr_t)_mmi.p >> 3) + 0x7fff8000),
(_mmi.i * sizeof(_mmi.p[0])) >> 3);
}
for (i = 0; i < _mmi.i && ok; ++i) {
if ((_mmi.p[i].flags & MAP_TYPE) != MAP_SHARED) {
ok = WriteAll(writer, (void *)((uint64_t)_mmi.p[i].x << 16),
_mmi.p[i].size);
}
}
if (ok) ok = WriteAll(writer, __data_start, __data_end - __data_start);
if (ok) ok = WriteAll(writer, __bss_start, __bss_end - __bss_start);
if (ok) {
if (!CloseHandle(writer)) ok = false;
writer = -1;
}
if (ok) {
g_fds.p[pid].kind = kFdProcess;
g_fds.p[pid].handle = procinfo.hProcess;
g_fds.p[pid].flags = O_CLOEXEC;
g_fds.p[pid].zombie = false;
untrackpid = -1;
rc = pid;
} else {
TerminateProcess(procinfo.hProcess, 127);
CloseHandle(procinfo.hProcess);
}
}
}
if (reader != -1) CloseHandle(reader);
if (writer != -1) CloseHandle(writer);
if (rc == -1 && errno != ENOMEM) {
eagain(); // posix fork() only specifies two errors
}
} else {
rc = 0;
if (tib && _weaken(__set_tls) && _weaken(__morph_tls)) {
_weaken(__set_tls)(tib);
_weaken(__morph_tls)();
__tls_enabled_set(true);
}
if (threaded && !__threaded && _weaken(__enable_threads)) {
_weaken(__enable_threads)();
}
}
if (untrackpid != -1) {
__releasefd(untrackpid);
}
return rc;
}
#endif /* __x86_64__ */
| 13,667 | 368 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/stack.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_STACK_H_
#define COSMOPOLITAN_LIBC_RUNTIME_STACK_H_
#include "ape/config.h"
#include "libc/dce.h"
#include "libc/nt/version.h"
#include "libc/runtime/runtime.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
/**
* Tunes APE stack maximum size.
*
* This defaults to `STACKSIZE`. The bottom-most page will be protected
* to ensure your stack does not magically grow beyond this value. It's
* possible to detect stack overflows, by calling `ShowCrashReports()`.
* Your stack size must be a power of two; the linker will check this.
*
* If you want to know how much stack your programs needs, then
*
* STATIC_YOINK("stack_usage_logging");
*
* will install an atexit() handler that appends to `o/$MODE/stack.log`
*
* @see libc/sysv/systemfive.S
* @see ape/ape.lds
*/
#define STATIC_STACK_SIZE(BYTES) \
STATIC_SYMBOL("ape_stack_memsz", _STACK_STRINGIFY(BYTES) _STACK_EXTRA)
/**
* Tunes APE stack virtual address.
*
* This value must be aligned according to your stack size, and that's
* checked by your linker script. This defaults to `0x700000000000` so
*
* 1. It's easy to see how close you are to the bottom
* 2. The linker script error is unlikely to happen
*
* This macro will be respected, with two exceptions
*
* 1. In MODE=tiny the operating system provided stack is used instead
* 2. Windows 7 doesn't support 64-bit addresses, so we'll instead use
* `0x10000000 - GetStackSize()` as the stack address
*
* @see libc/sysv/systemfive.S
* @see libc/nt/winmain.greg.c
* @see ape/ape.lds
*/
#define STATIC_STACK_ADDR(ADDR) \
STATIC_SYMBOL("ape_stack_vaddr", _STACK_STRINGIFY(ADDR))
/**
* Makes program stack executable if declared, e.g.
*
* STATIC_EXEC_STACK();
* int main() {
* char code[16] = {
* 0x55, // push %rbp
* 0xb8, 0007, 0x00, 0x00, 0x00, // mov $7,%eax
* 0x5d, // push %rbp
* 0xc3, // ret
* };
* int (*func)(void) = (void *)code;
* printf("result %d should be 7\n", func());
* }
*/
#define STATIC_EXEC_STACK() STATIC_SYMBOL("ape_stack_pf", "7")
#define _STACK_STRINGIFY(ADDR) #ADDR
#if IsAsan()
#define _STACK_EXTRA "*2"
#else
#define _STACK_EXTRA ""
#endif
#if defined(__GNUC__) && defined(__ELF__) && !defined(__STRICT_ANSI__)
COSMOPOLITAN_C_START_
extern char ape_stack_prot[] __attribute__((__weak__));
extern char ape_stack_memsz[] __attribute__((__weak__));
extern char ape_stack_align[] __attribute__((__weak__));
/**
* Returns size of stack, which is always a two power.
*/
#define GetStackSize() ((uintptr_t)ape_stack_memsz)
/**
* Returns address of bottom of stack.
*
* This takes into consideration threads and sigaltstack. This is
* implemented as a fast pure expression, since we're able to make the
* assumption that stack sizes are two powers and aligned. This is
* thanks to (1) the linker script checks the statically chosen sizes,
* and (2) the mmap() address picker will choose aligned addresses when
* the provided size is a two power.
*/
#define GetStackAddr() \
(((intptr_t)__builtin_frame_address(0) - 1) & -GetStackSize())
#ifdef __x86_64__
/**
* Returns preferred bottom address of stack.
*
* This is the stakc address of the main process. The only time that
* isn't guaranteed to be the case is in MODE=tiny, since it doesn't
* link the code for stack creation at startup. This generally isn't
* problematic, since MODE=tiny doesn't use any of the runtime codes
* which want the stack to be cheaply knowable, e.g. ftrace, kprintf
*/
#define GetStaticStackAddr(ADDEND) \
({ \
intptr_t vAddr; \
__asm__(".weak\tape_stack_vaddr\n\t" \
"movabs\t%1+ape_stack_vaddr,%0" \
: "=r"(vAddr) \
: "i"(ADDEND)); \
vAddr; \
})
#else
#define GetStaticStackAddr(ADDEND) (GetStackAddr() + ADDEND)
#endif
/**
* Returns true if at least `n` bytes of stack are available.
*/
#define HaveStackMemory(n) \
((intptr_t)__builtin_frame_address(0) >= GetStackAddr() + GUARDSIZE + (n))
forceinline void CheckLargeStackAllocation(void *p, ssize_t n) {
for (; n > 0; n -= 4096) {
((char *)p)[n - 1] = 0;
}
}
COSMOPOLITAN_C_END_
#endif /* GNU ELF */
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_STACK_H_ */
| 4,527 | 140 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/clone-xnu.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/macros.internal.h"
sys_clone_xnu:
mov $0x02000168,%eax # bsdthread_create
mov %rcx,%r10
syscall
ret
.endfn sys_clone_xnu,globl,hidden
| 1,992 | 27 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/fork-sysv.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/dce.h"
#include "libc/runtime/syslib.internal.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/errfuns.h"
int sys_fork(void) {
#ifdef __x86_64__
axdx_t ad;
int ax, dx;
ad = __sys_fork();
ax = ad.ax;
dx = ad.dx;
if (IsXnu() && ax != -1) {
// eax always returned with childs pid
// edx is 0 for parent and 1 for child
ax &= dx - 1;
}
return ax;
#elif defined(__aarch64__)
if (IsLinux()) {
int flags = 17; // SIGCHLD
void *child_stack = 0;
void *parent_tidptr = 0;
void *newtls = 0;
void *child_tidptr = 0;
register long r0 asm("x0") = (long)flags;
register long r1 asm("x1") = (long)child_stack;
register long r2 asm("x2") = (long)parent_tidptr;
register long r3 asm("x3") = (long)newtls;
register long r4 asm("x4") = (long)child_tidptr;
register int res_x0 asm("x0");
asm volatile("mov\tx8,%1\n\t"
"svc\t0"
: "=r"(res_x0)
: "i"(220), "r"(r0), "r"(r1), "r"(r2), "r"(r3), "r"(r4)
: "x8", "x16", "memory");
return _sysret(res_x0);
} else if (__syslib) {
return _sysret(__syslib->fork());
} else {
return enosys();
}
#else
return enosys();
#endif
}
| 3,123 | 72 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/sigsetjmp.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Musl Libc â
â Copyright © 2005-2014 Rich Felker, et al. â
â â
â 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 "libc/macros.internal.h"
// Saves caller CPU state and signal mask.
//
// @param rdi points to jmp_buf
// @param esi if non-zero will cause mask to be saved
// @return eax 0 when set and !0 when longjmp'd
// @returnstwice
sigsetjmp:
test %esi,%esi
jz setjmp
popq 64(%rdi)
mov %rbx,72(%rdi)
mov %rdi,%rbx
call setjmp
pushq 64(%rbx)
mov %rbx,%rdi
mov %eax,%esi
mov 72(%rdi),%rbx
jmp __sigsetjmp_tail
.hidden __sigsetjmp_tail
.endfn sigsetjmp,globl
| 3,071 | 50 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/symbols.internal.h | #ifndef COSMOPOLITAN_LIBC_SYMBOLS_H_
#define COSMOPOLITAN_LIBC_SYMBOLS_H_
#include "libc/intrin/bits.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
#define SYMBOLS_MAGIC READ32LE("SYMT")
#define SYMBOLS_ABI 1
struct Symbol {
unsigned x; /* start (relative to addr_base) */
unsigned y; /* start + size - 1 (inclusive) */
};
struct SymbolTable {
uint32_t magic; /* 0xFEEDABEE little endian */
uint32_t abi; /* 1 */
uint64_t count; /* of `symbols` */
uint64_t size; /* file size */
uint64_t mapsize; /* of this object */
int64_t addr_base; /* IMAGE_BASE_VIRTUAL */
int64_t addr_end; /* _end - 1 */
uint32_t *names; /* relative to `name_base` */
char *name_base; /* double-nul terminated w/ empty first */
uint32_t names_offset; /* for file loading */
uint32_t name_base_offset; /* for file loading */
struct Symbol symbols[]; /* sorted and non-overlapping intervals */
};
struct SymbolTable *GetSymbolTable(void);
const char *FindComBinary(void);
const char *FindDebugBinary(void);
struct SymbolTable *OpenSymbolTable(const char *);
int CloseSymbolTable(struct SymbolTable **);
int __hook(void *, struct SymbolTable *);
int __get_symbol(struct SymbolTable *, intptr_t);
char *__get_symbol_name(struct SymbolTable *, int);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_SYMBOLS_H_ */
| 1,479 | 42 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/vfork.S | /*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-â
âvi: set et ft=asm ts=8 tw=8 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/intrin/strace.internal.h"
#include "libc/thread/tls.h"
#include "libc/macros.internal.h"
// Forks process without copying page tables.
//
// This is the same as fork() except it's optimized for the case
// where the caller invokes execve() immediately afterwards. You
// can also call functions like close(), dup2(), etc. Call _exit
// but don't call exit. Look for vforksafe function annotations,
// For example pthread mutexes are @vforksafe because they don't
// do anything in a vfork()'d child process. TLS memory must not
// be disabled (it's enabled by default) since vfork() needs it.
//
// What makes vfork() dangerous is that any changes to memory in
// the child process can happen in the parent too. The exception
// to this rule is `errno` which is saved/restored in a register
// by this implementation. However, despite its dangers, vfork's
// performance is irresistible and wonderous to behold. If safer
// code is desired, consider posix_spawn() which uses vfork().
//
// Do not make the assumption that the parent is suspended until
// the child terminates since this uses the raw fork system call
// on Windows, OpenBSD, and MacOS. In that case the process will
// proceed without blocking the parent; however, the `__vforked`
// variable is still set to true in the child, so lock functions
// won't do anything, and other functions shall change behavior.
// This ensures that, even if the operating system does not give
// us the performance of vfork(), we'll still be able to cut out
// the libc overhead, e.g. pthread_atfork().
//
// @return pid of child process or 0 if forked process
// @returnstwice
// @threadsafe
// @vforksafe
vfork:
#ifdef __x86_64__
#if !IsTiny()
push %rbp
mov %rsp,%rbp
.profilable
call __require_tls
#ifdef SYSDEBUG
ezlea .Llog,di
call __stracef
#endif
pop %rbp
#endif
mov %fs:0,%r9 // get thread information block
#if SupportsWindows()
testb IsWindows()
jnz 6f // and we're lucky to have that
#endif
#ifdef __SANITIZE_ADDRESS__
jmp 5f // TODO: asan and vfork don't mix?
#endif
#if SupportsXnu()
testb IsXnu()
jnz 5f
#endif
#if SupportsOpenbsd()
testb IsOpenbsd()
jnz 5f // fake vfork plus msyscall issues
#endif
mov 0x3c(%r9),%r8d // avoid question of @vforksafe errno
pop %rsi // saves return address in a register
mov __NR_vfork(%rip),%eax
#if SupportsBsd()
clc
#endif
syscall
#if SupportsBsd()
jnc 0f
neg %rax
0:
#endif
push %rsi // note it happens twice in same page
cmp $-4095,%eax
jae systemfive_error
mov %r8d,0x3c(%r9) // restore errno
1: test %eax,%eax
jnz .Lpar
.Lchi: orb $TIB_FLAG_VFORKED,0x40(%r9)
ret
.Lpar: andb $~TIB_FLAG_VFORKED,0x40(%r9)
ret
#if SupportsXnu() || SupportsOpenbsd() || defined(__SANITIZE_ADDRESS__)
5: push %rbp
mov %rsp,%rbp
push %r9
push %r9
call sys_fork
pop %r9
pop %r9
pop %rbp
jmp 1b
#endif
#if SupportsWindows()
6: push %rbp
mov %rsp,%rbp
push %r9
push %r9
xor %edi,%edi // dwCreationFlags
call sys_fork_nt
pop %r9
pop %r9
pop %rbp
jmp 1b
#endif
#elif defined(__aarch64__)
adrp x0,__hostos
ldr w0,[x0,#:lo12:__hostos]
tbz x0,3,1f // bit 3 is xnu
b fork // which doesn't support vfork()
1: mov x8,#220 // __NR_clone
mov x0,#0x4111 // SIGCHLD | CLONE_VM | CLONE_VFORK
mov x1,#0
svc 0
// if (!rc) {
// __get_tls()->tib_flags |= TIB_FLAG_VFORKED;
// } else {
// __get_tls()->tib_flags &= ~TIB_FLAG_VFORKED;
// }
sub x1,x28,#1152
ldr x2,[x1,0x40]
cbnz x0,2f
orr x2,x2,#TIB_FLAG_VFORKED
1: str x2,[x1,0x40]
b 3f
2: and x2,x2,#~TIB_FLAG_VFORKED
b 1b
// if (rc < 0) errno = -rc, rc = -1;
3: .hidden _sysret
b _sysret
#else
#error "architecture unsupported"
#endif
.endfn vfork,globl
#ifdef SYSDEBUG
.rodata.str1.1
.Llog: .ascii STRACE_PROLOGUE
.asciz "vfork()\n"
.previous
#endif /* DEBUGSYS */
| 5,649 | 172 | jart/cosmopolitan | false |
cosmopolitan/libc/runtime/internal.h | #ifndef COSMOPOLITAN_LIBC_RUNTIME_INTERNAL_H_
#define COSMOPOLITAN_LIBC_RUNTIME_INTERNAL_H_
#ifndef __STRICT_ANSI__
#include "libc/dce.h"
#include "libc/elf/struct/ehdr.h"
#include "libc/runtime/ezmap.internal.h"
#include "libc/runtime/runtime.h"
#define STACK_CEIL 0x700000000000ul
#define STACK_SIZE FRAMESIZE
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
extern int __pid;
extern uint32_t __ntconsolemode[3];
extern const char v_ntsubsystem[] __attribute__((__weak__));
extern const uintptr_t __fini_array_end[] __attribute__((__weak__));
extern const uintptr_t __fini_array_start[] __attribute__((__weak__));
extern unsigned char _tdata_start[] __attribute__((__weak__));
extern unsigned char _tdata_end[] __attribute__((__weak__));
extern unsigned char _tdata_size[] __attribute__((__weak__));
extern unsigned char _tbss_start[] __attribute__((__weak__));
extern unsigned char _tbss_end[] __attribute__((__weak__));
extern unsigned char _tbss_size[] __attribute__((__weak__));
extern unsigned char _tbss_offset[] __attribute__((__weak__));
extern unsigned char _tls_size[] __attribute__((__weak__));
extern unsigned char _tls_content[] __attribute__((__weak__));
void _init(void) _Hide;
void __morph_tls(void);
void __enable_tls(void);
void __enable_threads(void) _Hide;
void *__cxa_finalize(void *) _Hide;
void __stack_chk_fail(void) wontreturn relegated;
void __stack_chk_fail_local(void) wontreturn relegated _Hide;
void __asan_init(int, char **, char **, intptr_t *) _Hide;
void _jmpstack(void *, void *, ...) _Hide wontreturn;
long _setstack(void *, void *, ...) _Hide;
int GetDosArgv(const char16_t *, char *, size_t, char **, size_t);
Elf64_Ehdr *MapElfRead(const char *, struct MappedFile *) _Hide;
int GetDosEnviron(const char16_t *, char *, size_t, char **, size_t);
bool __intercept_flag(int *, char *[], const char *);
int sys_mprotect_nt(void *, size_t, int) _Hide;
int __inflate(void *, size_t, const void *, size_t);
noasan void *_Mmap(void *, size_t, int, int, int, int64_t) _Hide;
noasan int _Munmap(char *, size_t) _Hide;
void InitializeFileDescriptors(void);
void __on_arithmetic_overflow(void);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* ANSI */
#endif /* COSMOPOLITAN_LIBC_RUNTIME_INTERNAL_H_ */
| 2,276 | 56 | jart/cosmopolitan | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.