text
stringlengths
1
1.05M
#pragma once #ifdef POLYSOLVE_WITH_HYPRE //////////////////////////////////////////////////////////////////////////////// #include <polysolve/LinearSolver.hpp> #include <Eigen/Core> #include <Eigen/Sparse> #include <vector> #include <HYPRE_utilities.h> #include <HYPRE.h> #include <HYPRE_parcsr_ls.h> #include <HYPRE_parcsr_mv.h> #include <IJ_matrix.h> //////////////////////////////////////////////////////////////////////////////// // // https://computation.llnl.gov/sites/default/files/public/hypre-2.11.2_usr_manual.pdf // https://github.com/LLNL/hypre/blob/v2.14.0/docs/HYPRE_usr_manual.pdf // namespace polysolve { class LinearSolverHypre : public LinearSolver { public: LinearSolverHypre(); ~LinearSolverHypre(); private: POLYSOLVE_DELETE_MOVE_COPY(LinearSolverHypre) public: ////////////////////// // Public interface // ////////////////////// // Set solver parameters virtual void setParameters(const json &params) override; // Retrieve memory information from Pardiso virtual void getInfo(json &params) const override; // Analyze sparsity pattern virtual void analyzePattern(const StiffnessMatrix &A, const int precond_num) override { precond_num_ = precond_num; } // Factorize system matrix virtual void factorize(const StiffnessMatrix &A) override; // Solve the linear system Ax = b virtual void solve(const Ref<const VectorXd> b, Ref<VectorXd> x) override; // Name of the solver type (for debugging purposes) virtual std::string name() const override { return "Hypre"; } protected: int dimension_ = 1; // 1 = scalar (Laplace), 2 or 3 = vector (Elasticity) int max_iter_ = 1000; int pre_max_iter_ = 1; double conv_tol_ = 1e-10; HYPRE_Int num_iterations; HYPRE_Complex final_res_norm; private: bool has_matrix_ = false; int precond_num_; HYPRE_IJMatrix A; HYPRE_ParCSRMatrix parcsr_A; }; } // namespace polysolve #endif
; A076767: Triangular numbers with square pyramidal indices. ; 0,1,15,105,465,1540,4186,9870,20910,40755,74305,128271,211575,335790,515620,769420,1119756,1594005,2224995,3051685,4119885,5483016,7202910,9350650,12007450,15265575,19229301,24015915,29756755,36598290 mov $1,$0 mov $2,1 sub $2,$0 sub $1,$2 add $1,2 mov $0,$1 mul $0,$1 sub $0,1 mul $1,$0 add $1,12 pow $1,2 div $1,1152
_wc: file format elf32-i386 Disassembly of section .text: 00000000 <wc>: char buf[512]; void wc(int fd, char *name) { 0: f3 0f 1e fb endbr32 4: 55 push %ebp 5: 89 e5 mov %esp,%ebp 7: 83 ec 28 sub $0x28,%esp int i, n; int l, w, c, inword; l = w = c = 0; a: c7 45 e8 00 00 00 00 movl $0x0,-0x18(%ebp) 11: 8b 45 e8 mov -0x18(%ebp),%eax 14: 89 45 ec mov %eax,-0x14(%ebp) 17: 8b 45 ec mov -0x14(%ebp),%eax 1a: 89 45 f0 mov %eax,-0x10(%ebp) inword = 0; 1d: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp) while((n = read(fd, buf, sizeof(buf))) > 0){ 24: eb 69 jmp 8f <wc+0x8f> for(i=0; i<n; i++){ 26: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 2d: eb 58 jmp 87 <wc+0x87> c++; 2f: 83 45 e8 01 addl $0x1,-0x18(%ebp) if(buf[i] == '\n') 33: 8b 45 f4 mov -0xc(%ebp),%eax 36: 05 80 0c 00 00 add $0xc80,%eax 3b: 0f b6 00 movzbl (%eax),%eax 3e: 3c 0a cmp $0xa,%al 40: 75 04 jne 46 <wc+0x46> l++; 42: 83 45 f0 01 addl $0x1,-0x10(%ebp) if(strchr(" \r\t\n\v", buf[i])) 46: 8b 45 f4 mov -0xc(%ebp),%eax 49: 05 80 0c 00 00 add $0xc80,%eax 4e: 0f b6 00 movzbl (%eax),%eax 51: 0f be c0 movsbl %al,%eax 54: 83 ec 08 sub $0x8,%esp 57: 50 push %eax 58: 68 93 09 00 00 push $0x993 5d: e8 49 02 00 00 call 2ab <strchr> 62: 83 c4 10 add $0x10,%esp 65: 85 c0 test %eax,%eax 67: 74 09 je 72 <wc+0x72> inword = 0; 69: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp) 70: eb 11 jmp 83 <wc+0x83> else if(!inword){ 72: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp) 76: 75 0b jne 83 <wc+0x83> w++; 78: 83 45 ec 01 addl $0x1,-0x14(%ebp) inword = 1; 7c: c7 45 e4 01 00 00 00 movl $0x1,-0x1c(%ebp) for(i=0; i<n; i++){ 83: 83 45 f4 01 addl $0x1,-0xc(%ebp) 87: 8b 45 f4 mov -0xc(%ebp),%eax 8a: 3b 45 e0 cmp -0x20(%ebp),%eax 8d: 7c a0 jl 2f <wc+0x2f> while((n = read(fd, buf, sizeof(buf))) > 0){ 8f: 83 ec 04 sub $0x4,%esp 92: 68 00 02 00 00 push $0x200 97: 68 80 0c 00 00 push $0xc80 9c: ff 75 08 pushl 0x8(%ebp) 9f: e8 b4 03 00 00 call 458 <read> a4: 83 c4 10 add $0x10,%esp a7: 89 45 e0 mov %eax,-0x20(%ebp) aa: 83 7d e0 00 cmpl $0x0,-0x20(%ebp) ae: 0f 8f 72 ff ff ff jg 26 <wc+0x26> } } } if(n < 0){ b4: 83 7d e0 00 cmpl $0x0,-0x20(%ebp) b8: 79 17 jns d1 <wc+0xd1> printf(1, "wc: read error\n"); ba: 83 ec 08 sub $0x8,%esp bd: 68 99 09 00 00 push $0x999 c2: 6a 01 push $0x1 c4: e8 03 05 00 00 call 5cc <printf> c9: 83 c4 10 add $0x10,%esp exit(); cc: e8 6f 03 00 00 call 440 <exit> } printf(1, "%d %d %d %s\n", l, w, c, name); d1: 83 ec 08 sub $0x8,%esp d4: ff 75 0c pushl 0xc(%ebp) d7: ff 75 e8 pushl -0x18(%ebp) da: ff 75 ec pushl -0x14(%ebp) dd: ff 75 f0 pushl -0x10(%ebp) e0: 68 a9 09 00 00 push $0x9a9 e5: 6a 01 push $0x1 e7: e8 e0 04 00 00 call 5cc <printf> ec: 83 c4 20 add $0x20,%esp } ef: 90 nop f0: c9 leave f1: c3 ret 000000f2 <main>: int main(int argc, char *argv[]) { f2: f3 0f 1e fb endbr32 f6: 8d 4c 24 04 lea 0x4(%esp),%ecx fa: 83 e4 f0 and $0xfffffff0,%esp fd: ff 71 fc pushl -0x4(%ecx) 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 53 push %ebx 104: 51 push %ecx 105: 83 ec 10 sub $0x10,%esp 108: 89 cb mov %ecx,%ebx int fd, i; if(argc <= 1){ 10a: 83 3b 01 cmpl $0x1,(%ebx) 10d: 7f 17 jg 126 <main+0x34> wc(0, ""); 10f: 83 ec 08 sub $0x8,%esp 112: 68 b6 09 00 00 push $0x9b6 117: 6a 00 push $0x0 119: e8 e2 fe ff ff call 0 <wc> 11e: 83 c4 10 add $0x10,%esp exit(); 121: e8 1a 03 00 00 call 440 <exit> } for(i = 1; i < argc; i++){ 126: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%ebp) 12d: e9 83 00 00 00 jmp 1b5 <main+0xc3> if((fd = open(argv[i], 0)) < 0){ 132: 8b 45 f4 mov -0xc(%ebp),%eax 135: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 13c: 8b 43 04 mov 0x4(%ebx),%eax 13f: 01 d0 add %edx,%eax 141: 8b 00 mov (%eax),%eax 143: 83 ec 08 sub $0x8,%esp 146: 6a 00 push $0x0 148: 50 push %eax 149: e8 32 03 00 00 call 480 <open> 14e: 83 c4 10 add $0x10,%esp 151: 89 45 f0 mov %eax,-0x10(%ebp) 154: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 158: 79 29 jns 183 <main+0x91> printf(1, "wc: cannot open %s\n", argv[i]); 15a: 8b 45 f4 mov -0xc(%ebp),%eax 15d: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 164: 8b 43 04 mov 0x4(%ebx),%eax 167: 01 d0 add %edx,%eax 169: 8b 00 mov (%eax),%eax 16b: 83 ec 04 sub $0x4,%esp 16e: 50 push %eax 16f: 68 b7 09 00 00 push $0x9b7 174: 6a 01 push $0x1 176: e8 51 04 00 00 call 5cc <printf> 17b: 83 c4 10 add $0x10,%esp exit(); 17e: e8 bd 02 00 00 call 440 <exit> } wc(fd, argv[i]); 183: 8b 45 f4 mov -0xc(%ebp),%eax 186: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 18d: 8b 43 04 mov 0x4(%ebx),%eax 190: 01 d0 add %edx,%eax 192: 8b 00 mov (%eax),%eax 194: 83 ec 08 sub $0x8,%esp 197: 50 push %eax 198: ff 75 f0 pushl -0x10(%ebp) 19b: e8 60 fe ff ff call 0 <wc> 1a0: 83 c4 10 add $0x10,%esp close(fd); 1a3: 83 ec 0c sub $0xc,%esp 1a6: ff 75 f0 pushl -0x10(%ebp) 1a9: e8 ba 02 00 00 call 468 <close> 1ae: 83 c4 10 add $0x10,%esp for(i = 1; i < argc; i++){ 1b1: 83 45 f4 01 addl $0x1,-0xc(%ebp) 1b5: 8b 45 f4 mov -0xc(%ebp),%eax 1b8: 3b 03 cmp (%ebx),%eax 1ba: 0f 8c 72 ff ff ff jl 132 <main+0x40> } exit(); 1c0: e8 7b 02 00 00 call 440 <exit> 000001c5 <stosb>: : "cc"); } static inline void stosb(void *addr, int data, int cnt) { 1c5: 55 push %ebp 1c6: 89 e5 mov %esp,%ebp 1c8: 57 push %edi 1c9: 53 push %ebx asm volatile("cld; rep stosb" 1ca: 8b 4d 08 mov 0x8(%ebp),%ecx 1cd: 8b 55 10 mov 0x10(%ebp),%edx 1d0: 8b 45 0c mov 0xc(%ebp),%eax 1d3: 89 cb mov %ecx,%ebx 1d5: 89 df mov %ebx,%edi 1d7: 89 d1 mov %edx,%ecx 1d9: fc cld 1da: f3 aa rep stos %al,%es:(%edi) 1dc: 89 ca mov %ecx,%edx 1de: 89 fb mov %edi,%ebx 1e0: 89 5d 08 mov %ebx,0x8(%ebp) 1e3: 89 55 10 mov %edx,0x10(%ebp) : "=D"(addr), "=c"(cnt) : "0"(addr), "1"(cnt), "a"(data) : "memory", "cc"); } 1e6: 90 nop 1e7: 5b pop %ebx 1e8: 5f pop %edi 1e9: 5d pop %ebp 1ea: c3 ret 000001eb <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 1eb: f3 0f 1e fb endbr32 1ef: 55 push %ebp 1f0: 89 e5 mov %esp,%ebp 1f2: 83 ec 10 sub $0x10,%esp char *os; os = s; 1f5: 8b 45 08 mov 0x8(%ebp),%eax 1f8: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 1fb: 90 nop 1fc: 8b 55 0c mov 0xc(%ebp),%edx 1ff: 8d 42 01 lea 0x1(%edx),%eax 202: 89 45 0c mov %eax,0xc(%ebp) 205: 8b 45 08 mov 0x8(%ebp),%eax 208: 8d 48 01 lea 0x1(%eax),%ecx 20b: 89 4d 08 mov %ecx,0x8(%ebp) 20e: 0f b6 12 movzbl (%edx),%edx 211: 88 10 mov %dl,(%eax) 213: 0f b6 00 movzbl (%eax),%eax 216: 84 c0 test %al,%al 218: 75 e2 jne 1fc <strcpy+0x11> ; return os; 21a: 8b 45 fc mov -0x4(%ebp),%eax } 21d: c9 leave 21e: c3 ret 0000021f <strcmp>: int strcmp(const char *p, const char *q) { 21f: f3 0f 1e fb endbr32 223: 55 push %ebp 224: 89 e5 mov %esp,%ebp while(*p && *p == *q) 226: eb 08 jmp 230 <strcmp+0x11> p++, q++; 228: 83 45 08 01 addl $0x1,0x8(%ebp) 22c: 83 45 0c 01 addl $0x1,0xc(%ebp) while(*p && *p == *q) 230: 8b 45 08 mov 0x8(%ebp),%eax 233: 0f b6 00 movzbl (%eax),%eax 236: 84 c0 test %al,%al 238: 74 10 je 24a <strcmp+0x2b> 23a: 8b 45 08 mov 0x8(%ebp),%eax 23d: 0f b6 10 movzbl (%eax),%edx 240: 8b 45 0c mov 0xc(%ebp),%eax 243: 0f b6 00 movzbl (%eax),%eax 246: 38 c2 cmp %al,%dl 248: 74 de je 228 <strcmp+0x9> return (uchar)*p - (uchar)*q; 24a: 8b 45 08 mov 0x8(%ebp),%eax 24d: 0f b6 00 movzbl (%eax),%eax 250: 0f b6 d0 movzbl %al,%edx 253: 8b 45 0c mov 0xc(%ebp),%eax 256: 0f b6 00 movzbl (%eax),%eax 259: 0f b6 c0 movzbl %al,%eax 25c: 29 c2 sub %eax,%edx 25e: 89 d0 mov %edx,%eax } 260: 5d pop %ebp 261: c3 ret 00000262 <strlen>: uint strlen(const char *s) { 262: f3 0f 1e fb endbr32 266: 55 push %ebp 267: 89 e5 mov %esp,%ebp 269: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 26c: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 273: eb 04 jmp 279 <strlen+0x17> 275: 83 45 fc 01 addl $0x1,-0x4(%ebp) 279: 8b 55 fc mov -0x4(%ebp),%edx 27c: 8b 45 08 mov 0x8(%ebp),%eax 27f: 01 d0 add %edx,%eax 281: 0f b6 00 movzbl (%eax),%eax 284: 84 c0 test %al,%al 286: 75 ed jne 275 <strlen+0x13> ; return n; 288: 8b 45 fc mov -0x4(%ebp),%eax } 28b: c9 leave 28c: c3 ret 0000028d <memset>: void* memset(void *dst, int c, uint n) { 28d: f3 0f 1e fb endbr32 291: 55 push %ebp 292: 89 e5 mov %esp,%ebp stosb(dst, c, n); 294: 8b 45 10 mov 0x10(%ebp),%eax 297: 50 push %eax 298: ff 75 0c pushl 0xc(%ebp) 29b: ff 75 08 pushl 0x8(%ebp) 29e: e8 22 ff ff ff call 1c5 <stosb> 2a3: 83 c4 0c add $0xc,%esp return dst; 2a6: 8b 45 08 mov 0x8(%ebp),%eax } 2a9: c9 leave 2aa: c3 ret 000002ab <strchr>: char* strchr(const char *s, char c) { 2ab: f3 0f 1e fb endbr32 2af: 55 push %ebp 2b0: 89 e5 mov %esp,%ebp 2b2: 83 ec 04 sub $0x4,%esp 2b5: 8b 45 0c mov 0xc(%ebp),%eax 2b8: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 2bb: eb 14 jmp 2d1 <strchr+0x26> if(*s == c) 2bd: 8b 45 08 mov 0x8(%ebp),%eax 2c0: 0f b6 00 movzbl (%eax),%eax 2c3: 38 45 fc cmp %al,-0x4(%ebp) 2c6: 75 05 jne 2cd <strchr+0x22> return (char*)s; 2c8: 8b 45 08 mov 0x8(%ebp),%eax 2cb: eb 13 jmp 2e0 <strchr+0x35> for(; *s; s++) 2cd: 83 45 08 01 addl $0x1,0x8(%ebp) 2d1: 8b 45 08 mov 0x8(%ebp),%eax 2d4: 0f b6 00 movzbl (%eax),%eax 2d7: 84 c0 test %al,%al 2d9: 75 e2 jne 2bd <strchr+0x12> return 0; 2db: b8 00 00 00 00 mov $0x0,%eax } 2e0: c9 leave 2e1: c3 ret 000002e2 <gets>: char* gets(char *buf, int max) { 2e2: f3 0f 1e fb endbr32 2e6: 55 push %ebp 2e7: 89 e5 mov %esp,%ebp 2e9: 83 ec 18 sub $0x18,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 2ec: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 2f3: eb 42 jmp 337 <gets+0x55> cc = read(0, &c, 1); 2f5: 83 ec 04 sub $0x4,%esp 2f8: 6a 01 push $0x1 2fa: 8d 45 ef lea -0x11(%ebp),%eax 2fd: 50 push %eax 2fe: 6a 00 push $0x0 300: e8 53 01 00 00 call 458 <read> 305: 83 c4 10 add $0x10,%esp 308: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 30b: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 30f: 7e 33 jle 344 <gets+0x62> break; buf[i++] = c; 311: 8b 45 f4 mov -0xc(%ebp),%eax 314: 8d 50 01 lea 0x1(%eax),%edx 317: 89 55 f4 mov %edx,-0xc(%ebp) 31a: 89 c2 mov %eax,%edx 31c: 8b 45 08 mov 0x8(%ebp),%eax 31f: 01 c2 add %eax,%edx 321: 0f b6 45 ef movzbl -0x11(%ebp),%eax 325: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 327: 0f b6 45 ef movzbl -0x11(%ebp),%eax 32b: 3c 0a cmp $0xa,%al 32d: 74 16 je 345 <gets+0x63> 32f: 0f b6 45 ef movzbl -0x11(%ebp),%eax 333: 3c 0d cmp $0xd,%al 335: 74 0e je 345 <gets+0x63> for(i=0; i+1 < max; ){ 337: 8b 45 f4 mov -0xc(%ebp),%eax 33a: 83 c0 01 add $0x1,%eax 33d: 39 45 0c cmp %eax,0xc(%ebp) 340: 7f b3 jg 2f5 <gets+0x13> 342: eb 01 jmp 345 <gets+0x63> break; 344: 90 nop break; } buf[i] = '\0'; 345: 8b 55 f4 mov -0xc(%ebp),%edx 348: 8b 45 08 mov 0x8(%ebp),%eax 34b: 01 d0 add %edx,%eax 34d: c6 00 00 movb $0x0,(%eax) return buf; 350: 8b 45 08 mov 0x8(%ebp),%eax } 353: c9 leave 354: c3 ret 00000355 <stat>: int stat(const char *n, struct stat *st) { 355: f3 0f 1e fb endbr32 359: 55 push %ebp 35a: 89 e5 mov %esp,%ebp 35c: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 35f: 83 ec 08 sub $0x8,%esp 362: 6a 00 push $0x0 364: ff 75 08 pushl 0x8(%ebp) 367: e8 14 01 00 00 call 480 <open> 36c: 83 c4 10 add $0x10,%esp 36f: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 372: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 376: 79 07 jns 37f <stat+0x2a> return -1; 378: b8 ff ff ff ff mov $0xffffffff,%eax 37d: eb 25 jmp 3a4 <stat+0x4f> r = fstat(fd, st); 37f: 83 ec 08 sub $0x8,%esp 382: ff 75 0c pushl 0xc(%ebp) 385: ff 75 f4 pushl -0xc(%ebp) 388: e8 0b 01 00 00 call 498 <fstat> 38d: 83 c4 10 add $0x10,%esp 390: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 393: 83 ec 0c sub $0xc,%esp 396: ff 75 f4 pushl -0xc(%ebp) 399: e8 ca 00 00 00 call 468 <close> 39e: 83 c4 10 add $0x10,%esp return r; 3a1: 8b 45 f0 mov -0x10(%ebp),%eax } 3a4: c9 leave 3a5: c3 ret 000003a6 <atoi>: int atoi(const char *s) { 3a6: f3 0f 1e fb endbr32 3aa: 55 push %ebp 3ab: 89 e5 mov %esp,%ebp 3ad: 83 ec 10 sub $0x10,%esp int n; n = 0; 3b0: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 3b7: eb 25 jmp 3de <atoi+0x38> n = n*10 + *s++ - '0'; 3b9: 8b 55 fc mov -0x4(%ebp),%edx 3bc: 89 d0 mov %edx,%eax 3be: c1 e0 02 shl $0x2,%eax 3c1: 01 d0 add %edx,%eax 3c3: 01 c0 add %eax,%eax 3c5: 89 c1 mov %eax,%ecx 3c7: 8b 45 08 mov 0x8(%ebp),%eax 3ca: 8d 50 01 lea 0x1(%eax),%edx 3cd: 89 55 08 mov %edx,0x8(%ebp) 3d0: 0f b6 00 movzbl (%eax),%eax 3d3: 0f be c0 movsbl %al,%eax 3d6: 01 c8 add %ecx,%eax 3d8: 83 e8 30 sub $0x30,%eax 3db: 89 45 fc mov %eax,-0x4(%ebp) while('0' <= *s && *s <= '9') 3de: 8b 45 08 mov 0x8(%ebp),%eax 3e1: 0f b6 00 movzbl (%eax),%eax 3e4: 3c 2f cmp $0x2f,%al 3e6: 7e 0a jle 3f2 <atoi+0x4c> 3e8: 8b 45 08 mov 0x8(%ebp),%eax 3eb: 0f b6 00 movzbl (%eax),%eax 3ee: 3c 39 cmp $0x39,%al 3f0: 7e c7 jle 3b9 <atoi+0x13> return n; 3f2: 8b 45 fc mov -0x4(%ebp),%eax } 3f5: c9 leave 3f6: c3 ret 000003f7 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 3f7: f3 0f 1e fb endbr32 3fb: 55 push %ebp 3fc: 89 e5 mov %esp,%ebp 3fe: 83 ec 10 sub $0x10,%esp char *dst; const char *src; dst = vdst; 401: 8b 45 08 mov 0x8(%ebp),%eax 404: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 407: 8b 45 0c mov 0xc(%ebp),%eax 40a: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 40d: eb 17 jmp 426 <memmove+0x2f> *dst++ = *src++; 40f: 8b 55 f8 mov -0x8(%ebp),%edx 412: 8d 42 01 lea 0x1(%edx),%eax 415: 89 45 f8 mov %eax,-0x8(%ebp) 418: 8b 45 fc mov -0x4(%ebp),%eax 41b: 8d 48 01 lea 0x1(%eax),%ecx 41e: 89 4d fc mov %ecx,-0x4(%ebp) 421: 0f b6 12 movzbl (%edx),%edx 424: 88 10 mov %dl,(%eax) while(n-- > 0) 426: 8b 45 10 mov 0x10(%ebp),%eax 429: 8d 50 ff lea -0x1(%eax),%edx 42c: 89 55 10 mov %edx,0x10(%ebp) 42f: 85 c0 test %eax,%eax 431: 7f dc jg 40f <memmove+0x18> return vdst; 433: 8b 45 08 mov 0x8(%ebp),%eax } 436: c9 leave 437: c3 ret 00000438 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 438: b8 01 00 00 00 mov $0x1,%eax 43d: cd 40 int $0x40 43f: c3 ret 00000440 <exit>: SYSCALL(exit) 440: b8 02 00 00 00 mov $0x2,%eax 445: cd 40 int $0x40 447: c3 ret 00000448 <wait>: SYSCALL(wait) 448: b8 03 00 00 00 mov $0x3,%eax 44d: cd 40 int $0x40 44f: c3 ret 00000450 <pipe>: SYSCALL(pipe) 450: b8 04 00 00 00 mov $0x4,%eax 455: cd 40 int $0x40 457: c3 ret 00000458 <read>: SYSCALL(read) 458: b8 05 00 00 00 mov $0x5,%eax 45d: cd 40 int $0x40 45f: c3 ret 00000460 <write>: SYSCALL(write) 460: b8 10 00 00 00 mov $0x10,%eax 465: cd 40 int $0x40 467: c3 ret 00000468 <close>: SYSCALL(close) 468: b8 15 00 00 00 mov $0x15,%eax 46d: cd 40 int $0x40 46f: c3 ret 00000470 <kill>: SYSCALL(kill) 470: b8 06 00 00 00 mov $0x6,%eax 475: cd 40 int $0x40 477: c3 ret 00000478 <exec>: SYSCALL(exec) 478: b8 07 00 00 00 mov $0x7,%eax 47d: cd 40 int $0x40 47f: c3 ret 00000480 <open>: SYSCALL(open) 480: b8 0f 00 00 00 mov $0xf,%eax 485: cd 40 int $0x40 487: c3 ret 00000488 <mknod>: SYSCALL(mknod) 488: b8 11 00 00 00 mov $0x11,%eax 48d: cd 40 int $0x40 48f: c3 ret 00000490 <unlink>: SYSCALL(unlink) 490: b8 12 00 00 00 mov $0x12,%eax 495: cd 40 int $0x40 497: c3 ret 00000498 <fstat>: SYSCALL(fstat) 498: b8 08 00 00 00 mov $0x8,%eax 49d: cd 40 int $0x40 49f: c3 ret 000004a0 <link>: SYSCALL(link) 4a0: b8 13 00 00 00 mov $0x13,%eax 4a5: cd 40 int $0x40 4a7: c3 ret 000004a8 <mkdir>: SYSCALL(mkdir) 4a8: b8 14 00 00 00 mov $0x14,%eax 4ad: cd 40 int $0x40 4af: c3 ret 000004b0 <chdir>: SYSCALL(chdir) 4b0: b8 09 00 00 00 mov $0x9,%eax 4b5: cd 40 int $0x40 4b7: c3 ret 000004b8 <dup>: SYSCALL(dup) 4b8: b8 0a 00 00 00 mov $0xa,%eax 4bd: cd 40 int $0x40 4bf: c3 ret 000004c0 <getpid>: SYSCALL(getpid) 4c0: b8 0b 00 00 00 mov $0xb,%eax 4c5: cd 40 int $0x40 4c7: c3 ret 000004c8 <sbrk>: SYSCALL(sbrk) 4c8: b8 0c 00 00 00 mov $0xc,%eax 4cd: cd 40 int $0x40 4cf: c3 ret 000004d0 <sleep>: SYSCALL(sleep) 4d0: b8 0d 00 00 00 mov $0xd,%eax 4d5: cd 40 int $0x40 4d7: c3 ret 000004d8 <uptime>: SYSCALL(uptime) 4d8: b8 0e 00 00 00 mov $0xe,%eax 4dd: cd 40 int $0x40 4df: c3 ret 000004e0 <cps>: SYSCALL(cps) 4e0: b8 16 00 00 00 mov $0x16,%eax 4e5: cd 40 int $0x40 4e7: c3 ret 000004e8 <cdate>: 4e8: b8 17 00 00 00 mov $0x17,%eax 4ed: cd 40 int $0x40 4ef: c3 ret 000004f0 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 4f0: f3 0f 1e fb endbr32 4f4: 55 push %ebp 4f5: 89 e5 mov %esp,%ebp 4f7: 83 ec 18 sub $0x18,%esp 4fa: 8b 45 0c mov 0xc(%ebp),%eax 4fd: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 500: 83 ec 04 sub $0x4,%esp 503: 6a 01 push $0x1 505: 8d 45 f4 lea -0xc(%ebp),%eax 508: 50 push %eax 509: ff 75 08 pushl 0x8(%ebp) 50c: e8 4f ff ff ff call 460 <write> 511: 83 c4 10 add $0x10,%esp } 514: 90 nop 515: c9 leave 516: c3 ret 00000517 <printint>: static void printint(int fd, int xx, int base, int sgn) { 517: f3 0f 1e fb endbr32 51b: 55 push %ebp 51c: 89 e5 mov %esp,%ebp 51e: 83 ec 28 sub $0x28,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 521: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 528: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 52c: 74 17 je 545 <printint+0x2e> 52e: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 532: 79 11 jns 545 <printint+0x2e> neg = 1; 534: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 53b: 8b 45 0c mov 0xc(%ebp),%eax 53e: f7 d8 neg %eax 540: 89 45 ec mov %eax,-0x14(%ebp) 543: eb 06 jmp 54b <printint+0x34> } else { x = xx; 545: 8b 45 0c mov 0xc(%ebp),%eax 548: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 54b: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 552: 8b 4d 10 mov 0x10(%ebp),%ecx 555: 8b 45 ec mov -0x14(%ebp),%eax 558: ba 00 00 00 00 mov $0x0,%edx 55d: f7 f1 div %ecx 55f: 89 d1 mov %edx,%ecx 561: 8b 45 f4 mov -0xc(%ebp),%eax 564: 8d 50 01 lea 0x1(%eax),%edx 567: 89 55 f4 mov %edx,-0xc(%ebp) 56a: 0f b6 91 3c 0c 00 00 movzbl 0xc3c(%ecx),%edx 571: 88 54 05 dc mov %dl,-0x24(%ebp,%eax,1) }while((x /= base) != 0); 575: 8b 4d 10 mov 0x10(%ebp),%ecx 578: 8b 45 ec mov -0x14(%ebp),%eax 57b: ba 00 00 00 00 mov $0x0,%edx 580: f7 f1 div %ecx 582: 89 45 ec mov %eax,-0x14(%ebp) 585: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 589: 75 c7 jne 552 <printint+0x3b> if(neg) 58b: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 58f: 74 2d je 5be <printint+0xa7> buf[i++] = '-'; 591: 8b 45 f4 mov -0xc(%ebp),%eax 594: 8d 50 01 lea 0x1(%eax),%edx 597: 89 55 f4 mov %edx,-0xc(%ebp) 59a: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 59f: eb 1d jmp 5be <printint+0xa7> putc(fd, buf[i]); 5a1: 8d 55 dc lea -0x24(%ebp),%edx 5a4: 8b 45 f4 mov -0xc(%ebp),%eax 5a7: 01 d0 add %edx,%eax 5a9: 0f b6 00 movzbl (%eax),%eax 5ac: 0f be c0 movsbl %al,%eax 5af: 83 ec 08 sub $0x8,%esp 5b2: 50 push %eax 5b3: ff 75 08 pushl 0x8(%ebp) 5b6: e8 35 ff ff ff call 4f0 <putc> 5bb: 83 c4 10 add $0x10,%esp while(--i >= 0) 5be: 83 6d f4 01 subl $0x1,-0xc(%ebp) 5c2: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 5c6: 79 d9 jns 5a1 <printint+0x8a> } 5c8: 90 nop 5c9: 90 nop 5ca: c9 leave 5cb: c3 ret 000005cc <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 5cc: f3 0f 1e fb endbr32 5d0: 55 push %ebp 5d1: 89 e5 mov %esp,%ebp 5d3: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 5d6: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 5dd: 8d 45 0c lea 0xc(%ebp),%eax 5e0: 83 c0 04 add $0x4,%eax 5e3: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 5e6: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 5ed: e9 59 01 00 00 jmp 74b <printf+0x17f> c = fmt[i] & 0xff; 5f2: 8b 55 0c mov 0xc(%ebp),%edx 5f5: 8b 45 f0 mov -0x10(%ebp),%eax 5f8: 01 d0 add %edx,%eax 5fa: 0f b6 00 movzbl (%eax),%eax 5fd: 0f be c0 movsbl %al,%eax 600: 25 ff 00 00 00 and $0xff,%eax 605: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 608: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 60c: 75 2c jne 63a <printf+0x6e> if(c == '%'){ 60e: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 612: 75 0c jne 620 <printf+0x54> state = '%'; 614: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 61b: e9 27 01 00 00 jmp 747 <printf+0x17b> } else { putc(fd, c); 620: 8b 45 e4 mov -0x1c(%ebp),%eax 623: 0f be c0 movsbl %al,%eax 626: 83 ec 08 sub $0x8,%esp 629: 50 push %eax 62a: ff 75 08 pushl 0x8(%ebp) 62d: e8 be fe ff ff call 4f0 <putc> 632: 83 c4 10 add $0x10,%esp 635: e9 0d 01 00 00 jmp 747 <printf+0x17b> } } else if(state == '%'){ 63a: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 63e: 0f 85 03 01 00 00 jne 747 <printf+0x17b> if(c == 'd'){ 644: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 648: 75 1e jne 668 <printf+0x9c> printint(fd, *ap, 10, 1); 64a: 8b 45 e8 mov -0x18(%ebp),%eax 64d: 8b 00 mov (%eax),%eax 64f: 6a 01 push $0x1 651: 6a 0a push $0xa 653: 50 push %eax 654: ff 75 08 pushl 0x8(%ebp) 657: e8 bb fe ff ff call 517 <printint> 65c: 83 c4 10 add $0x10,%esp ap++; 65f: 83 45 e8 04 addl $0x4,-0x18(%ebp) 663: e9 d8 00 00 00 jmp 740 <printf+0x174> } else if(c == 'x' || c == 'p'){ 668: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 66c: 74 06 je 674 <printf+0xa8> 66e: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 672: 75 1e jne 692 <printf+0xc6> printint(fd, *ap, 16, 0); 674: 8b 45 e8 mov -0x18(%ebp),%eax 677: 8b 00 mov (%eax),%eax 679: 6a 00 push $0x0 67b: 6a 10 push $0x10 67d: 50 push %eax 67e: ff 75 08 pushl 0x8(%ebp) 681: e8 91 fe ff ff call 517 <printint> 686: 83 c4 10 add $0x10,%esp ap++; 689: 83 45 e8 04 addl $0x4,-0x18(%ebp) 68d: e9 ae 00 00 00 jmp 740 <printf+0x174> } else if(c == 's'){ 692: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 696: 75 43 jne 6db <printf+0x10f> s = (char*)*ap; 698: 8b 45 e8 mov -0x18(%ebp),%eax 69b: 8b 00 mov (%eax),%eax 69d: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 6a0: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 6a4: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 6a8: 75 25 jne 6cf <printf+0x103> s = "(null)"; 6aa: c7 45 f4 cb 09 00 00 movl $0x9cb,-0xc(%ebp) while(*s != 0){ 6b1: eb 1c jmp 6cf <printf+0x103> putc(fd, *s); 6b3: 8b 45 f4 mov -0xc(%ebp),%eax 6b6: 0f b6 00 movzbl (%eax),%eax 6b9: 0f be c0 movsbl %al,%eax 6bc: 83 ec 08 sub $0x8,%esp 6bf: 50 push %eax 6c0: ff 75 08 pushl 0x8(%ebp) 6c3: e8 28 fe ff ff call 4f0 <putc> 6c8: 83 c4 10 add $0x10,%esp s++; 6cb: 83 45 f4 01 addl $0x1,-0xc(%ebp) while(*s != 0){ 6cf: 8b 45 f4 mov -0xc(%ebp),%eax 6d2: 0f b6 00 movzbl (%eax),%eax 6d5: 84 c0 test %al,%al 6d7: 75 da jne 6b3 <printf+0xe7> 6d9: eb 65 jmp 740 <printf+0x174> } } else if(c == 'c'){ 6db: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 6df: 75 1d jne 6fe <printf+0x132> putc(fd, *ap); 6e1: 8b 45 e8 mov -0x18(%ebp),%eax 6e4: 8b 00 mov (%eax),%eax 6e6: 0f be c0 movsbl %al,%eax 6e9: 83 ec 08 sub $0x8,%esp 6ec: 50 push %eax 6ed: ff 75 08 pushl 0x8(%ebp) 6f0: e8 fb fd ff ff call 4f0 <putc> 6f5: 83 c4 10 add $0x10,%esp ap++; 6f8: 83 45 e8 04 addl $0x4,-0x18(%ebp) 6fc: eb 42 jmp 740 <printf+0x174> } else if(c == '%'){ 6fe: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 702: 75 17 jne 71b <printf+0x14f> putc(fd, c); 704: 8b 45 e4 mov -0x1c(%ebp),%eax 707: 0f be c0 movsbl %al,%eax 70a: 83 ec 08 sub $0x8,%esp 70d: 50 push %eax 70e: ff 75 08 pushl 0x8(%ebp) 711: e8 da fd ff ff call 4f0 <putc> 716: 83 c4 10 add $0x10,%esp 719: eb 25 jmp 740 <printf+0x174> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 71b: 83 ec 08 sub $0x8,%esp 71e: 6a 25 push $0x25 720: ff 75 08 pushl 0x8(%ebp) 723: e8 c8 fd ff ff call 4f0 <putc> 728: 83 c4 10 add $0x10,%esp putc(fd, c); 72b: 8b 45 e4 mov -0x1c(%ebp),%eax 72e: 0f be c0 movsbl %al,%eax 731: 83 ec 08 sub $0x8,%esp 734: 50 push %eax 735: ff 75 08 pushl 0x8(%ebp) 738: e8 b3 fd ff ff call 4f0 <putc> 73d: 83 c4 10 add $0x10,%esp } state = 0; 740: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) for(i = 0; fmt[i]; i++){ 747: 83 45 f0 01 addl $0x1,-0x10(%ebp) 74b: 8b 55 0c mov 0xc(%ebp),%edx 74e: 8b 45 f0 mov -0x10(%ebp),%eax 751: 01 d0 add %edx,%eax 753: 0f b6 00 movzbl (%eax),%eax 756: 84 c0 test %al,%al 758: 0f 85 94 fe ff ff jne 5f2 <printf+0x26> } } } 75e: 90 nop 75f: 90 nop 760: c9 leave 761: c3 ret 00000762 <free>: static Header base; static Header *freep; void free(void *ap) { 762: f3 0f 1e fb endbr32 766: 55 push %ebp 767: 89 e5 mov %esp,%ebp 769: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 76c: 8b 45 08 mov 0x8(%ebp),%eax 76f: 83 e8 08 sub $0x8,%eax 772: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 775: a1 68 0c 00 00 mov 0xc68,%eax 77a: 89 45 fc mov %eax,-0x4(%ebp) 77d: eb 24 jmp 7a3 <free+0x41> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 77f: 8b 45 fc mov -0x4(%ebp),%eax 782: 8b 00 mov (%eax),%eax 784: 39 45 fc cmp %eax,-0x4(%ebp) 787: 72 12 jb 79b <free+0x39> 789: 8b 45 f8 mov -0x8(%ebp),%eax 78c: 3b 45 fc cmp -0x4(%ebp),%eax 78f: 77 24 ja 7b5 <free+0x53> 791: 8b 45 fc mov -0x4(%ebp),%eax 794: 8b 00 mov (%eax),%eax 796: 39 45 f8 cmp %eax,-0x8(%ebp) 799: 72 1a jb 7b5 <free+0x53> for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 79b: 8b 45 fc mov -0x4(%ebp),%eax 79e: 8b 00 mov (%eax),%eax 7a0: 89 45 fc mov %eax,-0x4(%ebp) 7a3: 8b 45 f8 mov -0x8(%ebp),%eax 7a6: 3b 45 fc cmp -0x4(%ebp),%eax 7a9: 76 d4 jbe 77f <free+0x1d> 7ab: 8b 45 fc mov -0x4(%ebp),%eax 7ae: 8b 00 mov (%eax),%eax 7b0: 39 45 f8 cmp %eax,-0x8(%ebp) 7b3: 73 ca jae 77f <free+0x1d> break; if(bp + bp->s.size == p->s.ptr){ 7b5: 8b 45 f8 mov -0x8(%ebp),%eax 7b8: 8b 40 04 mov 0x4(%eax),%eax 7bb: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 7c2: 8b 45 f8 mov -0x8(%ebp),%eax 7c5: 01 c2 add %eax,%edx 7c7: 8b 45 fc mov -0x4(%ebp),%eax 7ca: 8b 00 mov (%eax),%eax 7cc: 39 c2 cmp %eax,%edx 7ce: 75 24 jne 7f4 <free+0x92> bp->s.size += p->s.ptr->s.size; 7d0: 8b 45 f8 mov -0x8(%ebp),%eax 7d3: 8b 50 04 mov 0x4(%eax),%edx 7d6: 8b 45 fc mov -0x4(%ebp),%eax 7d9: 8b 00 mov (%eax),%eax 7db: 8b 40 04 mov 0x4(%eax),%eax 7de: 01 c2 add %eax,%edx 7e0: 8b 45 f8 mov -0x8(%ebp),%eax 7e3: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 7e6: 8b 45 fc mov -0x4(%ebp),%eax 7e9: 8b 00 mov (%eax),%eax 7eb: 8b 10 mov (%eax),%edx 7ed: 8b 45 f8 mov -0x8(%ebp),%eax 7f0: 89 10 mov %edx,(%eax) 7f2: eb 0a jmp 7fe <free+0x9c> } else bp->s.ptr = p->s.ptr; 7f4: 8b 45 fc mov -0x4(%ebp),%eax 7f7: 8b 10 mov (%eax),%edx 7f9: 8b 45 f8 mov -0x8(%ebp),%eax 7fc: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 7fe: 8b 45 fc mov -0x4(%ebp),%eax 801: 8b 40 04 mov 0x4(%eax),%eax 804: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 80b: 8b 45 fc mov -0x4(%ebp),%eax 80e: 01 d0 add %edx,%eax 810: 39 45 f8 cmp %eax,-0x8(%ebp) 813: 75 20 jne 835 <free+0xd3> p->s.size += bp->s.size; 815: 8b 45 fc mov -0x4(%ebp),%eax 818: 8b 50 04 mov 0x4(%eax),%edx 81b: 8b 45 f8 mov -0x8(%ebp),%eax 81e: 8b 40 04 mov 0x4(%eax),%eax 821: 01 c2 add %eax,%edx 823: 8b 45 fc mov -0x4(%ebp),%eax 826: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 829: 8b 45 f8 mov -0x8(%ebp),%eax 82c: 8b 10 mov (%eax),%edx 82e: 8b 45 fc mov -0x4(%ebp),%eax 831: 89 10 mov %edx,(%eax) 833: eb 08 jmp 83d <free+0xdb> } else p->s.ptr = bp; 835: 8b 45 fc mov -0x4(%ebp),%eax 838: 8b 55 f8 mov -0x8(%ebp),%edx 83b: 89 10 mov %edx,(%eax) freep = p; 83d: 8b 45 fc mov -0x4(%ebp),%eax 840: a3 68 0c 00 00 mov %eax,0xc68 } 845: 90 nop 846: c9 leave 847: c3 ret 00000848 <morecore>: static Header* morecore(uint nu) { 848: f3 0f 1e fb endbr32 84c: 55 push %ebp 84d: 89 e5 mov %esp,%ebp 84f: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if(nu < 4096) 852: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 859: 77 07 ja 862 <morecore+0x1a> nu = 4096; 85b: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 862: 8b 45 08 mov 0x8(%ebp),%eax 865: c1 e0 03 shl $0x3,%eax 868: 83 ec 0c sub $0xc,%esp 86b: 50 push %eax 86c: e8 57 fc ff ff call 4c8 <sbrk> 871: 83 c4 10 add $0x10,%esp 874: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 877: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 87b: 75 07 jne 884 <morecore+0x3c> return 0; 87d: b8 00 00 00 00 mov $0x0,%eax 882: eb 26 jmp 8aa <morecore+0x62> hp = (Header*)p; 884: 8b 45 f4 mov -0xc(%ebp),%eax 887: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 88a: 8b 45 f0 mov -0x10(%ebp),%eax 88d: 8b 55 08 mov 0x8(%ebp),%edx 890: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 893: 8b 45 f0 mov -0x10(%ebp),%eax 896: 83 c0 08 add $0x8,%eax 899: 83 ec 0c sub $0xc,%esp 89c: 50 push %eax 89d: e8 c0 fe ff ff call 762 <free> 8a2: 83 c4 10 add $0x10,%esp return freep; 8a5: a1 68 0c 00 00 mov 0xc68,%eax } 8aa: c9 leave 8ab: c3 ret 000008ac <malloc>: void* malloc(uint nbytes) { 8ac: f3 0f 1e fb endbr32 8b0: 55 push %ebp 8b1: 89 e5 mov %esp,%ebp 8b3: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 8b6: 8b 45 08 mov 0x8(%ebp),%eax 8b9: 83 c0 07 add $0x7,%eax 8bc: c1 e8 03 shr $0x3,%eax 8bf: 83 c0 01 add $0x1,%eax 8c2: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 8c5: a1 68 0c 00 00 mov 0xc68,%eax 8ca: 89 45 f0 mov %eax,-0x10(%ebp) 8cd: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 8d1: 75 23 jne 8f6 <malloc+0x4a> base.s.ptr = freep = prevp = &base; 8d3: c7 45 f0 60 0c 00 00 movl $0xc60,-0x10(%ebp) 8da: 8b 45 f0 mov -0x10(%ebp),%eax 8dd: a3 68 0c 00 00 mov %eax,0xc68 8e2: a1 68 0c 00 00 mov 0xc68,%eax 8e7: a3 60 0c 00 00 mov %eax,0xc60 base.s.size = 0; 8ec: c7 05 64 0c 00 00 00 movl $0x0,0xc64 8f3: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 8f6: 8b 45 f0 mov -0x10(%ebp),%eax 8f9: 8b 00 mov (%eax),%eax 8fb: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 8fe: 8b 45 f4 mov -0xc(%ebp),%eax 901: 8b 40 04 mov 0x4(%eax),%eax 904: 39 45 ec cmp %eax,-0x14(%ebp) 907: 77 4d ja 956 <malloc+0xaa> if(p->s.size == nunits) 909: 8b 45 f4 mov -0xc(%ebp),%eax 90c: 8b 40 04 mov 0x4(%eax),%eax 90f: 39 45 ec cmp %eax,-0x14(%ebp) 912: 75 0c jne 920 <malloc+0x74> prevp->s.ptr = p->s.ptr; 914: 8b 45 f4 mov -0xc(%ebp),%eax 917: 8b 10 mov (%eax),%edx 919: 8b 45 f0 mov -0x10(%ebp),%eax 91c: 89 10 mov %edx,(%eax) 91e: eb 26 jmp 946 <malloc+0x9a> else { p->s.size -= nunits; 920: 8b 45 f4 mov -0xc(%ebp),%eax 923: 8b 40 04 mov 0x4(%eax),%eax 926: 2b 45 ec sub -0x14(%ebp),%eax 929: 89 c2 mov %eax,%edx 92b: 8b 45 f4 mov -0xc(%ebp),%eax 92e: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 931: 8b 45 f4 mov -0xc(%ebp),%eax 934: 8b 40 04 mov 0x4(%eax),%eax 937: c1 e0 03 shl $0x3,%eax 93a: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 93d: 8b 45 f4 mov -0xc(%ebp),%eax 940: 8b 55 ec mov -0x14(%ebp),%edx 943: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 946: 8b 45 f0 mov -0x10(%ebp),%eax 949: a3 68 0c 00 00 mov %eax,0xc68 return (void*)(p + 1); 94e: 8b 45 f4 mov -0xc(%ebp),%eax 951: 83 c0 08 add $0x8,%eax 954: eb 3b jmp 991 <malloc+0xe5> } if(p == freep) 956: a1 68 0c 00 00 mov 0xc68,%eax 95b: 39 45 f4 cmp %eax,-0xc(%ebp) 95e: 75 1e jne 97e <malloc+0xd2> if((p = morecore(nunits)) == 0) 960: 83 ec 0c sub $0xc,%esp 963: ff 75 ec pushl -0x14(%ebp) 966: e8 dd fe ff ff call 848 <morecore> 96b: 83 c4 10 add $0x10,%esp 96e: 89 45 f4 mov %eax,-0xc(%ebp) 971: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 975: 75 07 jne 97e <malloc+0xd2> return 0; 977: b8 00 00 00 00 mov $0x0,%eax 97c: eb 13 jmp 991 <malloc+0xe5> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 97e: 8b 45 f4 mov -0xc(%ebp),%eax 981: 89 45 f0 mov %eax,-0x10(%ebp) 984: 8b 45 f4 mov -0xc(%ebp),%eax 987: 8b 00 mov (%eax),%eax 989: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 98c: e9 6d ff ff ff jmp 8fe <malloc+0x52> } } 991: c9 leave 992: c3 ret
frame 1, 07 setrepeat 2 frame 2, 07 frame 3, 07 dorepeat 2 frame 2, 26 setrepeat 2 frame 0, 05 frame 4, 05 dorepeat 7 endanim
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1995 -- All Rights Reserved PROJECT: PC GEOS MODULE: Kernel FILE: geodesPatchResource.asm AUTHOR: Paul Canavese, Jan 27, 1995 ROUTINES: Name Description ---- ----------- (See geodesPatch.asm for an overview to the patching code.) APPLY A PATCH TO A RESOURCE When a resource is loaded in, check if there is patch data for that resource. If so, apply it. GeodePatchLoadResource Load the resource, and see if patches need to be applied. ------------------------------------------------------------- GeodeLoadPatchedResource Make sure the resource block is big enough for patching, read in the resource from the geode file, patch it, and resize the block to its final size. SearchPatchResourceList Check each entry in the list for the resource being loaded. ------------------------------------------------------------- GeodePatchInitLMemBlock This is a hack to make "resedit"- produced files work on an EC system. GeodePatchResource Patch a resource. ------------------------------------------------------------- GeodePatchData Apply some patches to a segment of code, relocations, etc. REVISION HISTORY: Name Date Description ---- ---- ----------- PC 1/27/95 Initial revision DESCRIPTION: Code to facilitate the actual patching of a resource. $Id: geodesPatchResource.asm,v 1.1 97/04/05 01:12:23 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ kcode segment if USE_PATCHES COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GeodePatchLoadResource %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Load the resource, and see if patches need to be applied. CALLED BY: DoLoadResource PASS: ax - segment address of temporary block bx - handle of temporary block cx - size of resource if resource is dgroup, then this size doesn't include the udata size dx - handle of resource bp - handle of block that relocation is relative to (?) ds - core block of owner of resource si - resource number * 2 RETURN: carry SET if relocations have been performed carry CLEAR otherwise (relocations should be loaded from the original geode) DESTROYED: bx, es PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: Locks the PatchedResourceList every time a resource is loaded -- is this too much overhead? REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 1/17/94 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GeodePatchLoadResource proc near passedBP local hptr push bp tempBlock local hptr push bx ; Handle of resource ; block. .enter ; Streamlined for no patches... if USE_BUG_PATCHES tryGeneralPatchList:: ; Are there any general patches? tst ds:[GH_generalPatchData] jnz searchGeneralPatchList endif tryLanguagePatchList:: if MULTI_LANGUAGE ; Are there any language patches? tst ds:[GH_languagePatchData] jnz searchLanguagePatchList noPatchDataFound: endif ; No patch data found for this resource... just load ; in the resource normally. call LoadResourceDataFar clc ; Use normal relocations exit: .leave ret ; <--- EXIT HERE! if USE_BUG_PATCHES searchGeneralPatchList: mov bx, ds:[GH_generalPatchData] ; si = twice the resource number being loaded. call SearchPatchResourceList jnc found jmp tryLanguagePatchList endif if MULTI_LANGUAGE searchLanguagePatchList: mov bx, ds:[GH_languagePatchData] ; si = twice the resource number being loaded. call SearchPatchResourceList jc noPatchDataFound endif found:: push bx, bp mov bx, ss:[tempBlock] mov bp, ss:[passedBP] call GeodeLoadPatchedResource pop bx, bp ; Unlock the patch data call NearUnlock jmp exit GeodePatchLoadResource endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GeodeLoadPatchedResource %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Make sure the resource block is big enough for patching, read in the resource from the geode file, patch it, and resize the block to its final size. CALLED BY: GeodePatchLoadResource PASS: ax - segment address of temporary block bx - handle of temporary block temporary block is the size that it will be after patching occurs. cx - size of resource if resource is dgroup, then this size doesn't include the udata size dx - handle of resource bp - handle of block that relocation is relative to (?) ds - core block of owner of resource si - resource number * 2 es:di - PatchedResourceEntry RETURN: DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PC 1/17/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GeodeLoadPatchedResource proc near uses bx,cx,dx,si,di,bp passedBP local hptr push bp resourceSize local word push cx ; Size of the resource ; before patching. reAllocSize local word push cx ; Size to reallocate ; the resource block ; to after patching. .enter ; Is this resource dgroup? cmp si, 2 jne notDgroup ; Resource is dgroup. Remember the current size of the ; resource block, so we can reallocate the resource block to ; it later (cx does not account for udata). push ax, ds LoadVarSeg ds, ax call GetByteSize ; ax, cx = size mov ss:[reAllocSize], ax pop ax, ds notDgroup: ; Check if more room is needed to apply the patches than we ; currently have. cmp cx, es:[di].PRE_maxResourceSize jae afterReAlloc ; Enough space already. reAlloc:: ; Reallocate the resource to the maximum space needed while ; patching this resource. mov ax, es:[di].PRE_maxResourceSize mov ch, mask HAF_NO_ERR call MemReAlloc afterReAlloc: ; Determine size of resource to load from original file. mov cx, ss:[resourceSize] ; cx = original size of resource. ; If size is zero, this is a new resource (nothing to load). jcxz afterLoad ; Resource is new. ; Load the original version of the resource from the geode file. call LoadResourceDataFar afterLoad: ; Perform the patches on the resource. push bp mov bp, ss:[passedBP] call GeodePatchResource pop bp pushf ; Remember if we did relocations. ; Now restore the resource to its normal size. Since the block ; is still locked, we'll get its address back in AX mov ax, ss:[reAllocSize] mov ch, mask HAF_NO_ERR call MemReAlloc call GeodePatchInitLMemBlock popf ; Remember if we did relocations. .leave ret GeodeLoadPatchedResource endp if FULL_EXECUTE_IN_PLACE and MULTI_LANGUAGE GeodeLoadPatchedResourceFar proc far call GeodeLoadPatchedResource ret GeodeLoadPatchedResourceFar endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchPatchResourceList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Check each entry in the list for the resource being loaded. CALLED BY: GeodePatchLoadResource PASS: bx = handle of patch data list si = twice the resource number being loaded RETURN: if resource is found, carry clear es = patch data (LOCKED) di = matching entry else carry set DESTROYED: es, si SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PC 1/ 4/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchPatchResourceList proc far uses ax, bx, cx, ds, si .enter ; Search the lock the patch list. call NearLock mov es, ax ; Prepare search loop. mov_tr ax, si ; Twice the resource number. shr ax ; Resource number. mov cx, es:[PDH_count] mov si, offset PDH_resources startLoop: ; Check each entry for our resource. cmp ax, es:[si].PRE_id je found ; This is the resource. add si, size PatchedResourceEntry loop startLoop ; Not found... unlock patch list. call NearUnlock stc jmp exit found: mov di, si ; Offset of matching entry. exit: .leave ret SearchPatchResourceList endp endif ; USE_PATCHES kcode ends GLoad segment resource if USE_PATCHES COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GeodePatchInitLMemBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This is a hack to make "resedit"-produced files work on an EC system. CALLED BY: GeodeLoadPatchedResource PASS: ss:bp - inherited local vars ax - address of temporary block bx - handle of temp block dx - resource handle RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 7/22/94 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GeodePatchInitLMemBlock proc far uses ax,bx,dx,ds .enter push bx mov bx, dx LoadVarSeg ds, dx test ds:[bx].HM_flags, mask HF_LMEM pop bx jz done mov dx, ax ; resource segment mov_tr ax, bx ; handle done: .leave ret GeodePatchInitLMemBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GeodePatchResource %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Patch a resource CALLED BY: GeodePatchLoadResource, GeodePatchCoreBlock PASS: ax - segment address at which to load resource dx - handle of resource ds - core block es - PatchDataHeader es:di - PatchedResourceEntry for patch data RETURN: carry SET if relocations loaded from patch file, carry CLEAR otherwise DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 1/17/94 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GeodePatchResource proc far uses ax,bx,cx,dx,di,si passedBP local word push bp resourceSegment local sptr push ax resourceHandle local hptr push dx coreBlock local sptr.GeodeHeader push ds patchedResourceEntry local fptr.PatchedResourceEntry push es, di patchBlock local hptr patchBlockSeg local sptr relocBlock local hptr .enter ; Allocate a block in which to read the patch data. mov ax, es:[di].PRE_size push ax ; Resource patch size. add ax, es:[di].PRE_relocSize push ax ; Total size. mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK call MemAllocFar mov ds, ax mov ss:[patchBlock], bx mov ss:[patchBlockSeg], ax ; Load the patch data from the patch file. mov al, FILE_POS_START movdw cxdx, es:[di].PRE_pos mov bx, es:[PDH_fileHandle] call FilePosFar clr dx pop cx ; Total size. mov al, FILE_NO_ERRORS call FileReadFar ; Apply the patches. mov dx, es:[di].PRE_maxResourceSize mov es, ss:[resourceSegment] mov bx, ss:[resourceHandle] pop cx ; resource patch size clr si call GeodePatchData ; ds:si now points to ; reloc patches. ; Now that all patches have been applied, apply the ; relocations. If there are no relocations in the patch file, ; then relocations will be done normally. les di, ss:[patchedResourceEntry] mov ax, es:[di].PRE_relocSize tst ax ; clears carry LONG jz doneFree patchReloc:: ; Allocate a block to hold the relocations, using the size ; stored in the PatchedResourceEntry. mov ds, ss:[coreBlock] mov ax, es:[di].PRE_maxRelocSize mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK call MemAllocFar mov ss:[relocBlock], bx push ax ; Relocation block segment. if FULL_EXECUTE_IN_PLACE ; Is this an XIP resource? If so, there are no old relocations. test ds:[GH_geodeAttr], mask GA_XIP jnz afterRead endif ; Is this is a new resource? If so, there are no old relocations. mov bx, es:[di].PRE_id cmp bx, es:[PDH_origResCount] jae afterRead ; Read in the old relocation table from the geode file. shl bx add bx, ds:[GH_resRelocOff] mov cx, ds:[bx] ; Old relocation size. mov bx, ds:[GH_geoHandle] ; Handle to .GEO file. mov ds, ax clr dx ; Destination block. mov al, FILE_NO_ERRORS call FileReadFar afterRead: ; Patch the old relocation table. mov cx, es:[di].PRE_size add cx, es:[di].PRE_relocSize ; End of reloc patches. mov dx, es:[di].PRE_maxRelocSize ; Size of reloc block. pop es ; Relocation block. mov ds, ss:[patchBlockSeg] ; Patch information. call GeodePatchData ; Prepare for performing the relocations. segmov ds, es ; Relocation block. mov es, ss:[resourceSegment] clr si ; Perform the relocations. relocLoop: mov ax, {word} ds:[si].GRE_info mov bx, ds:[si].GRE_offset push ds, bp, dx, si mov ds, ss:[coreBlock] mov cx, ss:[resourceHandle] mov bp, ss:[passedBP] call DoRelocation pop ds, bp, dx, si add si, size GeodeRelocationEntry cmp si, dx jb relocLoop mov bx, ss:[relocBlock] call MemFree stc ; signal - relocations handled doneFree: mov bx, ss:[patchBlock] pushf call MemFree popf mov ds, ss:[coreBlock] .leave ret GeodePatchResource endp GeodePatchResourceFar proc far call GeodePatchResource ret GeodePatchResourceFar endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GeodePatchData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Apply some patches to a segment of code, relocations, etc. CALLED BY: GeodePatchResource PASS: es - segment to which to apply patches dx - size of segment ds:si - array of PatchElement structures ds:cx - pointer to end of array RETURN: ds:si - points at first PatchElement after this group DESTROYED: ax,bx,cx,di PSEUDO CODE/STRATEGY: SIDE EFFECTS: Do not operate heavy machinery after reading this routine. REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 1/24/94 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GeodePatchData proc near patchLoop: mov ax, ds:[si].PE_flags Assert record ax PatchFlags mov bx, ax andnf bx, mask PF_TYPE ; Rotating left 3 times is probably faster than shifting right ; 13 times... CheckHack <offset PF_TYPE eq 14> rol bx rol bx rol bx push si, cx call cs:patchTable[bx] ; bx <- patch size pop si, cx patchNext:: lea si, ds:[si][bx][size PatchElement] cmp si, cx jb patchLoop ret ;;---------------------------------------- patchReplace: mov di, ds:[si].PE_pos mov ax, ds:[si].PE_flags mov cx, ax andnf cx, mask PF_SIZE andnf ax, mask PF_TYPE cmp ax, PT_INSERT_ZERO shl offset PF_TYPE je insertZero mov bx, cx ; return size lea si, ds:[si].PE_data EC < call checkRepMovsb > rep movsb replaceDone: retn ;;---------------------------------------- insertZero: clr ax, bx Assert okForRepScasb ; (really Assert okForRepStosb!) rep stosb jmp replaceDone ;;---------------------------------------- patchDelete: mov di, ds:[si].PE_pos andnf ax, mask PF_SIZE mov si, di add si, ax mov cx, dx ; segment size sub cx, si push ds segmov ds, es EC < call checkRepMovsb > rep movsb clr bx ; return size pop ds retn ;;---------------------------------------- patchInsert: ; ax - size andnf ax, mask PF_SIZE mov bx, ds:[si].PE_pos ; source ; ; # bytes to move = ResourceSize - Position - insert count ; mov cx, dx ; segment size sub cx, bx EC < ERROR_Z PATCH_FILE_ERROR > sub cx, ax EC < ERROR_S PATCH_FILE_ERROR > ; If it's an insertion at the end, then there's nothing to move LONG jz patchReplace push ds, si ; PatchElement mov si, bx add si, cx dec si mov di, bx add di, ax ; dest add di, cx dec di segmov ds, es Assert fptr dssi Assert fptr esdi std rep movsb cld pop ds, si ; PatchElement jmp patchReplace patchTable nptr.near \ patchReplace, patchDelete, patchInsert, patchInsert if ERROR_CHECK checkRepMovsb: ; Assert okForRepMovsb retn endif GeodePatchData endp endif ; USE_PATCHES GLoad ends
; A124297: a(n) = 5*F(n)^2 + 5*F(n) + 1, where F(n) = Fibonacci(n). ; 1,11,11,31,61,151,361,911,2311,5951,15401,40051,104401,272611,712531,1863551,4875781,12760031,33398201,87424711,228859951,599129311,1568486161,4106261531,10750188961,28144128251,73681909211,192901135711,505020747661,1322159893351,3461456968201,9062207833151,23725161388951,62113268013311,162614629188281,425730597768451,1114577128871281,2918000731816531,7639424974303651,20000274041790911,52361396909490901,137083916295800111,358890351345449561,939587136717207031,2459871057150370111,6440026032054760351,16860207034678966561,44140595064968052011,115561578148876157761,302544139363297302251,792070839911303598251,2073668380322538222751,5428934300978523649501,14213134522487170035511,37210469266279336346281,97418273276021326202351,255044350561251479349031,667714778406870436132031,1748099984657963990422601,4576585175564763020798611,11981655542032670719011601,31368381450527336268937411,82123488809539770867540211,215002084978076496246124031,562882766124664670563012261,1473646213395876988047533951,3858055874062900718876391161,10100521408792719066483062311,26443508352315084803771020111,69230003648152257565929645151,181246502592141238438315786801,474509504128270730514415233851,1242282009792669776414625304801,3252336525249736694804553589211,8514727565956537227383823761531,22291846172619870002806798902751,58360810951903064715881242452781,152790586683089311095141479169031,400010949097364847454692415273801,1047242260609005197104389537585311,2741715832729650688579079188634551,7177905237579946779188904790403711,18791999880010189504264294935814361,49198094402450621499436696532362531,128802283327341674615155170929834161,337208755579574401732970909041024051,882823983411381529591809025245683011 seq $0,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. add $0,1 bin $0,2 mul $0,10 add $0,1
; A029929: a(n) = n*(n + ceiling(2^n/12)). ; 0,2,6,12,24,40,72,126,240,468,960,2002,4248,9048,19320,41190,87648,185980,393552,830490,1748040,3670464,7690056,16078702,33555024,69905700,145403232,301990626,626350200,1297438888,2684355480,5547667062,11453247168,23622321228,48676297200,100215904810,206158431528,423770107920,870446706792,1786706396670,3665038760880,7513329458164,15393162790656,31519333331442,64504682164824,131941395335160,269746852683192,551221829393926,1125899906844960,2298712309806108,4691249611846800 mov $2,2 pow $2,$0 div $2,12 mov $3,$0 mul $3,$2 mov $1,$3 add $1,$0 mov $4,$0 mul $4,$0 add $1,$4
;/* ; * Microsoft Confidential ; * Copyright (C) Microsoft Corporation 1991 ; * All Rights Reserved. ; */ CODE SEGMENT BYTE PUBLIC 'CODE' ASSUME CS:CODE,DS:CODE IF1 ; %OUT EGA.CPI creation file ; %OUT . ; %OUT CP SRC files: ; %OUT . ; %OUT . CODE PAGE: 865 ENDIF EGA865: DW LEN_865 ; SIZE OF ENTRY HEADER DW POST_EGA865,0 ; POINTER TO NEXT HEADER DW 1 ; DEVICE TYPE DB "EGA " ; DEVICE SUBTYPE ID DW 865 ; CODE PAGE ID DW 3 DUP(0) ; RESERVED DW OFFSET DATA865,0 ; POINTER TO FONTS LEN_865 EQU ($-EGA865) ; ; DATA865:DW 1 ; CART/NON-CART DW 3 ; # OF FONTS DW LEN_D865 ; LENGTH OF DATA D865: ; DB 16,8 ; CHARACTER BOX SIZE DB 0,0 ; ASPECT RATIO (UNUSED) DW 256 ; NUMBER OF CHARACTERS ; INCLUDE 865-8X16.ASM ; ; DB 14,8 ; CHARACTER BOX SIZE DB 0,0 ; ASPECT RATIO (UNUSED) DW 256 ; NUMBER OF CHARACTERS ; INCLUDE 865-8X14.ASM ; ; DB 8,8 ; CHARACTER BOX SIZE DB 0,0 ; ASPECT RATIO (UNUSED) DW 256 ; NUMBER OF CHARACTERS ; INCLUDE 865-8X8.ASM ; ; LEN_D865 EQU ($-D865) ; ; POST_EGA865 EQU $ ; ; CODE ENDS ; END ;  
section .text global _start _start: mov edx,len mov ecx,msg mov ebx,1 mov eax,4 int 0x80 mov eax,1 mov ebx,0 int 0x80 section .data msg db 'Hi Everyone~!', 0xa len equ $ - msg
#include "MercuryWindow.h" //#include "MercuryMessageManager.h" #include <HgInput.h> MercuryWindow::MercuryWindow(const MString& title, MercuryWindow::Dimensions d, int bits, int depthBits, bool fullscreen) :m_title(title), m_requestedDimenstions(d), m_bits(bits), m_depthBits(depthBits), m_fullscreen(fullscreen), m_iLastMouseX(0),m_iLastMouseY(0),m_inFocus(false), m_close(false), m_altEnter(false) { // MESSAGEMAN.GetValue( "Input.CursorGrabbed" )->SetBool( true ); } MercuryWindow::~MercuryWindow() { } void MercuryWindow::ScanForKeystrokes() { using namespace ENGINE::INPUT; bool alt_enter = ScanForKeyCombo(KeyCodes::KEY_ALT, KeyCodes::KEY_ENTER); if (alt_enter && !m_altEnter) { ToggleFullscreen(!m_fullscreen); } m_altEnter = alt_enter; //remember last combo so that we can filter repeats if (ScanForKeyCombo(KeyCodes::KEY_ALT, KeyCodes::KEY_F4)) { m_close = true; } } void MercuryWindow::ToggleFullscreen(bool fullscreen) { m_fullscreen = fullscreen; TryFullscreen(); } MercuryWindow* MercuryWindow::m_windowInstance; /* * Copyright (c) 2008, Joshua Allen * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of the Mercury Engine nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r8 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x7613, %rsi lea addresses_A_ht+0x9613, %rdi nop dec %rax mov $42, %rcx rep movsl add %r8, %r8 lea addresses_D_ht+0x12593, %rbp nop nop nop nop nop add $9311, %r12 movl $0x61626364, (%rbp) nop nop cmp $20352, %rax lea addresses_UC_ht+0xa723, %rax nop cmp $34587, %rbp mov $0x6162636465666768, %r12 movq %r12, %xmm5 movups %xmm5, (%rax) nop nop sub $40342, %rcx lea addresses_WT_ht+0x9a73, %rsi lea addresses_WC_ht+0xd263, %rdi nop nop cmp %rbx, %rbx mov $10, %rcx rep movsw nop sub $21572, %r12 lea addresses_WT_ht+0x10a13, %rax add %rsi, %rsi mov $0x6162636465666768, %r8 movq %r8, (%rax) nop nop nop nop sub %rbp, %rbp lea addresses_WT_ht+0x1b013, %rsi lea addresses_WC_ht+0xe7d3, %rdi sub $60541, %rax mov $87, %rcx rep movsw nop nop and %rdi, %rdi lea addresses_A_ht+0x1434d, %rsi lea addresses_WT_ht+0x2853, %rdi clflush (%rsi) nop nop nop nop nop xor $14353, %rbp mov $88, %rcx rep movsb nop nop nop xor $40618, %rbx lea addresses_A_ht+0x4113, %rcx nop nop and $42199, %rsi movl $0x61626364, (%rcx) inc %rbx lea addresses_normal_ht+0x10213, %rsi lea addresses_normal_ht+0xdbeb, %rdi nop sub %rbp, %rbp mov $29, %rcx rep movsb nop nop sub $31517, %rax lea addresses_A_ht+0x5e13, %rsi lea addresses_WC_ht+0x1bf1b, %rdi nop nop and $55101, %r12 mov $1, %rcx rep movsw nop nop nop and %r8, %r8 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r8 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r15 push %rax push %rcx push %rdi // Store mov $0x7d4, %rax nop lfence movb $0x51, (%rax) nop nop add $2145, %r15 // Faulty Load lea addresses_RW+0x3e13, %r15 nop nop sub $49761, %rax vmovups (%r15), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %rcx lea oracles, %r12 and $0xff, %rcx shlq $12, %rcx mov (%r12,%rcx,1), %rcx pop %rdi pop %rcx pop %rax pop %r15 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_P', 'size': 1, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_A_ht', 'size': 4, 'AVXalign': True}} {'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}} {'32': 14201} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x1c418, %rsi nop nop nop sub %rax, %rax movw $0x6162, (%rsi) add $2836, %r9 lea addresses_WC_ht+0x12c7d, %rcx add $36250, %r9 mov (%rcx), %r14 nop nop nop nop nop cmp $56479, %r9 lea addresses_normal_ht+0x14498, %rcx nop nop nop nop cmp $14459, %r10 mov (%rcx), %r9d nop nop nop nop cmp %r9, %r9 lea addresses_A_ht+0x140d4, %r10 nop nop nop sub $14801, %r9 movw $0x6162, (%r10) nop nop sub $4066, %r14 lea addresses_normal_ht+0xc498, %r14 nop nop nop nop nop xor $17439, %rax and $0xffffffffffffffc0, %r14 movntdqa (%r14), %xmm3 vpextrq $1, %xmm3, %rdx nop nop cmp %rdx, %rdx lea addresses_WT_ht+0x5c98, %rax nop add %rsi, %rsi movb (%rax), %dl dec %rdx lea addresses_normal_ht+0x14e98, %rsi lea addresses_A_ht+0x2098, %rdi nop nop nop nop nop inc %r9 mov $7, %rcx rep movsl nop nop nop nop nop xor $54166, %r10 lea addresses_WT_ht+0x1b498, %rsi lea addresses_normal_ht+0x1298, %rdi nop nop nop nop nop sub %r14, %r14 mov $106, %rcx rep movsq and $11810, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %rax push %rbx push %rdi // Store lea addresses_RW+0x1cf88, %rax nop nop nop nop dec %r12 movw $0x5152, (%rax) nop nop nop nop sub %r11, %r11 // Load lea addresses_RW+0x12860, %rbx nop dec %r10 vmovups (%rbx), %ymm1 vextracti128 $0, %ymm1, %xmm1 vpextrq $0, %xmm1, %r12 nop cmp $38908, %rdi // Store lea addresses_US+0x1d498, %r12 xor $57806, %rax movw $0x5152, (%r12) nop nop dec %rbx // Faulty Load lea addresses_US+0x1d498, %r13 nop nop nop nop nop and $43733, %rbx vmovups (%r13), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %r12 lea oracles, %rdi and $0xff, %r12 shlq $12, %r12 mov (%rdi,%r12,1), %r12 pop %rdi pop %rbx pop %rax pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_RW', 'size': 2, 'AVXalign': False}} {'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_RW', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 2, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': True, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WC_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}} {'src': {'same': False, 'congruent': 11, 'NT': True, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'00': 21783, '49': 46} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
main: nor $s0, $0, $0 add $s1, $s0, $0 add $s2, $s0, $s0 sll $t1, $s2, 2 sra $t2, $s1, 4 srl $t3, $t2, 2 slt $t0, $t1, $s0
; /***************************************************************************** ; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers * ; ***************************************************************************** ; * Copyright 2021 Marco Spedaletti (asimov@mclink.it) ; * ; * Licensed under the Apache License, Version 2.0 (the "License"); ; * you may not use this file except in compliance with the License. ; * You may obtain a copy of the License at ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Unless required by applicable law or agreed to in writing, software ; * distributed under the License is distributed on an "AS IS" BASIS, ; * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; * See the License for the specific language governing permissions and ; * limitations under the License. ; *---------------------------------------------------------------------------- ; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0 ; * (la "Licenza"); è proibito usare questo file se non in conformità alla ; * Licenza. Una copia della Licenza è disponibile all'indirizzo: ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Se non richiesto dalla legislazione vigente o concordato per iscritto, ; * il software distribuito nei termini della Licenza è distribuito ; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o ; * implicite. Consultare la Licenza per il testo specifico che regola le ; * autorizzazioni e le limitazioni previste dalla medesima. ; ****************************************************************************/ ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ;* * ;* SQUARE ROOT CALCULATION ON 6809 * ;* * ;* by Marco Spedaletti * ;* * ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Numberl equ $14 ; number to find square root of low byte Numberh equ Numberl+1 ; number to find square root of high byte Reml equ $16 ; remainder low byte Remh equ Reml+1 ; remainder high byte templ equ $18 ; temp partial low byte temph equ templ+1 ; temp partial high byte Root equ $20 ; square root SQROOT LDA #$00 ; clear A STA <Reml ; clear remainder low byte STA <Remh ; clear remainder high byte STA <Root ; clear Root LDU #$08 ; 8 pairs of bits to do SQROOTL1 LSL <Root ; Root = Root * 2 LSL <Numberl ; shift highest bit of number .. ROL <Numberh ; LDB <Numberl LDB <Numberh LDB <Root ROL <Reml ; .. into remainder ROL <Remh ; LSL <Numberl ; shift highest bit of number .. ROL <Numberh ; ROL <Reml ; .. into remainder ROL <Remh ; LDA <Root ; copy Root .. STA <templ ; .. to templ LDA #$00 ; clear byte STA <temph ; clear temp high byte ORCC #$01 ; +1 ROL <templ ; temp = temp * 2 + 1 ROL <temph ; LDA <Remh ; get remainder high byte CMPA <temph ; comapre with partial high byte BLT SQROOTNX ; skip sub if remainder high byte smaller BNE SQROOTSB ; do sub if <> (must be remainder>partial !) LDA <Reml ; get remainder low byte CMPA <templ ; comapre with partial low byte BLT SQROOTNX ; skip sub if remainder low byte smaller ; else remainder>=partial so subtract then ; and add 1 to root. carry is always set here SQROOTSB LDA <Reml ; get remainder low byte SUBA <templ ; subtract partial low byte STA <Reml ; save remainder low byte LDA <Remh ; get remainder high byte SUBA <temph ; subtract partial high byte STA <Remh ; save remainder high byte INC <Root ; increment Root SQROOTNX LEAU -1, U ; decrement bit pair count CMPU #0 BNE SQROOTL1 ; loop if not all done RTS
/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ubx.cpp * * U-Blox protocol implementation. Following u-blox 6/7/8/9 Receiver Description * including Prototol Specification. * * @author Thomas Gubler <thomasgubler@student.ethz.ch> * @author Julian Oes <julian@oes.ch> * @author Anton Babushkin <anton.babushkin@me.com> * @author Beat Kueng <beat-kueng@gmx.net> * * @author Hannes Delago * (rework, add ubx7+ compatibility) * * @see https://www.u-blox.com/sites/default/files/products/documents/u-blox6-GPS-GLONASS-QZSS-V14_ReceiverDescrProtSpec_%28GPS.G6-SW-12013%29_Public.pdf * @see https://www.u-blox.com/sites/default/files/products/documents/u-blox8-M8_ReceiverDescrProtSpec_%28UBX-13003221%29_Public.pdf * @see https://www.u-blox.com/sites/default/files/ZED-F9P_InterfaceDescription_%28UBX-18010854%29.pdf */ #include <string.h> #include "rtcm.h" #include "ubx.h" #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #define SWAP16(X) ((((X) >> 8) & 0x00ff) | (((X) << 8) & 0xff00)) /**** Trace macros, disable for production builds */ #define UBX_TRACE_PARSER(...) {/*GPS_INFO(__VA_ARGS__);*/} // decoding progress in parse_char() #define UBX_TRACE_RXMSG(...) {/*GPS_INFO(__VA_ARGS__);*/} // Rx msgs in payload_rx_done() #define UBX_TRACE_SVINFO(...) {/*GPS_INFO(__VA_ARGS__);*/} // NAV-SVINFO processing (debug use only, will cause rx buffer overflows) /**** Warning macros, disable to save memory */ #define UBX_WARN(...) {GPS_WARN(__VA_ARGS__);} #define UBX_DEBUG(...) {/*GPS_WARN(__VA_ARGS__);*/} GPSDriverUBX::GPSDriverUBX(Interface gpsInterface, GPSCallbackPtr callback, void *callback_user, sensor_gps_s *gps_position, satellite_info_s *satellite_info, uint8_t dynamic_model, float heading_offset, UBXMode mode) : GPSBaseStationSupport(callback, callback_user), _interface(gpsInterface), _gps_position(gps_position), _satellite_info(satellite_info), _dyn_model(dynamic_model), _mode(mode), _heading_offset(heading_offset) { decodeInit(); } GPSDriverUBX::~GPSDriverUBX() { delete _rtcm_parsing; } int GPSDriverUBX::configure(unsigned &baudrate, const GPSConfig &config) { _configured = false; _output_mode = config.output_mode; ubx_payload_tx_cfg_prt_t cfg_prt[2]; uint16_t out_proto_mask = _output_mode == OutputMode::GPS ? UBX_TX_CFG_PRT_PROTO_UBX : (UBX_TX_CFG_PRT_PROTO_UBX | UBX_TX_CFG_PRT_PROTO_RTCM); uint16_t in_proto_mask = (_output_mode == OutputMode::GPS || _output_mode == OutputMode::GPSAndRTCM) ? (UBX_TX_CFG_PRT_PROTO_UBX | UBX_TX_CFG_PRT_PROTO_RTCM) : UBX_TX_CFG_PRT_PROTO_UBX; const bool auto_baudrate = baudrate == 0; if (_interface == Interface::UART) { /* try different baudrates */ const unsigned baudrates[] = {38400, 57600, 9600, 115200, 230400, 460800, 921600}; unsigned baud_i; unsigned desired_baudrate = auto_baudrate ? UBX_BAUDRATE_M8_AND_NEWER : baudrate; if ((_mode == UBXMode::RoverWithMovingBaseUART1) || (_mode == UBXMode::MovingBaseUART1)) { desired_baudrate = UART1_BAUDRATE_HEADING; } for (baud_i = 0; baud_i < sizeof(baudrates) / sizeof(baudrates[0]); baud_i++) { unsigned test_baudrate = baudrates[baud_i]; if (!auto_baudrate && baudrate != test_baudrate) { continue; // skip to next baudrate } UBX_DEBUG("baudrate set to %i", test_baudrate); setBaudrate(test_baudrate); /* flush input and wait for at least 20 ms silence */ decodeInit(); receive(20); decodeInit(); // try CFG-VALSET: if we get an ACK we know we can use protocol version 27+ int cfg_valset_msg_size = initCfgValset(); // UART1 cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1_STOPBITS, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1_DATABITS, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1_PARITY, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_RTCM3X, _output_mode == OutputMode::RTCM ? 0 : 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_UBX, 1, cfg_valset_msg_size); if (_output_mode != OutputMode::GPS) { cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_RTCM3X, 1, cfg_valset_msg_size); } cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_NMEA, 0, cfg_valset_msg_size); // TODO: are we ever connected to UART2? // USB cfgValset<uint8_t>(UBX_CFG_KEY_CFG_USBINPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_USBINPROT_RTCM3X, _output_mode == OutputMode::RTCM ? 0 : 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_USBINPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_USBOUTPROT_UBX, 1, cfg_valset_msg_size); if (_output_mode != OutputMode::GPS) { cfgValset<uint8_t>(UBX_CFG_KEY_CFG_USBOUTPROT_RTCM3X, 1, cfg_valset_msg_size); } cfgValset<uint8_t>(UBX_CFG_KEY_CFG_USBOUTPROT_NMEA, 0, cfg_valset_msg_size); bool cfg_valset_success = false; if (sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) == 0) { cfg_valset_success = true; } } if (cfg_valset_success) { _proto_ver_27_or_higher = true; // Now we only have to change the baudrate cfg_valset_msg_size = initCfgValset(); cfgValset<uint32_t>(UBX_CFG_KEY_CFG_UART1_BAUDRATE, desired_baudrate, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { continue; } /* no ACK is expected here, but read the buffer anyway in case we actually get an ACK */ waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, false); } else { _proto_ver_27_or_higher = false; UBX_DEBUG("trying old protocol"); /* Send a CFG-PRT message to set the UBX protocol for in and out * and leave the baudrate as it is, we just want an ACK-ACK for this */ memset(cfg_prt, 0, 2 * sizeof(ubx_payload_tx_cfg_prt_t)); cfg_prt[0].portID = UBX_TX_CFG_PRT_PORTID; cfg_prt[0].mode = UBX_TX_CFG_PRT_MODE; cfg_prt[0].baudRate = test_baudrate; cfg_prt[0].inProtoMask = in_proto_mask; cfg_prt[0].outProtoMask = out_proto_mask; cfg_prt[1].portID = UBX_TX_CFG_PRT_PORTID_USB; cfg_prt[1].mode = UBX_TX_CFG_PRT_MODE; cfg_prt[1].baudRate = test_baudrate; cfg_prt[1].inProtoMask = in_proto_mask; cfg_prt[1].outProtoMask = out_proto_mask; if (!sendMessage(UBX_MSG_CFG_PRT, (uint8_t *)cfg_prt, 2 * sizeof(ubx_payload_tx_cfg_prt_t))) { continue; } if (waitForAck(UBX_MSG_CFG_PRT, UBX_CONFIG_TIMEOUT, false) < 0) { /* try next baudrate */ continue; } if (auto_baudrate) { desired_baudrate = UBX_TX_CFG_PRT_BAUDRATE; } /* Send a CFG-PRT message again, this time change the baudrate */ cfg_prt[0].baudRate = desired_baudrate; cfg_prt[1].baudRate = desired_baudrate; if (!sendMessage(UBX_MSG_CFG_PRT, (uint8_t *)cfg_prt, 2 * sizeof(ubx_payload_tx_cfg_prt_t))) { continue; } /* no ACK is expected here, but read the buffer anyway in case we actually get an ACK */ waitForAck(UBX_MSG_CFG_PRT, UBX_CONFIG_TIMEOUT, false); } if (desired_baudrate != test_baudrate) { setBaudrate(desired_baudrate); decodeInit(); receive(20); decodeInit(); } /* at this point we have correct baudrate on both ends */ baudrate = desired_baudrate; break; } if (baud_i >= sizeof(baudrates) / sizeof(baudrates[0])) { return -1; // connection and/or baudrate detection failed } } else if (_interface == Interface::SPI) { // try CFG-VALSET: if we get an ACK we know we can use protocol version 27+ int cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_SPI_ENABLED, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_SPI_MAXFF, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_SPIINPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_SPIINPROT_RTCM3X, _output_mode == OutputMode::RTCM ? 0 : 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_SPIINPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_SPIOUTPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_SPIOUTPROT_RTCM3X, _output_mode == OutputMode::GPS ? 0 : 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_SPIOUTPROT_NMEA, 0, cfg_valset_msg_size); bool cfg_valset_success = false; if (sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) == 0) { cfg_valset_success = true; } } if (cfg_valset_success) { _proto_ver_27_or_higher = true; } else { _proto_ver_27_or_higher = false; memset(cfg_prt, 0, sizeof(ubx_payload_tx_cfg_prt_t)); cfg_prt[0].portID = UBX_TX_CFG_PRT_PORTID_SPI; cfg_prt[0].mode = UBX_TX_CFG_PRT_MODE_SPI; cfg_prt[0].inProtoMask = in_proto_mask; cfg_prt[0].outProtoMask = out_proto_mask; if (!sendMessage(UBX_MSG_CFG_PRT, (uint8_t *)cfg_prt, sizeof(ubx_payload_tx_cfg_prt_t))) { return -1; } waitForAck(UBX_MSG_CFG_PRT, UBX_CONFIG_TIMEOUT, false); } } else { return -1; } UBX_DEBUG("Protocol version 27+: %i", static_cast<int>(_proto_ver_27_or_higher)); /* Request module version information by sending an empty MON-VER message */ if (!sendMessage(UBX_MSG_MON_VER, nullptr, 0)) { return -1; } /* Wait for the reply so that we know to which device we're connected (_board will be set). * Note: we won't actually get an ACK-ACK, but UBX_MSG_MON_VER will also set the ack state. */ if (waitForAck(UBX_MSG_MON_VER, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } /* Now that we know the board, update the baudrate on M8 boards (on F9+ we already used the * higher baudrate with CFG-VALSET) */ if (_interface == Interface::UART && auto_baudrate && _board == Board::u_blox8) { cfg_prt[0].baudRate = UBX_BAUDRATE_M8_AND_NEWER; cfg_prt[1].baudRate = UBX_BAUDRATE_M8_AND_NEWER; if (sendMessage(UBX_MSG_CFG_PRT, (uint8_t *)cfg_prt, 2 * sizeof(ubx_payload_tx_cfg_prt_t))) { /* no ACK is expected here, but read the buffer anyway in case we actually get an ACK */ waitForAck(UBX_MSG_CFG_PRT, UBX_CONFIG_TIMEOUT, false); setBaudrate(UBX_BAUDRATE_M8_AND_NEWER); baudrate = UBX_BAUDRATE_M8_AND_NEWER; } } if (_output_mode == OutputMode::RTCM) { // RTCM mode force stationary dynamic model _dyn_model = 2; } int ret; if (_proto_ver_27_or_higher) { ret = configureDevice(config.gnss_systems); } else { ret = configureDevicePreV27(config.gnss_systems); } if (ret != 0) { return ret; } if (_output_mode == OutputMode::RTCM) { if (restartSurveyIn() < 0) { return -1; } } else if (_output_mode == OutputMode::GPSAndRTCM) { if (activateRTCMOutput(false) < 0) { return -1; } } _configured = true; return 0; } int GPSDriverUBX::configureDevicePreV27(const GNSSSystemsMask &gnssSystems) { /* Send a CFG-RATE message to define update rate */ memset(&_buf.payload_tx_cfg_rate, 0, sizeof(_buf.payload_tx_cfg_rate)); _buf.payload_tx_cfg_rate.measRate = UBX_TX_CFG_RATE_MEASINTERVAL; _buf.payload_tx_cfg_rate.navRate = UBX_TX_CFG_RATE_NAVRATE; _buf.payload_tx_cfg_rate.timeRef = UBX_TX_CFG_RATE_TIMEREF; if (!sendMessage(UBX_MSG_CFG_RATE, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_rate))) { return -1; } if (waitForAck(UBX_MSG_CFG_RATE, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } /* send a NAV5 message to set the options for the internal filter */ memset(&_buf.payload_tx_cfg_nav5, 0, sizeof(_buf.payload_tx_cfg_nav5)); _buf.payload_tx_cfg_nav5.mask = UBX_TX_CFG_NAV5_MASK; _buf.payload_tx_cfg_nav5.dynModel = _dyn_model; _buf.payload_tx_cfg_nav5.fixMode = UBX_TX_CFG_NAV5_FIXMODE; if (!sendMessage(UBX_MSG_CFG_NAV5, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_nav5))) { return -1; } if (waitForAck(UBX_MSG_CFG_NAV5, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } /* configure active GNSS systems (number of channels and used signals taken from U-Center default) */ if (static_cast<int32_t>(gnssSystems) != 0) { memset(&_buf.payload_tx_cfg_gnss, 0, sizeof(_buf.payload_tx_cfg_gnss)); _buf.payload_tx_cfg_gnss.msgVer = 0x00; _buf.payload_tx_cfg_gnss.numTrkChHw = 0x00; // read only _buf.payload_tx_cfg_gnss.numTrkChUse = 0xFF; // use max number of HW channels _buf.payload_tx_cfg_gnss.numConfigBlocks = 7; // always configure all systems // GPS and QZSS should always be enabled and disabled together, according to uBlox _buf.payload_tx_cfg_gnss.block[0].gnssId = UBX_TX_CFG_GNSS_GNSSID_GPS; _buf.payload_tx_cfg_gnss.block[1].gnssId = UBX_TX_CFG_GNSS_GNSSID_QZSS; if (gnssSystems & GNSSSystemsMask::ENABLE_GPS) { UBX_DEBUG("GNSS Systems: Use GPS + QZSS"); _buf.payload_tx_cfg_gnss.block[0].resTrkCh = 8; _buf.payload_tx_cfg_gnss.block[0].maxTrkCh = 16; _buf.payload_tx_cfg_gnss.block[0].flags = UBX_TX_CFG_GNSS_FLAGS_GPS_L1CA | UBX_TX_CFG_GNSS_FLAGS_ENABLE; _buf.payload_tx_cfg_gnss.block[1].resTrkCh = 0; _buf.payload_tx_cfg_gnss.block[1].maxTrkCh = 3; _buf.payload_tx_cfg_gnss.block[1].flags = UBX_TX_CFG_GNSS_FLAGS_QZSS_L1CA | UBX_TX_CFG_GNSS_FLAGS_ENABLE; } _buf.payload_tx_cfg_gnss.block[2].gnssId = UBX_TX_CFG_GNSS_GNSSID_SBAS; if (gnssSystems & GNSSSystemsMask::ENABLE_SBAS) { UBX_DEBUG("GNSS Systems: Use SBAS"); _buf.payload_tx_cfg_gnss.block[2].resTrkCh = 1; _buf.payload_tx_cfg_gnss.block[2].maxTrkCh = 3; _buf.payload_tx_cfg_gnss.block[2].flags = UBX_TX_CFG_GNSS_FLAGS_SBAS_L1CA | UBX_TX_CFG_GNSS_FLAGS_ENABLE; } _buf.payload_tx_cfg_gnss.block[3].gnssId = UBX_TX_CFG_GNSS_GNSSID_GALILEO; if (gnssSystems & GNSSSystemsMask::ENABLE_GALILEO) { UBX_DEBUG("GNSS Systems: Use Galileo"); _buf.payload_tx_cfg_gnss.block[3].resTrkCh = 4; _buf.payload_tx_cfg_gnss.block[3].maxTrkCh = 8; _buf.payload_tx_cfg_gnss.block[3].flags = UBX_TX_CFG_GNSS_FLAGS_GALILEO_E1 | UBX_TX_CFG_GNSS_FLAGS_ENABLE; } _buf.payload_tx_cfg_gnss.block[4].gnssId = UBX_TX_CFG_GNSS_GNSSID_BEIDOU; if (gnssSystems & GNSSSystemsMask::ENABLE_BEIDOU) { UBX_DEBUG("GNSS Systems: Use BeiDou"); _buf.payload_tx_cfg_gnss.block[4].resTrkCh = 8; _buf.payload_tx_cfg_gnss.block[4].maxTrkCh = 16; _buf.payload_tx_cfg_gnss.block[4].flags = UBX_TX_CFG_GNSS_FLAGS_BEIDOU_B1I | UBX_TX_CFG_GNSS_FLAGS_ENABLE; } _buf.payload_tx_cfg_gnss.block[5].gnssId = UBX_TX_CFG_GNSS_GNSSID_GLONASS; if (gnssSystems & GNSSSystemsMask::ENABLE_GLONASS) { UBX_DEBUG("GNSS Systems: Use GLONASS"); _buf.payload_tx_cfg_gnss.block[5].resTrkCh = 8; _buf.payload_tx_cfg_gnss.block[5].maxTrkCh = 14; _buf.payload_tx_cfg_gnss.block[5].flags = UBX_TX_CFG_GNSS_FLAGS_GLONASS_L1 | UBX_TX_CFG_GNSS_FLAGS_ENABLE; } // IMES always disabled _buf.payload_tx_cfg_gnss.block[6].gnssId = UBX_TX_CFG_GNSS_GNSSID_IMES; _buf.payload_tx_cfg_gnss.block[6].flags = 0; // send message if (!sendMessage(UBX_MSG_CFG_GNSS, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_gnss))) { GPS_ERR("UBX CFG-GNSS message send failed"); return -1; } if (waitForAck(UBX_MSG_CFG_GNSS, UBX_CONFIG_TIMEOUT, true) < 0) { GPS_ERR("UBX CFG-GNSS message ACK failed"); return -1; } } /* configure message rates */ /* the last argument is divisor for measurement rate (set by CFG RATE), i.e. 1 means 5Hz */ /* try to set rate for NAV-PVT */ /* (implemented for ubx7+ modules only, use NAV-SOL, NAV-POSLLH, NAV-VELNED and NAV-TIMEUTC for ubx6) */ if (!configureMessageRate(UBX_MSG_NAV_PVT, 1)) { return -1; } if (waitForAck(UBX_MSG_CFG_MSG, UBX_CONFIG_TIMEOUT, true) < 0) { _use_nav_pvt = false; } else { _use_nav_pvt = true; } UBX_DEBUG("%susing NAV-PVT", _use_nav_pvt ? "" : "not "); if (!_use_nav_pvt) { if (!configureMessageRateAndAck(UBX_MSG_NAV_TIMEUTC, 5, true)) { return -1; } if (!configureMessageRateAndAck(UBX_MSG_NAV_POSLLH, 1, true)) { return -1; } if (!configureMessageRateAndAck(UBX_MSG_NAV_SOL, 1, true)) { return -1; } if (!configureMessageRateAndAck(UBX_MSG_NAV_VELNED, 1, true)) { return -1; } } if (!configureMessageRateAndAck(UBX_MSG_NAV_DOP, 1, true)) { return -1; } if (!configureMessageRateAndAck(UBX_MSG_NAV_SVINFO, (_satellite_info != nullptr) ? 5 : 0, true)) { return -1; } if (!configureMessageRateAndAck(UBX_MSG_MON_HW, 1, true)) { return -1; } return 0; } int GPSDriverUBX::configureDevice(const GNSSSystemsMask &gnssSystems) { /* set configuration parameters */ int cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_NAVSPG_FIXMODE, 3 /* Auto 2d/3d */, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_NAVSPG_UTCSTANDARD, 3 /* USNO (U.S. Naval Observatory derived from GPS) */, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_NAVSPG_DYNMODEL, _dyn_model, cfg_valset_msg_size); // disable odometer & filtering cfgValset<uint8_t>(UBX_CFG_KEY_ODO_USE_ODO, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_ODO_USE_COG, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_ODO_OUTLPVEL, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_ODO_OUTLPCOG, 0, cfg_valset_msg_size); // enable jamming monitor cfgValset<uint8_t>(UBX_CFG_KEY_ITFM_ENABLE, 1, cfg_valset_msg_size); // measurement rate // In case of F9P not in moving base mode we use 10Hz, otherwise 8Hz (receivers such as M9N can go higher as well, but // the number of used satellites will be restricted to 16. Not mentioned in datasheet) int rate_meas; if (_mode != UBXMode::Normal) { rate_meas = 125; //8Hz for heading. } else { rate_meas = (_board == Board::u_blox9_F9P) ? 100 : 125; } cfgValset<uint16_t>(UBX_CFG_KEY_RATE_MEAS, rate_meas, cfg_valset_msg_size); cfgValset<uint16_t>(UBX_CFG_KEY_RATE_NAV, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_RATE_TIMEREF, 0, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } // RTK (optional, as only RTK devices like F9P support it) cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_NAVHPG_DGNSSMODE, 3 /* RTK Fixed */, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, false); // configure active GNSS systems (leave signal bands as is) if (static_cast<int32_t>(gnssSystems) != 0) { cfg_valset_msg_size = initCfgValset(); // GPS and QZSS should always be enabled and disabled together, according to uBlox if (gnssSystems & GNSSSystemsMask::ENABLE_GPS) { UBX_DEBUG("GNSS Systems: Use GPS + QZSS"); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_GPS_ENA, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_QZSS_ENA, 1, cfg_valset_msg_size); } else { cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_GPS_ENA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_QZSS_ENA, 0, cfg_valset_msg_size); } if (gnssSystems & GNSSSystemsMask::ENABLE_GALILEO) { UBX_DEBUG("GNSS Systems: Use Galileo"); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_GAL_ENA, 1, cfg_valset_msg_size); } else { cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_GAL_ENA, 0, cfg_valset_msg_size); } if (gnssSystems & GNSSSystemsMask::ENABLE_BEIDOU) { UBX_DEBUG("GNSS Systems: Use BeiDou"); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_BDS_ENA, 1, cfg_valset_msg_size); } else { cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_BDS_ENA, 0, cfg_valset_msg_size); } if (gnssSystems & GNSSSystemsMask::ENABLE_GLONASS) { cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_GLO_ENA, 1, cfg_valset_msg_size); } else { cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_GLO_ENA, 0, cfg_valset_msg_size); } if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { GPS_ERR("UBX GNSS config send failed"); return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } // send SBAS config separately, because it seems to be buggy (with u-center, too) cfg_valset_msg_size = initCfgValset(); if (gnssSystems & GNSSSystemsMask::ENABLE_SBAS) { UBX_DEBUG("GNSS Systems: Use SBAS"); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_SBAS_ENA, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_SBAS_L1CA_ENA, 1, cfg_valset_msg_size); } else { cfgValset<uint8_t>(UBX_CFG_KEY_SIGNAL_SBAS_ENA, 0, cfg_valset_msg_size); } if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true); } // Configure message rates // Send a new CFG-VALSET message to make sure it does not get too large cfg_valset_msg_size = initCfgValset(); cfgValsetPort(UBX_CFG_KEY_MSGOUT_UBX_NAV_PVT_I2C, 1, cfg_valset_msg_size); _use_nav_pvt = true; cfgValsetPort(UBX_CFG_KEY_MSGOUT_UBX_NAV_DOP_I2C, 1, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_UBX_NAV_SAT_I2C, (_satellite_info != nullptr) ? 10 : 0, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_UBX_MON_RF_I2C, 1, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } if (_interface == Interface::UART) { // Disable GPS protocols at I2C cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_I2CINPROT_UBX, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_I2CINPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_I2CINPROT_RTCM3X, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_I2COUTPROT_UBX, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_I2COUTPROT_NMEA, 0, cfg_valset_msg_size); if (_board == Board::u_blox9_F9P) { cfgValset<uint8_t>(UBX_CFG_KEY_CFG_I2COUTPROT_RTCM3X, 0, cfg_valset_msg_size); } if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } } int uart2_baudrate = 230400; if (_mode == UBXMode::RoverWithMovingBase) { UBX_DEBUG("Configuring UART2 for rover"); cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_RTCM3X, 0, cfg_valset_msg_size); // heading output period 1 second cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_UBX_NAV_RELPOSNED_UART1, 1, cfg_valset_msg_size); // enable RTCM input on uart2 + set baudrate cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2_STOPBITS, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2_DATABITS, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2_PARITY, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2INPROT_UBX, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2INPROT_RTCM3X, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2INPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2OUTPROT_UBX, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2OUTPROT_RTCM3X, 0, cfg_valset_msg_size); cfgValset<uint32_t>(UBX_CFG_KEY_CFG_UART2_BAUDRATE, uart2_baudrate, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } } else if (_mode == UBXMode::MovingBase) { UBX_DEBUG("Configuring UART2 for moving base"); // enable RTCM output on uart2 + set baudrate cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2_STOPBITS, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2_DATABITS, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2_PARITY, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2INPROT_UBX, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2INPROT_RTCM3X, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2INPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2OUTPROT_UBX, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART2OUTPROT_RTCM3X, 1, cfg_valset_msg_size); cfgValset<uint32_t>(UBX_CFG_KEY_CFG_UART2_BAUDRATE, uart2_baudrate, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE4072_0_UART2, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1230_UART2, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1074_UART2, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1084_UART2, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1094_UART2, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1124_UART2, 1, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } } else if (_mode == UBXMode::RoverWithMovingBaseUART1) { UBX_DEBUG("Configuring UART1 for rover"); // heading output period 1 second cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_RTCM3X, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_RTCM3X, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_UBX_NAV_RELPOSNED_UART1, 1, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } } else if (_mode == UBXMode::MovingBaseUART1) { UBX_DEBUG("Configuring UART1 for moving base"); // enable RTCM output on uart1 cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_RTCM3X, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1INPROT_NMEA, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_UBX, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_CFG_UART1OUTPROT_RTCM3X, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_UBX_NAV_RELPOSNED_UART1, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_UBX_NAV_RELPOSNED_UART2, 0, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE4072_0_UART1, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1230_UART1, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1074_UART1, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1084_UART1, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1094_UART1, 1, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1124_UART1, 1, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } } return 0; } int GPSDriverUBX::initCfgValset() { memset(&_buf.payload_tx_cfg_valset, 0, sizeof(_buf.payload_tx_cfg_valset)); _buf.payload_tx_cfg_valset.layers = UBX_CFG_LAYER_RAM; return sizeof(_buf.payload_tx_cfg_valset) - sizeof(_buf.payload_tx_cfg_valset.cfgData); } template<typename T> bool GPSDriverUBX::cfgValset(uint32_t key_id, T value, int &msg_size) { if (msg_size + sizeof(key_id) + sizeof(value) > sizeof(_buf)) { // If this happens use several CFG-VALSET messages instead of one UBX_WARN("buf for CFG_VALSET too small"); return false; } uint8_t *buffer = (uint8_t *)&_buf.payload_tx_cfg_valset; memcpy(buffer + msg_size, &key_id, sizeof(key_id)); msg_size += sizeof(key_id); memcpy(buffer + msg_size, &value, sizeof(value)); msg_size += sizeof(value); return true; } bool GPSDriverUBX::cfgValsetPort(uint32_t key_id, uint8_t value, int &msg_size) { if (_interface == Interface::SPI) { if (!cfgValset<uint8_t>(key_id + 4, value, msg_size)) { return false; } } else { // enable on UART1 & USB (TODO: should we enable UART2 too? -> better would be to detect the port) if (!cfgValset<uint8_t>(key_id + 1, value, msg_size)) { return false; } if (!cfgValset<uint8_t>(key_id + 3, value, msg_size)) { return false; } } return true; } int GPSDriverUBX::restartSurveyInPreV27() { //disable RTCM output configureMessageRate(UBX_MSG_RTCM3_1005, 0); configureMessageRate(UBX_MSG_RTCM3_1077, 0); configureMessageRate(UBX_MSG_RTCM3_1087, 0); configureMessageRate(UBX_MSG_RTCM3_1230, 0); configureMessageRate(UBX_MSG_RTCM3_1097, 0); configureMessageRate(UBX_MSG_RTCM3_1127, 0); //stop it first //FIXME: stopping the survey-in process does not seem to work memset(&_buf.payload_tx_cfg_tmode3, 0, sizeof(_buf.payload_tx_cfg_tmode3)); _buf.payload_tx_cfg_tmode3.flags = 0; /* disable time mode */ if (!sendMessage(UBX_MSG_CFG_TMODE3, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_tmode3))) { UBX_WARN("TMODE3 failed. Device w/o base station support?"); return -1; } if (waitForAck(UBX_MSG_CFG_TMODE3, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } if (_base_settings.type == BaseSettingsType::survey_in) { UBX_DEBUG("Starting Survey-in"); memset(&_buf.payload_tx_cfg_tmode3, 0, sizeof(_buf.payload_tx_cfg_tmode3)); _buf.payload_tx_cfg_tmode3.flags = 1; /* start survey-in */ _buf.payload_tx_cfg_tmode3.svinMinDur = _base_settings.settings.survey_in.min_dur; _buf.payload_tx_cfg_tmode3.svinAccLimit = _base_settings.settings.survey_in.acc_limit; if (!sendMessage(UBX_MSG_CFG_TMODE3, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_tmode3))) { return -1; } if (waitForAck(UBX_MSG_CFG_TMODE3, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } /* enable status output of survey-in */ if (!configureMessageRateAndAck(UBX_MSG_NAV_SVIN, 5, true)) { return -1; } } else { UBX_DEBUG("Setting fixed base position"); const FixedPositionSettings &settings = _base_settings.settings.fixed_position; memset(&_buf.payload_tx_cfg_tmode3, 0, sizeof(_buf.payload_tx_cfg_tmode3)); _buf.payload_tx_cfg_tmode3.flags = 2 /* fixed mode */ | (1 << 8) /* lat/lon mode */; int64_t lat64 = (int64_t)(settings.latitude * 1e9); _buf.payload_tx_cfg_tmode3.ecefXOrLat = (int32_t)(lat64 / 100); _buf.payload_tx_cfg_tmode3.ecefXOrLatHP = lat64 % 100; // range [-99, 99] int64_t lon64 = (int64_t)(settings.longitude * 1e9); _buf.payload_tx_cfg_tmode3.ecefYOrLon = (int32_t)(lon64 / 100); _buf.payload_tx_cfg_tmode3.ecefYOrLonHP = lon64 % 100; int64_t alt64 = (int64_t)((double)settings.altitude * 1e4); _buf.payload_tx_cfg_tmode3.ecefZOrAlt = (int32_t)(alt64 / 100); // cm _buf.payload_tx_cfg_tmode3.ecefZOrAltHP = alt64 % 100; // 0.1mm _buf.payload_tx_cfg_tmode3.fixedPosAcc = (uint32_t)(settings.position_accuracy * 10.f); if (!sendMessage(UBX_MSG_CFG_TMODE3, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_tmode3))) { return -1; } if (waitForAck(UBX_MSG_CFG_TMODE3, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } // directly enable RTCM3 output return activateRTCMOutput(true); } return 0; } int GPSDriverUBX::restartSurveyIn() { if (_output_mode != OutputMode::RTCM) { return -1; } if (!_proto_ver_27_or_higher) { return restartSurveyInPreV27(); } //disable RTCM output int cfg_valset_msg_size = initCfgValset(); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1005_I2C, 0, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1077_I2C, 0, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1087_I2C, 0, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1230_I2C, 0, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1097_I2C, 0, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1127_I2C, 0, cfg_valset_msg_size); sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size); waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, false); if (_base_settings.type == BaseSettingsType::survey_in) { UBX_DEBUG("Starting Survey-in"); cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_TMODE_MODE, 1 /* Survey-in */, cfg_valset_msg_size); cfgValset<uint32_t>(UBX_CFG_KEY_TMODE_SVIN_MIN_DUR, _base_settings.settings.survey_in.min_dur, cfg_valset_msg_size); cfgValset<uint32_t>(UBX_CFG_KEY_TMODE_SVIN_ACC_LIMIT, _base_settings.settings.survey_in.acc_limit, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_UBX_NAV_SVIN_I2C, 5, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } } else { UBX_DEBUG("Setting fixed base position"); const FixedPositionSettings &settings = _base_settings.settings.fixed_position; cfg_valset_msg_size = initCfgValset(); cfgValset<uint8_t>(UBX_CFG_KEY_TMODE_MODE, 2 /* Fixed Mode */, cfg_valset_msg_size); cfgValset<uint8_t>(UBX_CFG_KEY_TMODE_POS_TYPE, 1 /* Lat/Lon/Height */, cfg_valset_msg_size); int64_t lat64 = (int64_t)(settings.latitude * 1e9); cfgValset<int32_t>(UBX_CFG_KEY_TMODE_LAT, (int32_t)(lat64 / 100), cfg_valset_msg_size); cfgValset<int8_t>(UBX_CFG_KEY_TMODE_LAT_HP, lat64 % 100 /* range [-99, 99] */, cfg_valset_msg_size); int64_t lon64 = (int64_t)(settings.longitude * 1e9); cfgValset<int32_t>(UBX_CFG_KEY_TMODE_LON, (int32_t)(lon64 / 100), cfg_valset_msg_size); cfgValset<int8_t>(UBX_CFG_KEY_TMODE_LON_HP, lon64 % 100 /* range [-99, 99] */, cfg_valset_msg_size); int64_t alt64 = (int64_t)((double)settings.altitude * 1e4); cfgValset<int32_t>(UBX_CFG_KEY_TMODE_HEIGHT, (int32_t)(alt64 / 100) /* cm */, cfg_valset_msg_size); cfgValset<int8_t>(UBX_CFG_KEY_TMODE_HEIGHT_HP, alt64 % 100 /* 0.1mm */, cfg_valset_msg_size); cfgValset<uint32_t>(UBX_CFG_KEY_TMODE_FIXED_POS_ACC, (uint32_t)(settings.position_accuracy * 10.f), cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, true) < 0) { return -1; } // directly enable RTCM3 output return activateRTCMOutput(true); } return 0; } int // -1 = NAK, error or timeout, 0 = ACK GPSDriverUBX::waitForAck(const uint16_t msg, const unsigned timeout, const bool report) { int ret = -1; _ack_state = UBX_ACK_WAITING; _ack_waiting_msg = msg; // memorize sent msg class&ID for ACK check gps_abstime time_started = gps_absolute_time(); while ((_ack_state == UBX_ACK_WAITING) && (gps_absolute_time() < time_started + timeout * 1000)) { receive(timeout); } if (_ack_state == UBX_ACK_GOT_ACK) { ret = 0; // ACK received ok } else if (report) { if (_ack_state == UBX_ACK_GOT_NAK) { UBX_DEBUG("ubx msg 0x%04x NAK", SWAP16((unsigned)msg)); } else { UBX_DEBUG("ubx msg 0x%04x ACK timeout", SWAP16((unsigned)msg)); } } _ack_state = UBX_ACK_IDLE; return ret; } int // -1 = error, 0 = no message handled, 1 = message handled, 2 = sat info message handled GPSDriverUBX::receive(unsigned timeout) { uint8_t buf[GPS_READ_BUFFER_SIZE]; /* timeout additional to poll */ gps_abstime time_started = gps_absolute_time(); int handled = 0; while (true) { bool ready_to_return = _configured ? (_got_posllh && _got_velned) : handled; /* Wait for only UBX_PACKET_TIMEOUT if something already received. */ int ret = read(buf, sizeof(buf), ready_to_return ? UBX_PACKET_TIMEOUT : timeout); if (ret < 0) { /* something went wrong when polling or reading */ UBX_WARN("ubx poll_or_read err"); return -1; } else if (ret == 0) { /* return success if ready */ if (ready_to_return) { _got_posllh = false; _got_velned = false; return handled; } } else { //UBX_DEBUG("read %d bytes", ret); /* pass received bytes to the packet decoder */ for (int i = 0; i < ret; i++) { handled |= parseChar(buf[i]); //UBX_DEBUG("parsed %d: 0x%x", i, buf[i]); } if (_interface == Interface::SPI) { if (buf[ret - 1] == 0xff) { if (ready_to_return) { _got_posllh = false; _got_velned = false; return handled; } } } } /* abort after timeout if no useful packets received */ if (time_started + timeout * 1000 < gps_absolute_time()) { UBX_DEBUG("timed out, returning"); return -1; } } } int // 0 = decoding, 1 = message handled, 2 = sat info message handled GPSDriverUBX::parseChar(const uint8_t b) { int ret = 0; switch (_decode_state) { /* Expecting Sync1 */ case UBX_DECODE_SYNC1: if (b == UBX_SYNC1) { // Sync1 found --> expecting Sync2 UBX_TRACE_PARSER("A"); _decode_state = UBX_DECODE_SYNC2; } else if (b == RTCM3_PREAMBLE && _rtcm_parsing) { UBX_TRACE_PARSER("RTCM"); _decode_state = UBX_DECODE_RTCM3; _rtcm_parsing->addByte(b); } break; /* Expecting Sync2 */ case UBX_DECODE_SYNC2: if (b == UBX_SYNC2) { // Sync2 found --> expecting Class UBX_TRACE_PARSER("B"); _decode_state = UBX_DECODE_CLASS; } else { // Sync1 not followed by Sync2: reset parser decodeInit(); } break; /* Expecting Class */ case UBX_DECODE_CLASS: UBX_TRACE_PARSER("C"); addByteToChecksum(b); // checksum is calculated for everything except Sync and Checksum bytes _rx_msg = b; _decode_state = UBX_DECODE_ID; break; /* Expecting ID */ case UBX_DECODE_ID: UBX_TRACE_PARSER("D"); addByteToChecksum(b); _rx_msg |= b << 8; _decode_state = UBX_DECODE_LENGTH1; break; /* Expecting first length byte */ case UBX_DECODE_LENGTH1: UBX_TRACE_PARSER("E"); addByteToChecksum(b); _rx_payload_length = b; _decode_state = UBX_DECODE_LENGTH2; break; /* Expecting second length byte */ case UBX_DECODE_LENGTH2: UBX_TRACE_PARSER("F"); addByteToChecksum(b); _rx_payload_length |= b << 8; // calculate payload size if (payloadRxInit() != 0) { // start payload reception // payload will not be handled, discard message decodeInit(); } else { _decode_state = (_rx_payload_length > 0) ? UBX_DECODE_PAYLOAD : UBX_DECODE_CHKSUM1; } break; /* Expecting payload */ case UBX_DECODE_PAYLOAD: UBX_TRACE_PARSER("."); addByteToChecksum(b); switch (_rx_msg) { case UBX_MSG_NAV_SAT: ret = payloadRxAddNavSat(b); // add a NAV-SAT payload byte break; case UBX_MSG_NAV_SVINFO: ret = payloadRxAddNavSvinfo(b); // add a NAV-SVINFO payload byte break; case UBX_MSG_MON_VER: ret = payloadRxAddMonVer(b); // add a MON-VER payload byte break; default: ret = payloadRxAdd(b); // add a payload byte break; } if (ret < 0) { // payload not handled, discard message decodeInit(); } else if (ret > 0) { // payload complete, expecting checksum _decode_state = UBX_DECODE_CHKSUM1; } else { // expecting more payload, stay in state UBX_DECODE_PAYLOAD } ret = 0; break; /* Expecting first checksum byte */ case UBX_DECODE_CHKSUM1: if (_rx_ck_a != b) { UBX_DEBUG("ubx checksum err"); decodeInit(); } else { _decode_state = UBX_DECODE_CHKSUM2; } break; /* Expecting second checksum byte */ case UBX_DECODE_CHKSUM2: if (_rx_ck_b != b) { UBX_DEBUG("ubx checksum err"); } else { ret = payloadRxDone(); // finish payload processing } decodeInit(); break; case UBX_DECODE_RTCM3: if (_rtcm_parsing->addByte(b)) { //UBX_DEBUG("got RTCM message with length %i", static_cast<int>(_rtcm_parsing->messageLength())); gotRTCMMessage(_rtcm_parsing->message(), _rtcm_parsing->messageLength()); decodeInit(); } break; default: break; } return ret; } /** * Start payload rx */ int // -1 = abort, 0 = continue GPSDriverUBX::payloadRxInit() { int ret = 0; _rx_state = UBX_RXMSG_HANDLE; // handle by default switch (_rx_msg) { case UBX_MSG_NAV_PVT: if ((_rx_payload_length != UBX_PAYLOAD_RX_NAV_PVT_SIZE_UBX7) /* u-blox 7 msg format */ && (_rx_payload_length != UBX_PAYLOAD_RX_NAV_PVT_SIZE_UBX8)) { /* u-blox 8+ msg format */ _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } else if (!_use_nav_pvt) { _rx_state = UBX_RXMSG_DISABLE; // disable if not using NAV-PVT } break; case UBX_MSG_INF_DEBUG: case UBX_MSG_INF_ERROR: case UBX_MSG_INF_NOTICE: case UBX_MSG_INF_WARNING: if (_rx_payload_length >= sizeof(ubx_buf_t)) { _rx_payload_length = sizeof(ubx_buf_t) - 1; //avoid buffer overflow } break; case UBX_MSG_NAV_POSLLH: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_posllh_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } else if (_use_nav_pvt) { _rx_state = UBX_RXMSG_DISABLE; // disable if using NAV-PVT instead } break; case UBX_MSG_NAV_SOL: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_sol_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } else if (_use_nav_pvt) { _rx_state = UBX_RXMSG_DISABLE; // disable if using NAV-PVT instead } break; case UBX_MSG_NAV_DOP: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_dop_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } break; case UBX_MSG_NAV_RELPOSNED: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_relposned_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } break; case UBX_MSG_NAV_TIMEUTC: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_timeutc_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } else if (_use_nav_pvt) { _rx_state = UBX_RXMSG_DISABLE; // disable if using NAV-PVT instead } break; case UBX_MSG_NAV_SAT: case UBX_MSG_NAV_SVINFO: if (_satellite_info == nullptr) { _rx_state = UBX_RXMSG_DISABLE; // disable if sat info not requested } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } else { memset(_satellite_info, 0, sizeof(*_satellite_info)); // initialize sat info } break; case UBX_MSG_NAV_SVIN: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_svin_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } break; case UBX_MSG_NAV_VELNED: if (_rx_payload_length != sizeof(ubx_payload_rx_nav_velned_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } else if (_use_nav_pvt) { _rx_state = UBX_RXMSG_DISABLE; // disable if using NAV-PVT instead } break; case UBX_MSG_MON_VER: break; // unconditionally handle this message case UBX_MSG_MON_HW: if ((_rx_payload_length != sizeof(ubx_payload_rx_mon_hw_ubx6_t)) /* u-blox 6 msg format */ && (_rx_payload_length != sizeof(ubx_payload_rx_mon_hw_ubx7_t))) { /* u-blox 7+ msg format */ _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } break; case UBX_MSG_MON_RF: if (_rx_payload_length < sizeof(ubx_payload_rx_mon_rf_t) || (_rx_payload_length - 4) % sizeof(ubx_payload_rx_mon_rf_t::ubx_payload_rx_mon_rf_block_t) != 0) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (!_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if not _configured } break; case UBX_MSG_ACK_ACK: if (_rx_payload_length != sizeof(ubx_payload_rx_ack_ack_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if _configured } break; case UBX_MSG_ACK_NAK: if (_rx_payload_length != sizeof(ubx_payload_rx_ack_nak_t)) { _rx_state = UBX_RXMSG_ERROR_LENGTH; } else if (_configured) { _rx_state = UBX_RXMSG_IGNORE; // ignore if _configured } break; default: _rx_state = UBX_RXMSG_DISABLE; // disable all other messages break; } switch (_rx_state) { case UBX_RXMSG_HANDLE: // handle message case UBX_RXMSG_IGNORE: // ignore message but don't report error ret = 0; break; case UBX_RXMSG_DISABLE: // disable unexpected messages UBX_DEBUG("ubx msg 0x%04x len %u unexpected", SWAP16((unsigned)_rx_msg), (unsigned)_rx_payload_length); if (_proto_ver_27_or_higher) { uint32_t key_id = 0; switch (_rx_msg) { // we cannot infer the config Key ID from _rx_msg for protocol version 27+ case UBX_MSG_RXM_RAWX: key_id = UBX_CFG_KEY_MSGOUT_UBX_RXM_RAWX_I2C; break; case UBX_MSG_RXM_SFRBX: key_id = UBX_CFG_KEY_MSGOUT_UBX_RXM_SFRBX_I2C; break; } if (key_id != 0) { gps_abstime t = gps_absolute_time(); if (t > _disable_cmd_last + DISABLE_MSG_INTERVAL && _configured) { /* don't attempt for every message to disable, some might not be disabled */ _disable_cmd_last = t; UBX_DEBUG("ubx disabling msg 0x%04x (0x%04x)", SWAP16((unsigned)_rx_msg), (uint16_t)key_id); // this will overwrite _buf, which is fine, as we'll return -1 and abort further parsing int cfg_valset_msg_size = initCfgValset(); cfgValsetPort(key_id, 0, cfg_valset_msg_size); sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size); } } } else { gps_abstime t = gps_absolute_time(); if (t > _disable_cmd_last + DISABLE_MSG_INTERVAL) { /* don't attempt for every message to disable, some might not be disabled */ _disable_cmd_last = t; UBX_DEBUG("ubx disabling msg 0x%04x", SWAP16((unsigned)_rx_msg)); configureMessageRate(_rx_msg, 0); } } ret = -1; // return error, abort handling this message break; case UBX_RXMSG_ERROR_LENGTH: // error: invalid length UBX_WARN("ubx msg 0x%04x invalid len %u", SWAP16((unsigned)_rx_msg), (unsigned)_rx_payload_length); ret = -1; // return error, abort handling this message break; default: // invalid message state UBX_WARN("ubx internal err1"); ret = -1; // return error, abort handling this message break; } return ret; } /** * Add payload rx byte */ int // -1 = error, 0 = ok, 1 = payload completed GPSDriverUBX::payloadRxAdd(const uint8_t b) { int ret = 0; uint8_t *p_buf = (uint8_t *)&_buf; p_buf[_rx_payload_index] = b; if (++_rx_payload_index >= _rx_payload_length) { ret = 1; // payload received completely } return ret; } int // -1 = error, 0 = ok, 1 = payload completed GPSDriverUBX::payloadRxAddNavSat(const uint8_t b) { int ret = 0; uint8_t *p_buf = (uint8_t *)&_buf; if (_rx_payload_index < sizeof(ubx_payload_rx_nav_sat_part1_t)) { // Fill Part 1 buffer p_buf[_rx_payload_index] = b; } else { if (_rx_payload_index == sizeof(ubx_payload_rx_nav_sat_part1_t)) { // Part 1 complete: decode Part 1 buffer _satellite_info->count = MIN(_buf.payload_rx_nav_sat_part1.numSvs, satellite_info_s::SAT_INFO_MAX_SATELLITES); UBX_TRACE_SVINFO("SAT len %u numCh %u", (unsigned)_rx_payload_length, (unsigned)_buf.payload_rx_nav_sat_part1.numSvs); } if (_rx_payload_index < sizeof(ubx_payload_rx_nav_sat_part1_t) + _satellite_info->count * sizeof( ubx_payload_rx_nav_sat_part2_t)) { // Still room in _satellite_info: fill Part 2 buffer unsigned buf_index = (_rx_payload_index - sizeof(ubx_payload_rx_nav_sat_part1_t)) % sizeof( ubx_payload_rx_nav_sat_part2_t); p_buf[buf_index] = b; if (buf_index == sizeof(ubx_payload_rx_nav_sat_part2_t) - 1) { // Part 2 complete: decode Part 2 buffer unsigned sat_index = (_rx_payload_index - sizeof(ubx_payload_rx_nav_sat_part1_t)) / sizeof(ubx_payload_rx_nav_sat_part2_t); // convert gnssId:svId to a 8 bit number (use svId numbering from NAV-SVINFO) uint8_t ubx_sat_gnssId = static_cast<uint8_t>(_buf.payload_rx_nav_sat_part2.gnssId); uint8_t ubx_sat_svId = static_cast<uint8_t>(_buf.payload_rx_nav_sat_part2.svId); uint8_t svinfo_svid = 255; switch (ubx_sat_gnssId) { case 0: // GPS: G1-G23 -> 1-32 if (ubx_sat_svId >= 1 && ubx_sat_svId <= 32) { svinfo_svid = ubx_sat_svId; } break; case 1: // SBAS: S120-S158 -> 120-158 if (ubx_sat_svId >= 120 && ubx_sat_svId <= 158) { svinfo_svid = ubx_sat_svId; } break; case 2: // Galileo: E1-E36 -> 211-246 if (ubx_sat_svId >= 1 && ubx_sat_svId <= 36) { svinfo_svid = ubx_sat_svId + 210; } break; case 3: // BeiDou: B1-B37 -> 159-163,33-64 if (ubx_sat_svId >= 1 && ubx_sat_svId <= 4) { svinfo_svid = ubx_sat_svId + 158; } else if (ubx_sat_svId >= 5 && ubx_sat_svId <= 37) { svinfo_svid = ubx_sat_svId + 28; } break; case 4: // IMES: I1-I10 -> 173-182 if (ubx_sat_svId >= 1 && ubx_sat_svId <= 10) { svinfo_svid = ubx_sat_svId + 172; } break; case 5: // QZSS: Q1-A10 -> 193-202 if (ubx_sat_svId >= 1 && ubx_sat_svId <= 10) { svinfo_svid = ubx_sat_svId + 192; } break; case 6: // GLONASS: R1-R32 -> 65-96, R? -> 255 if (ubx_sat_svId >= 1 && ubx_sat_svId <= 32) { svinfo_svid = ubx_sat_svId + 64; } break; } _satellite_info->svid[sat_index] = svinfo_svid; _satellite_info->used[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_sat_part2.flags & 0x01); _satellite_info->elevation[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_sat_part2.elev); _satellite_info->azimuth[sat_index] = static_cast<uint8_t>(static_cast<float>(_buf.payload_rx_nav_sat_part2.azim) * 255.0f / 360.0f); _satellite_info->snr[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_sat_part2.cno); _satellite_info->prn[sat_index] = svinfo_svid; UBX_TRACE_SVINFO("SAT #%02u svid %3u used %u elevation %3u azimuth %3u snr %3u prn %3u", static_cast<unsigned>(sat_index + 1), static_cast<unsigned>(_satellite_info->svid[sat_index]), static_cast<unsigned>(_satellite_info->used[sat_index]), static_cast<unsigned>(_satellite_info->elevation[sat_index]), static_cast<unsigned>(_satellite_info->azimuth[sat_index]), static_cast<unsigned>(_satellite_info->snr[sat_index]), static_cast<unsigned>(_satellite_info->prn[sat_index]) ); } } } if (++_rx_payload_index >= _rx_payload_length) { ret = 1; // payload received completely } return ret; } /** * Add NAV-SVINFO payload rx byte */ int // -1 = error, 0 = ok, 1 = payload completed GPSDriverUBX::payloadRxAddNavSvinfo(const uint8_t b) { int ret = 0; uint8_t *p_buf = (uint8_t *)&_buf; if (_rx_payload_index < sizeof(ubx_payload_rx_nav_svinfo_part1_t)) { // Fill Part 1 buffer p_buf[_rx_payload_index] = b; } else { if (_rx_payload_index == sizeof(ubx_payload_rx_nav_svinfo_part1_t)) { // Part 1 complete: decode Part 1 buffer _satellite_info->count = MIN(_buf.payload_rx_nav_svinfo_part1.numCh, satellite_info_s::SAT_INFO_MAX_SATELLITES); UBX_TRACE_SVINFO("SVINFO len %u numCh %u", (unsigned)_rx_payload_length, (unsigned)_buf.payload_rx_nav_svinfo_part1.numCh); } if (_rx_payload_index < sizeof(ubx_payload_rx_nav_svinfo_part1_t) + _satellite_info->count * sizeof( ubx_payload_rx_nav_svinfo_part2_t)) { // Still room in _satellite_info: fill Part 2 buffer unsigned buf_index = (_rx_payload_index - sizeof(ubx_payload_rx_nav_svinfo_part1_t)) % sizeof( ubx_payload_rx_nav_svinfo_part2_t); p_buf[buf_index] = b; if (buf_index == sizeof(ubx_payload_rx_nav_svinfo_part2_t) - 1) { // Part 2 complete: decode Part 2 buffer unsigned sat_index = (_rx_payload_index - sizeof(ubx_payload_rx_nav_svinfo_part1_t)) / sizeof(ubx_payload_rx_nav_svinfo_part2_t); _satellite_info->svid[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_svinfo_part2.svid); _satellite_info->used[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_svinfo_part2.flags & 0x01); _satellite_info->elevation[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_svinfo_part2.elev); _satellite_info->azimuth[sat_index] = static_cast<uint8_t>(static_cast<float>(_buf.payload_rx_nav_svinfo_part2.azim) * 255.0f / 360.0f); _satellite_info->snr[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_svinfo_part2.cno); _satellite_info->prn[sat_index] = static_cast<uint8_t>(_buf.payload_rx_nav_svinfo_part2.svid); UBX_TRACE_SVINFO("SVINFO #%02u svid %3u used %u elevation %3u azimuth %3u snr %3u prn %3u", static_cast<unsigned>(sat_index + 1), static_cast<unsigned>(_satellite_info->svid[sat_index]), static_cast<unsigned>(_satellite_info->used[sat_index]), static_cast<unsigned>(_satellite_info->elevation[sat_index]), static_cast<unsigned>(_satellite_info->azimuth[sat_index]), static_cast<unsigned>(_satellite_info->snr[sat_index]), static_cast<unsigned>(_satellite_info->prn[sat_index]) ); } } } if (++_rx_payload_index >= _rx_payload_length) { ret = 1; // payload received completely } return ret; } /** * Add MON-VER payload rx byte */ int // -1 = error, 0 = ok, 1 = payload completed GPSDriverUBX::payloadRxAddMonVer(const uint8_t b) { int ret = 0; uint8_t *p_buf = (uint8_t *)&_buf; if (_rx_payload_index < sizeof(ubx_payload_rx_mon_ver_part1_t)) { // Fill Part 1 buffer p_buf[_rx_payload_index] = b; } else { if (_rx_payload_index == sizeof(ubx_payload_rx_mon_ver_part1_t)) { // Part 1 complete: decode Part 1 buffer and calculate hash for SW&HW version strings _ubx_version = fnv1_32_str(_buf.payload_rx_mon_ver_part1.swVersion, FNV1_32_INIT); _ubx_version = fnv1_32_str(_buf.payload_rx_mon_ver_part1.hwVersion, _ubx_version); UBX_DEBUG("VER hash 0x%08x", (uint16_t)_ubx_version); UBX_DEBUG("VER hw \"%10s\"", _buf.payload_rx_mon_ver_part1.hwVersion); UBX_DEBUG("VER sw \"%30s\"", _buf.payload_rx_mon_ver_part1.swVersion); // Device detection (See https://forum.u-blox.com/index.php/9432/need-help-decoding-ubx-mon-ver-hardware-string) if (strncmp((const char *)_buf.payload_rx_mon_ver_part1.hwVersion, "00040005", sizeof(_buf.payload_rx_mon_ver_part1.hwVersion)) == 0) { _board = Board::u_blox5; } else if (strncmp((const char *)_buf.payload_rx_mon_ver_part1.hwVersion, "00040007", sizeof(_buf.payload_rx_mon_ver_part1.hwVersion)) == 0) { _board = Board::u_blox6; } else if (strncmp((const char *)_buf.payload_rx_mon_ver_part1.hwVersion, "00070000", sizeof(_buf.payload_rx_mon_ver_part1.hwVersion)) == 0) { _board = Board::u_blox7; } else if (strncmp((const char *)_buf.payload_rx_mon_ver_part1.hwVersion, "00080000", sizeof(_buf.payload_rx_mon_ver_part1.hwVersion)) == 0) { _board = Board::u_blox8; } else if (strncmp((const char *)_buf.payload_rx_mon_ver_part1.hwVersion, "00190000", sizeof(_buf.payload_rx_mon_ver_part1.hwVersion)) == 0) { _board = Board::u_blox9; } else { UBX_WARN("unknown board hw: %s", _buf.payload_rx_mon_ver_part1.hwVersion); } UBX_DEBUG("detected board: %i", static_cast<int>(_board)); } // fill Part 2 buffer unsigned buf_index = (_rx_payload_index - sizeof(ubx_payload_rx_mon_ver_part1_t)) % sizeof( ubx_payload_rx_mon_ver_part2_t); p_buf[buf_index] = b; if (buf_index == sizeof(ubx_payload_rx_mon_ver_part2_t) - 1) { // Part 2 complete: decode Part 2 buffer UBX_DEBUG("VER ext \" %30s\"", _buf.payload_rx_mon_ver_part2.extension); // "FWVER=" Firmware of product category and version const char *fwver_str = strstr((const char *)_buf.payload_rx_mon_ver_part2.extension, "FWVER="); if (fwver_str != nullptr) { GPS_INFO("u-blox firmware version: %s", fwver_str + strlen("FWVER=")); } // "PROTVER=" Supported protocol version. const char *protver_str = strstr((const char *)_buf.payload_rx_mon_ver_part2.extension, "PROTVER="); if (protver_str != nullptr) { GPS_INFO("u-blox protocol version: %s", protver_str + strlen("PROTVER=")); } // "MOD=" Module identification. Set in production. const char *mod_str = strstr((const char *)_buf.payload_rx_mon_ver_part2.extension, "MOD="); if (mod_str != nullptr) { // in case of u-blox9 family, check if it's an F9P if (_board == Board::u_blox9) { if (strstr(mod_str, "F9P")) { _board = Board::u_blox9_F9P; UBX_DEBUG("F9P detected"); } } GPS_INFO("u-blox module: %s", mod_str + strlen("MOD=")); } } } if (++_rx_payload_index >= _rx_payload_length) { ret = 1; // payload received completely } return ret; } /** * Finish payload rx */ int // 0 = no message handled, 1 = message handled, 2 = sat info message handled GPSDriverUBX::payloadRxDone() { int ret = 0; // return if no message handled if (_rx_state != UBX_RXMSG_HANDLE) { return ret; } // handle message switch (_rx_msg) { case UBX_MSG_NAV_PVT: UBX_TRACE_RXMSG("Rx NAV-PVT"); //Check if position fix flag is good if ((_buf.payload_rx_nav_pvt.flags & UBX_RX_NAV_PVT_FLAGS_GNSSFIXOK) == 1) { _gps_position->fix_type = _buf.payload_rx_nav_pvt.fixType; if (_buf.payload_rx_nav_pvt.flags & UBX_RX_NAV_PVT_FLAGS_DIFFSOLN) { _gps_position->fix_type = 4; //DGPS } uint8_t carr_soln = _buf.payload_rx_nav_pvt.flags >> 6; if (carr_soln == 1) { _gps_position->fix_type = 5; //Float RTK } else if (carr_soln == 2) { _gps_position->fix_type = 6; //Fixed RTK } _gps_position->vel_ned_valid = true; } else { _gps_position->fix_type = 0; _gps_position->vel_ned_valid = false; } _gps_position->satellites_used = _buf.payload_rx_nav_pvt.numSV; _gps_position->lat = _buf.payload_rx_nav_pvt.lat; _gps_position->lon = _buf.payload_rx_nav_pvt.lon; _gps_position->alt = _buf.payload_rx_nav_pvt.hMSL; _gps_position->alt_ellipsoid = _buf.payload_rx_nav_pvt.height; _gps_position->eph = static_cast<float>(_buf.payload_rx_nav_pvt.hAcc) * 1e-3f; _gps_position->epv = static_cast<float>(_buf.payload_rx_nav_pvt.vAcc) * 1e-3f; _gps_position->s_variance_m_s = static_cast<float>(_buf.payload_rx_nav_pvt.sAcc) * 1e-3f; _gps_position->vel_m_s = static_cast<float>(_buf.payload_rx_nav_pvt.gSpeed) * 1e-3f; _gps_position->vel_n_m_s = static_cast<float>(_buf.payload_rx_nav_pvt.velN) * 1e-3f; _gps_position->vel_e_m_s = static_cast<float>(_buf.payload_rx_nav_pvt.velE) * 1e-3f; _gps_position->vel_d_m_s = static_cast<float>(_buf.payload_rx_nav_pvt.velD) * 1e-3f; _gps_position->cog_rad = static_cast<float>(_buf.payload_rx_nav_pvt.headMot) * M_DEG_TO_RAD_F * 1e-5f; _gps_position->c_variance_rad = static_cast<float>(_buf.payload_rx_nav_pvt.headAcc) * M_DEG_TO_RAD_F * 1e-5f; //Check if time and date fix flags are good if ((_buf.payload_rx_nav_pvt.valid & UBX_RX_NAV_PVT_VALID_VALIDDATE) && (_buf.payload_rx_nav_pvt.valid & UBX_RX_NAV_PVT_VALID_VALIDTIME) && (_buf.payload_rx_nav_pvt.valid & UBX_RX_NAV_PVT_VALID_FULLYRESOLVED)) { /* convert to unix timestamp */ tm timeinfo{}; timeinfo.tm_year = _buf.payload_rx_nav_pvt.year - 1900; timeinfo.tm_mon = _buf.payload_rx_nav_pvt.month - 1; timeinfo.tm_mday = _buf.payload_rx_nav_pvt.day; timeinfo.tm_hour = _buf.payload_rx_nav_pvt.hour; timeinfo.tm_min = _buf.payload_rx_nav_pvt.min; timeinfo.tm_sec = _buf.payload_rx_nav_pvt.sec; #ifndef NO_MKTIME time_t epoch = mktime(&timeinfo); if (epoch > GPS_EPOCH_SECS) { // FMUv2+ boards have a hardware RTC, but GPS helps us to configure it // and control its drift. Since we rely on the HRT for our monotonic // clock, updating it from time to time is safe. timespec ts{}; ts.tv_sec = epoch; ts.tv_nsec = _buf.payload_rx_nav_pvt.nano; setClock(ts); _gps_position->time_utc_usec = static_cast<uint64_t>(epoch) * 1000000ULL; _gps_position->time_utc_usec += _buf.payload_rx_nav_pvt.nano / 1000; } else { _gps_position->time_utc_usec = 0; } #else _gps_position->time_utc_usec = 0; #endif } _gps_position->timestamp = gps_absolute_time(); _last_timestamp_time = _gps_position->timestamp; _rate_count_vel++; _rate_count_lat_lon++; _got_posllh = true; _got_velned = true; ret = 1; break; case UBX_MSG_INF_DEBUG: case UBX_MSG_INF_NOTICE: { uint8_t *p_buf = (uint8_t *)&_buf; p_buf[_rx_payload_length] = 0; UBX_DEBUG("ubx msg: %s", p_buf); } break; case UBX_MSG_INF_ERROR: case UBX_MSG_INF_WARNING: { uint8_t *p_buf = (uint8_t *)&_buf; p_buf[_rx_payload_length] = 0; UBX_WARN("ubx msg: %s", p_buf); } break; case UBX_MSG_NAV_POSLLH: UBX_TRACE_RXMSG("Rx NAV-POSLLH"); _gps_position->lat = _buf.payload_rx_nav_posllh.lat; _gps_position->lon = _buf.payload_rx_nav_posllh.lon; _gps_position->alt = _buf.payload_rx_nav_posllh.hMSL; _gps_position->eph = static_cast<float>(_buf.payload_rx_nav_posllh.hAcc) * 1e-3f; // from mm to m _gps_position->epv = static_cast<float>(_buf.payload_rx_nav_posllh.vAcc) * 1e-3f; // from mm to m _gps_position->alt_ellipsoid = _buf.payload_rx_nav_posllh.height; _gps_position->timestamp = gps_absolute_time(); _rate_count_lat_lon++; _got_posllh = true; ret = 1; break; case UBX_MSG_NAV_SOL: UBX_TRACE_RXMSG("Rx NAV-SOL"); _gps_position->fix_type = _buf.payload_rx_nav_sol.gpsFix; _gps_position->s_variance_m_s = static_cast<float>(_buf.payload_rx_nav_sol.sAcc) * 1e-2f; // from cm to m _gps_position->satellites_used = _buf.payload_rx_nav_sol.numSV; ret = 1; break; case UBX_MSG_NAV_DOP: UBX_TRACE_RXMSG("Rx NAV-DOP"); _gps_position->hdop = _buf.payload_rx_nav_dop.hDOP * 0.01f; // from cm to m _gps_position->vdop = _buf.payload_rx_nav_dop.vDOP * 0.01f; // from cm to m ret = 1; break; case UBX_MSG_NAV_TIMEUTC: UBX_TRACE_RXMSG("Rx NAV-TIMEUTC"); if (_buf.payload_rx_nav_timeutc.valid & UBX_RX_NAV_TIMEUTC_VALID_VALIDUTC) { // convert to unix timestamp tm timeinfo {}; timeinfo.tm_year = _buf.payload_rx_nav_timeutc.year - 1900; timeinfo.tm_mon = _buf.payload_rx_nav_timeutc.month - 1; timeinfo.tm_mday = _buf.payload_rx_nav_timeutc.day; timeinfo.tm_hour = _buf.payload_rx_nav_timeutc.hour; timeinfo.tm_min = _buf.payload_rx_nav_timeutc.min; timeinfo.tm_sec = _buf.payload_rx_nav_timeutc.sec; timeinfo.tm_isdst = 0; #ifndef NO_MKTIME time_t epoch = mktime(&timeinfo); // only set the time if it makes sense if (epoch > GPS_EPOCH_SECS) { // FMUv2+ boards have a hardware RTC, but GPS helps us to configure it // and control its drift. Since we rely on the HRT for our monotonic // clock, updating it from time to time is safe. timespec ts{}; ts.tv_sec = epoch; ts.tv_nsec = _buf.payload_rx_nav_timeutc.nano; setClock(ts); _gps_position->time_utc_usec = static_cast<uint64_t>(epoch) * 1000000ULL; _gps_position->time_utc_usec += _buf.payload_rx_nav_timeutc.nano / 1000; } else { _gps_position->time_utc_usec = 0; } #else _gps_position->time_utc_usec = 0; #endif } _last_timestamp_time = gps_absolute_time(); ret = 1; break; case UBX_MSG_NAV_SAT: case UBX_MSG_NAV_SVINFO: UBX_TRACE_RXMSG("Rx NAV-SVINFO"); // _satellite_info already populated by payload_rx_add_svinfo(), just add a timestamp _satellite_info->timestamp = gps_absolute_time(); ret = 2; break; case UBX_MSG_NAV_SVIN: UBX_TRACE_RXMSG("Rx NAV-SVIN"); { ubx_payload_rx_nav_svin_t &svin = _buf.payload_rx_nav_svin; UBX_DEBUG("Survey-in status: %lus cur accuracy: %lumm nr obs: %lu valid: %i active: %i", svin.dur, svin.meanAcc / 10, svin.obs, static_cast<int>(svin.valid), static_cast<int>(svin.active)); SurveyInStatus status{}; double ecef_x = (static_cast<double>(svin.meanX) + static_cast<double>(svin.meanXHP) * 0.01) * 0.01; double ecef_y = (static_cast<double>(svin.meanY) + static_cast<double>(svin.meanYHP) * 0.01) * 0.01; double ecef_z = (static_cast<double>(svin.meanZ) + static_cast<double>(svin.meanZHP) * 0.01) * 0.01; ECEF2lla(ecef_x, ecef_y, ecef_z, status.latitude, status.longitude, status.altitude); status.duration = svin.dur; status.mean_accuracy = svin.meanAcc / 10; status.flags = (svin.valid & 1) | ((svin.active & 1) << 1); surveyInStatus(status); if (svin.valid == 1 && svin.active == 0) { if (activateRTCMOutput(true) != 0) { return 0; } } } ret = 1; break; case UBX_MSG_NAV_VELNED: UBX_TRACE_RXMSG("Rx NAV-VELNED"); _gps_position->vel_m_s = static_cast<float>(_buf.payload_rx_nav_velned.gSpeed) * 1e-2f; _gps_position->vel_n_m_s = static_cast<float>(_buf.payload_rx_nav_velned.velN) * 1e-2f; // NED NORTH velocity _gps_position->vel_e_m_s = static_cast<float>(_buf.payload_rx_nav_velned.velE) * 1e-2f; // NED EAST velocity _gps_position->vel_d_m_s = static_cast<float>(_buf.payload_rx_nav_velned.velD) * 1e-2f; // NED DOWN velocity _gps_position->cog_rad = static_cast<float>(_buf.payload_rx_nav_velned.heading) * M_DEG_TO_RAD_F * 1e-5f; _gps_position->c_variance_rad = static_cast<float>(_buf.payload_rx_nav_velned.cAcc) * M_DEG_TO_RAD_F * 1e-5f; _gps_position->vel_ned_valid = true; _rate_count_vel++; _got_velned = true; ret = 1; break; case UBX_MSG_NAV_RELPOSNED: UBX_TRACE_RXMSG("Rx NAV-RELPOSNED"); if ((_mode == UBXMode::RoverWithMovingBase) || (_mode == UBXMode::RoverWithMovingBaseUART1)) { float heading = _buf.payload_rx_nav_relposned.relPosHeading * 1e-5f; float heading_acc = _buf.payload_rx_nav_relposned.accHeading * 1e-5f; float rel_length = _buf.payload_rx_nav_relposned.relPosLength + _buf.payload_rx_nav_relposned.relPosHPLength * 1e-2f; float rel_length_acc = _buf.payload_rx_nav_relposned.accLength * 1e-2f; bool heading_valid = _buf.payload_rx_nav_relposned.flags & (1 << 8); bool rel_pos_valid = _buf.payload_rx_nav_relposned.flags & (1 << 2); bool carrier_solution_fixed = _buf.payload_rx_nav_relposned.flags & (1 << 4); (void)rel_length_acc; if (heading_valid && rel_pos_valid && rel_length < 1000.f && carrier_solution_fixed) { // validity & sanity checks heading *= M_PI_F / 180.0f; // deg to rad, now in range [0, 2pi] heading -= _heading_offset; // range: [-pi, 3pi] if (heading > M_PI_F) { heading -= 2.f * M_PI_F; // final range is [-pi, pi] } _gps_position->heading = heading; heading_acc *= M_PI_F / 180.0f; // deg to rad, now in range [0, 2pi] _gps_position->heading_accuracy = heading_acc; UBX_DEBUG("Heading: %.3f rad, acc: %.1f deg, relLen: %.1f cm, relAcc: %.1f cm, valid: %i %i", (double)heading, (double)heading_acc, (double)rel_length, (double)rel_length_acc, heading_valid, rel_pos_valid); } ret = 1; } { sensor_gnss_relative_s gps_rel{}; gps_rel.timestamp_sample = gps_absolute_time(); // TODO: adjust with delay estimate gps_rel.time_utc_usec = _buf.payload_rx_nav_relposned.iTOW * 1000; // TODO: convert iTOW ms GPS time of week gps_rel.reference_station_id = _buf.payload_rx_nav_relposned.refStationId; // relPosN + (relPosHPN * 1e-2), relPosHPN is 0.1 mm gps_rel.position[0] = (_buf.payload_rx_nav_relposned.relPosN + _buf.payload_rx_nav_relposned.relPosHPN * 1e-2f) * 1e-2f; gps_rel.position[1] = (_buf.payload_rx_nav_relposned.relPosE + _buf.payload_rx_nav_relposned.relPosHPE * 1e-2f) * 1e-2f; gps_rel.position[2] = (_buf.payload_rx_nav_relposned.relPosD + _buf.payload_rx_nav_relposned.relPosHPD * 1e-2f) * 1e-2f; // full length of the relative position vector, in units of cm, is given by relPosLength + (relPosHPLength * 1e-2) gps_rel.position_length = (_buf.payload_rx_nav_relposned.relPosLength + _buf.payload_rx_nav_relposned.relPosHPLength * 1e-2f) * 1e-2f; gps_rel.heading = _buf.payload_rx_nav_relposned.relPosHeading * 1e-5f * (M_PI_F / 180.f); // 1e-5 deg -> radians gps_rel.heading_accuracy = _buf.payload_rx_nav_relposned.accHeading * 1e-5f * (M_PI_F / 180.f); // 1e-5 deg -> radians // Accuracy of relative position in 0.1 mm gps_rel.position_accuracy[0] = _buf.payload_rx_nav_relposned.accN * 1e-4f; // 0.1mm -> m gps_rel.position_accuracy[1] = _buf.payload_rx_nav_relposned.accE * 1e-4f; // 0.1mm -> m gps_rel.position_accuracy[2] = _buf.payload_rx_nav_relposned.accD * 1e-4f; // 0.1mm -> m gps_rel.accuracy_length = _buf.payload_rx_nav_relposned.accLength * 1e-4f; // 0.1mm -> m gps_rel.gnss_fix_ok = _buf.payload_rx_nav_relposned.flags & (1 << 0); gps_rel.differential_solution = _buf.payload_rx_nav_relposned.flags & (1 << 1); gps_rel.relative_position_valid = _buf.payload_rx_nav_relposned.flags & (1 << 2); gps_rel.carrier_solution_floating = _buf.payload_rx_nav_relposned.flags & (1 << 3); gps_rel.carrier_solution_fixed = _buf.payload_rx_nav_relposned.flags & (1 << 4); gps_rel.moving_base_mode = _buf.payload_rx_nav_relposned.flags & (1 << 5); gps_rel.reference_position_miss = _buf.payload_rx_nav_relposned.flags & (1 << 6); gps_rel.reference_observations_miss = _buf.payload_rx_nav_relposned.flags & (1 << 7); gps_rel.heading_valid = _buf.payload_rx_nav_relposned.flags & (1 << 8); gps_rel.relative_position_normalized = _buf.payload_rx_nav_relposned.flags & (1 << 9); gotRelativePositionMessage(gps_rel); } break; case UBX_MSG_MON_VER: UBX_TRACE_RXMSG("Rx MON-VER"); // This is polled only on startup, and the startup code waits for an ack if (_ack_state == UBX_ACK_WAITING && _ack_waiting_msg == UBX_MSG_MON_VER) { _ack_state = UBX_ACK_GOT_ACK; } ret = 1; break; case UBX_MSG_MON_HW: UBX_TRACE_RXMSG("Rx MON-HW"); switch (_rx_payload_length) { case sizeof(ubx_payload_rx_mon_hw_ubx6_t): /* u-blox 6 msg format */ _gps_position->noise_per_ms = _buf.payload_rx_mon_hw_ubx6.noisePerMS; _gps_position->automatic_gain_control = _buf.payload_rx_mon_hw_ubx6.agcCnt; _gps_position->jamming_indicator = _buf.payload_rx_mon_hw_ubx6.jamInd; ret = 1; break; case sizeof(ubx_payload_rx_mon_hw_ubx7_t): /* u-blox 7+ msg format */ _gps_position->noise_per_ms = _buf.payload_rx_mon_hw_ubx7.noisePerMS; _gps_position->automatic_gain_control = _buf.payload_rx_mon_hw_ubx7.agcCnt; _gps_position->jamming_indicator = _buf.payload_rx_mon_hw_ubx7.jamInd; ret = 1; break; default: // unexpected payload size: ret = 0; // don't handle message break; } break; case UBX_MSG_MON_RF: UBX_TRACE_RXMSG("Rx MON-RF"); _gps_position->noise_per_ms = _buf.payload_rx_mon_rf.block[0].noisePerMS; _gps_position->jamming_indicator = _buf.payload_rx_mon_rf.block[0].jamInd; _gps_position->jamming_state = _buf.payload_rx_mon_rf.block[0].flags; ret = 1; break; case UBX_MSG_ACK_ACK: UBX_TRACE_RXMSG("Rx ACK-ACK"); if ((_ack_state == UBX_ACK_WAITING) && (_buf.payload_rx_ack_ack.msg == _ack_waiting_msg)) { _ack_state = UBX_ACK_GOT_ACK; } ret = 1; break; case UBX_MSG_ACK_NAK: UBX_TRACE_RXMSG("Rx ACK-NAK"); if ((_ack_state == UBX_ACK_WAITING) && (_buf.payload_rx_ack_ack.msg == _ack_waiting_msg)) { _ack_state = UBX_ACK_GOT_NAK; } ret = 1; break; default: break; } if (ret > 0) { _gps_position->timestamp_time_relative = (int32_t)(_last_timestamp_time - _gps_position->timestamp); } return ret; } int GPSDriverUBX::activateRTCMOutput(bool reduce_update_rate) { /* For base stations we switch to 1 Hz update rate, which is enough for RTCM output. * For the survey-in, we still want 5/10 Hz, because this speeds up the process */ if (_proto_ver_27_or_higher) { int cfg_valset_msg_size = initCfgValset(); if (reduce_update_rate) { cfgValset<uint16_t>(UBX_CFG_KEY_RATE_MEAS, 1000, cfg_valset_msg_size); } cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1005_I2C, 5, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1077_I2C, 1, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1087_I2C, 1, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1230_I2C, 1, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1097_I2C, 1, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_RTCM_3X_TYPE1127_I2C, 1, cfg_valset_msg_size); cfgValsetPort(UBX_CFG_KEY_MSGOUT_UBX_NAV_SVIN_I2C, 0, cfg_valset_msg_size); if (!sendMessage(UBX_MSG_CFG_VALSET, (uint8_t *)&_buf, cfg_valset_msg_size)) { return -1; } if (waitForAck(UBX_MSG_CFG_VALSET, UBX_CONFIG_TIMEOUT, false) < 0) { return -1; } } else { if (reduce_update_rate) { memset(&_buf.payload_tx_cfg_rate, 0, sizeof(_buf.payload_tx_cfg_rate)); _buf.payload_tx_cfg_rate.measRate = 1000; _buf.payload_tx_cfg_rate.navRate = UBX_TX_CFG_RATE_NAVRATE; _buf.payload_tx_cfg_rate.timeRef = UBX_TX_CFG_RATE_TIMEREF; if (!sendMessage(UBX_MSG_CFG_RATE, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_rate))) { return -1; } // according to the spec we should receive an (N)ACK here, but we don't } configureMessageRate(UBX_MSG_NAV_SVIN, 0); // stationary RTK reference station ARP (can be sent at lower rate) if (!configureMessageRate(UBX_MSG_RTCM3_1005, 5)) { return -1; } // GPS if (!configureMessageRate(UBX_MSG_RTCM3_1077, 1)) { return -1; } // GLONASS if (!configureMessageRate(UBX_MSG_RTCM3_1087, 1)) { return -1; } // GLONASS code-phase biases if (!configureMessageRate(UBX_MSG_RTCM3_1230, 1)) { return -1; } // Galileo if (!configureMessageRate(UBX_MSG_RTCM3_1097, 1)) { return -1; } // BeiDou if (!configureMessageRate(UBX_MSG_RTCM3_1127, 1)) { return -1; } } return 0; } void GPSDriverUBX::decodeInit() { _decode_state = UBX_DECODE_SYNC1; _rx_ck_a = 0; _rx_ck_b = 0; _rx_payload_length = 0; _rx_payload_index = 0; if (_output_mode == OutputMode::GPSAndRTCM || _output_mode == OutputMode::RTCM || _mode == UBXMode::MovingBaseUART1) { if (!_rtcm_parsing) { _rtcm_parsing = new RTCMParsing(); } if (_rtcm_parsing) { _rtcm_parsing->reset(); } } } void GPSDriverUBX::addByteToChecksum(const uint8_t b) { _rx_ck_a = _rx_ck_a + b; _rx_ck_b = _rx_ck_b + _rx_ck_a; } void GPSDriverUBX::calcChecksum(const uint8_t *buffer, const uint16_t length, ubx_checksum_t *checksum) { for (uint16_t i = 0; i < length; i++) { checksum->ck_a = checksum->ck_a + buffer[i]; checksum->ck_b = checksum->ck_b + checksum->ck_a; } } bool GPSDriverUBX::configureMessageRate(const uint16_t msg, const uint8_t rate) { if (_proto_ver_27_or_higher) { // configureMessageRate() should not be called if _proto_ver_27_or_higher is true. // If you see this message the calling code needs to be fixed. UBX_WARN("FIXME: use of deprecated msg CFG_MSG (%i %i)", msg, rate); } ubx_payload_tx_cfg_msg_t cfg_msg; // don't use _buf (allow interleaved operation) memset(&cfg_msg, 0, sizeof(cfg_msg)); cfg_msg.msg = msg; cfg_msg.rate = rate; return sendMessage(UBX_MSG_CFG_MSG, (uint8_t *)&cfg_msg, sizeof(cfg_msg)); } bool GPSDriverUBX::configureMessageRateAndAck(uint16_t msg, uint8_t rate, bool report_ack_error) { if (!configureMessageRate(msg, rate)) { return false; } return waitForAck(UBX_MSG_CFG_MSG, UBX_CONFIG_TIMEOUT, report_ack_error) >= 0; } bool GPSDriverUBX::sendMessage(const uint16_t msg, const uint8_t *payload, const uint16_t length) { ubx_header_t header = {UBX_SYNC1, UBX_SYNC2, 0, 0}; ubx_checksum_t checksum = {0, 0}; // Populate header header.msg = msg; header.length = length; // Calculate checksum calcChecksum(((uint8_t *)&header) + 2, sizeof(header) - 2, &checksum); // skip 2 sync bytes if (payload != nullptr) { calcChecksum(payload, length, &checksum); } // Send message if (write((void *)&header, sizeof(header)) != sizeof(header)) { return false; } if (payload && write((void *)payload, length) != length) { return false; } if (write((void *)&checksum, sizeof(checksum)) != sizeof(checksum)) { return false; } return true; } uint32_t GPSDriverUBX::fnv1_32_str(uint8_t *str, uint32_t hval) { uint8_t *s = str; /* * FNV-1 hash each octet in the buffer */ while (*s) { /* multiply by the 32 bit FNV magic prime mod 2^32 */ #if defined(NO_FNV_GCC_OPTIMIZATION) hval *= FNV1_32_PRIME; #else hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); #endif /* xor the bottom with the current octet */ hval ^= (uint32_t) * s++; } /* return our new hash value */ return hval; } int GPSDriverUBX::reset(GPSRestartType restart_type) { memset(&_buf.payload_tx_cfg_rst, 0, sizeof(_buf.payload_tx_cfg_rst)); _buf.payload_tx_cfg_rst.resetMode = UBX_TX_CFG_RST_MODE_SOFTWARE; switch (restart_type) { case GPSRestartType::Hot: _buf.payload_tx_cfg_rst.navBbrMask = UBX_TX_CFG_RST_BBR_MODE_HOT_START; break; case GPSRestartType::Warm: _buf.payload_tx_cfg_rst.navBbrMask = UBX_TX_CFG_RST_BBR_MODE_WARM_START; break; case GPSRestartType::Cold: _buf.payload_tx_cfg_rst.navBbrMask = UBX_TX_CFG_RST_BBR_MODE_COLD_START; break; default: return -2; } if (sendMessage(UBX_MSG_CFG_RST, (uint8_t *)&_buf, sizeof(_buf.payload_tx_cfg_rst))) { return 0; } return -2; }
; A264238: Number of (n+1) X (2+1) arrays of permutations of 0..n*3+2 with each element having directed index change 0,0 1,1 0,-1 -1,1 or 0,-2. ; Submitted by Simon Strandgaard ; 8,21,89,296,1105,3897,14128,50533,181937,652944,2346977,8429681,30288280,108807669,390915337,1404388408,5045461169,18126337449,65121053504,233954670533,840509324641,3019625618976,10848352515265,38973949419745,140018388312104,503032120627413,1807200621707705,6492575578867784,23325322767354385,83798898386207769,301057157797674064,1081582383145240357,3885708814690317329,13959854770454402736,50152380045905469089,180178179899847037265,647310785304672486328,2325538269962521727157 add $0,3 mov $1,1 lpb $0 sub $0,1 add $3,$2 add $2,$3 mov $4,$3 mul $4,3 add $4,$2 mov $2,$1 mov $1,$4 add $1,$3 add $2,$3 lpe mov $0,$2
; A024020: a(n) = 2^n - n^10. ; 1,1,-1020,-59041,-1048560,-9765593,-60466112,-282475121,-1073741568,-3486783889,-9999998976,-25937422553,-61917360128,-137858483657,-289254638592,-576650357857,-1099511562240,-2015993769377,-3570466964480,-6131065733513,-10239998951424,-16679878881049,-26559918597120,-41426502825041,-63403364188160,-95367398086193,-141167028544512,-205890997876921,-296196498259968,-420706696429289,-590488926258176,-819626139497153,-1125895611875328,-1531570395329857,-2064360574190592,-2758512993777257,-3656089720586240,-4808446933464377,-6277936970081280,-8139856329377713,-10484660488372224,-13420460286896849,-17075800075166720,-21602686220262041,-27179768752373760,-34015444543926793,-42350378738598912,-52458394747474721,-64643587131834368,-79229316344190689,-96530350093157376,-116790624013927753,-140051506321686528,-165880271110772057,-192818120755438592,-217266365100176657,-231247895058186240,-217918143381035377,-142573830747694080,65343999002782087,548259744606846976,1592500097550811351,3772386652559047680,8238441744972984959,17293822569102704640,35547213812956212607,72218639413927410688,145751114785124651479,293033982359195615232,587849616298050891911,1177766868227411303424,2357927997883812725647,4718622576627020726272,9440435339909586869743,18884541941081224977408,37773300511486214443943,75551434836981983477760,151108400771356060637623,302223119127826057477120,604453441531231960505887,1208915082196389174706176,2417839481563799292483551,4835689533655383102766080,9671391040875846191795959,19342795623711190197207040,38685606540227699518332007,77371230325178378378124288,154742480068331115218821679,309484981971247467784568832,618969988460970207483378511,1237940004417536264899124224,2475880039629148737987503047,4951760113702675677233283072,9903520265884811481263675543,19807040574704572988896017408,39614081197258474872934084543,79228162447781073994393845760,158456324954786262497595074623,316912649975350069685421112320,633825300023676493247471153687 mov $1,2 pow $1,$0 pow $0,10 sub $1,$0 mov $0,$1
#include "cinn/hlir/pe/broadcast.h" #include <iostream> #include "cinn/hlir/framework/node.h" #include "cinn/hlir/framework/op.h" #include "cinn/hlir/framework/op_strategy.h" #include "cinn/ir/ir_operators.h" namespace cinn { namespace hlir { namespace op { using common::_CINNValuePack_; using common::CINNValue; using common::CINNValuePack; using framework::OpStrategy; using framework::shape_t; using framework::StrategyFunction; std::shared_ptr<OpStrategy> StrategyForElementwiseAdd(const framework::NodeAttr &attrs, const std::vector<ir::Tensor> &inputs, const std::vector<Type> &out_type, const std::vector<std::vector<int>> &output_shapes, const Target &target) { framework::CINNCompute add_compute([&attrs](lang::Args args, lang::RetValue *ret) { CHECK(!args.empty()) << "The input argument of add compute is empty! Please check.\n"; CINNValuePack a = args[0]; CHECK_GE(a.size(), 2U) << "at least 2 input tensors for add compute\n"; Expr A_expr = a[0]; Expr B_expr = a[1]; CHECK(A_expr.as_tensor()); CHECK(B_expr.as_tensor()); ir::Tensor A = A_expr.as_tensor_ref(); ir::Tensor B = B_expr.as_tensor_ref(); Expr axis; bool trans_a; for (auto &iter : attrs.attr_store) { if (iter.first == "axis") { axis = Expr(std::get<int>(iter.second)); } else { LOG(ERROR) << "unsupported attr_store: " << iter.first << std::endl; } } auto out = pe::Add(A, B, UniqName("C"), axis); auto stages = CreateStages({A, B, out}); *ret = CINNValuePack{{CINNValue(Expr(out.get())), CINNValue(stages)}}; }); framework::CINNSchedule add_schedule([](lang::Args args, lang::RetValue *ret) { CHECK(!args.empty()) << "The input argument of add schedule is empty! Please check.\n"; CINNValuePack arg_pack = args[0]; CHECK_EQ(arg_pack.size(), 2UL); Expr A [[maybe_unused]] = arg_pack[0]; *ret = arg_pack; }); auto strategy = std::make_shared<framework::OpStrategy>(); strategy->AddImpl(add_compute, add_schedule, "strategy.elementwise_add.x86", 1); return strategy; } std::shared_ptr<OpStrategy> StrategyForElementwiseMul(const framework::NodeAttr &attrs, const std::vector<ir::Tensor> &inputs, const std::vector<Type> &out_type, const std::vector<std::vector<int>> &output_shapes, const Target &target) { framework::CINNCompute mul_compute([&attrs](lang::Args args, lang::RetValue *ret) { CHECK(!args.empty()) << "The input argument of elementwise_mul compute is empty! Please check.\n"; CINNValuePack a = args[0]; CHECK_GE(a.size(), 2U) << "at least 2 input tensors for elementwise_mul compute\n"; Expr A_expr = a[0]; Expr B_expr = a[1]; CHECK(A_expr.as_tensor()); CHECK(B_expr.as_tensor()); ir::Tensor A = A_expr.as_tensor_ref(); ir::Tensor B = B_expr.as_tensor_ref(); auto attr_store = attrs.attr_store; auto iter = attr_store.find("axis"); Expr axis; if (iter != attr_store.end()) { axis = Expr(std::get<int>(iter->second)); } auto out = pe::Multiply(A, B, UniqName("C"), axis); auto stages = CreateStages({A, B, out}); *ret = CINNValuePack{{CINNValue(Expr(out.get())), CINNValue(stages)}}; }); framework::CINNSchedule mul_schedule([](lang::Args args, lang::RetValue *ret) { CHECK(!args.empty()) << "The input argument of elementwise_mul schedule is empty! Please check.\n"; CINNValuePack arg_pack = args[0]; CHECK_EQ(arg_pack.size(), 2UL); Expr A [[maybe_unused]] = arg_pack[0]; *ret = arg_pack; }); auto strategy = std::make_shared<framework::OpStrategy>(); strategy->AddImpl(mul_compute, mul_schedule, "strategy.elementwise_mul.x86", 1); return strategy; } std::vector<shape_t> InferShapeForElementwise(const std::vector<shape_t> &inputs_shape, const framework::NodeAttr &attrs) { CHECK_EQ(inputs_shape.size(), 2UL); std::vector<shape_t> res{inputs_shape[0]}; return res; } std::vector<Type> InferDtypeForElementwise(const std::vector<Type> &inputs_type, const framework::NodeAttr &attrs) { CHECK(!inputs_type.empty()) << "The input's type size is 0! Please check again."; std::vector<Type> res{inputs_type[0]}; return res; } std::shared_ptr<OpStrategy> StrategyForScale(const framework::NodeAttr &attrs, const std::vector<ir::Tensor> &inputs, const std::vector<Type> &out_type, const std::vector<std::vector<int>> &output_shapes, const Target &target) { float scale = 1.f; float bias = 0.f; bool bias_after_scale = true; for (auto &iter : attrs.attr_store) { if (iter.first == "scale") { scale = std::get<float>(iter.second); } else if (iter.first == "bias") { bias = std::get<float>(iter.second); } else if (iter.first == "bias_after_scale") { bias_after_scale = std::get<bool>(iter.second); } } framework::CINNCompute scale_compute([=](lang::Args args, lang::RetValue *ret) { CHECK(!args.empty()) << "The input arguments of scale compute is empty! Please check."; CINNValuePack a = args[0]; CHECK(!a.empty()) << "The input tensors of scale compute is empty! Please check."; Expr A_expr = a[0]; CHECK(A_expr.as_tensor()); ir::Tensor A = A_expr.as_tensor_ref(); ir::Tensor out; if (bias_after_scale) { out = Compute( A->shape, [=](const std::vector<Expr> &indice) { return scale * A(indice) + bias; }, UniqName("Scale_out")); } else { out = Compute( A->shape, [=](const std::vector<Expr> &indice) { return scale * (A(indice) + bias); }, UniqName("Scale_out")); } auto stages = CreateStages({out}); *ret = CINNValuePack{{CINNValue(Expr(out.get())), CINNValue(stages)}}; }); framework::CINNSchedule scale_schedule([](lang::Args args, lang::RetValue *ret) { CHECK(!args.empty()) << "The input arguments of scale schedule is empty! Please check."; CINNValuePack arg_pack = args[0]; CHECK_EQ(arg_pack.size(), 2UL) << "The input tensor's size of scale schedule is " << arg_pack.size() << "and it should be equal to 2! Please check."; Expr A [[maybe_unused]] = arg_pack[0]; *ret = arg_pack; }); auto strategy = std::make_shared<framework::OpStrategy>(); strategy->AddImpl(scale_compute, scale_schedule, "strategy.scale.x86", 1); return strategy; } std::vector<shape_t> InferShapeForScale(const std::vector<shape_t> &inputs_shape, const framework::NodeAttr &attrs) { CHECK(!inputs_shape.empty() && !inputs_shape[0].empty()) << "The input's shape size is 0! Please check again."; return {{inputs_shape[0]}}; } std::vector<Type> InferDtypeForScale(const std::vector<Type> &inputs_type, const framework::NodeAttr &attrs) { CHECK(!inputs_type.empty()) << "The input's type size is 0! Please check again."; std::vector<Type> res{inputs_type[0]}; return res; } } // namespace op } // namespace hlir } // namespace cinn CINN_REGISTER_HELPER(broadcast_ops) { CINN_REGISTER_OP(elementwise_add) .describe("Add two tensors") .set_num_inputs(2) .set_num_outputs(1) .set_attr<cinn::hlir::framework::StrategyFunction>("CINNStrategy", cinn::hlir::op::StrategyForElementwiseAdd) .set_attr("infershape", std::function(cinn::hlir::op::InferShapeForElementwise)) .set_attr("inferdtype", std::function(cinn::hlir::op::InferDtypeForElementwise)) .set_support_level(4); CINN_REGISTER_OP(elementwise_mul) .describe("multiply two tensors") .set_num_inputs(2) .set_num_outputs(1) .set_attr<cinn::hlir::framework::StrategyFunction>("CINNStrategy", cinn::hlir::op::StrategyForElementwiseMul) .set_attr("infershape", std::function(cinn::hlir::op::InferShapeForElementwise)) .set_attr("inferdtype", std::function(cinn::hlir::op::InferDtypeForElementwise)) .set_support_level(4); CINN_REGISTER_OP(scale) .describe("Putting scale and bias to the input Tensor") .set_num_inputs(1) .set_num_outputs(1) .set_attr<cinn::hlir::framework::StrategyFunction>("CINNStrategy", cinn::hlir::op::StrategyForScale) .set_attr("infershape", std::function(cinn::hlir::op::InferShapeForScale)) .set_attr("inferdtype", std::function(cinn::hlir::op::InferDtypeForScale)) .set_support_level(4); return true; }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__wchar_t_file_w32CreateFile_51a.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-51a.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: file Read input from a file * GoodSource: Use a fixed file name * Sink: w32CreateFile * BadSink : Open the file named in data using CreateFile() * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH L"c:\\temp\\" #else #include <wchar.h> #define BASEPATH L"/tmp/" #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #include <windows.h> namespace CWE23_Relative_Path_Traversal__wchar_t_file_w32CreateFile_51 { #ifndef OMITBAD /* bad function declaration */ void badSink(wchar_t * data); void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (FILENAME_MAX-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink(wchar_t * data); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ wcscat(data, L"file.txt"); goodG2BSink(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__wchar_t_file_w32CreateFile_51; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IConnectedPlayer class IConnectedPlayer; // Forward declaring type: GameplayServerMode struct GameplayServerMode; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: IReadOnlyList`1<T> template<typename T> class IReadOnlyList_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Completed forward declares // Begin il2cpp-utils forward declares struct Il2CppString; // Completed il2cpp-utils forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: ILobbyStateDataModel // [TokenAttribute] Offset: FFFFFFFF class ILobbyStateDataModel { public: // Creating value type constructor for type: ILobbyStateDataModel ILobbyStateDataModel() noexcept {} // public System.Boolean get_isConnected() // Offset: 0xFFFFFFFF bool get_isConnected(); // public IConnectedPlayer get_localPlayer() // Offset: 0xFFFFFFFF GlobalNamespace::IConnectedPlayer* get_localPlayer(); // public System.Collections.Generic.List`1<IConnectedPlayer> get_connectedPlayers() // Offset: 0xFFFFFFFF System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* get_connectedPlayers(); // public System.Collections.Generic.IReadOnlyList`1<IConnectedPlayer> get_rawConnectedPlayers() // Offset: 0xFFFFFFFF System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* get_rawConnectedPlayers(); // public GameplayServerMode get_gameServerMode() // Offset: 0xFFFFFFFF GlobalNamespace::GameplayServerMode get_gameServerMode(); // public System.Int32 get_maxPartySize() // Offset: 0xFFFFFFFF int get_maxPartySize(); // public System.Void add_playerConnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0xFFFFFFFF void add_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_playerConnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0xFFFFFFFF void remove_playerConnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void add_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0xFFFFFFFF void add_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void remove_playerDisconnectedEvent(System.Action`1<IConnectedPlayer> value) // Offset: 0xFFFFFFFF void remove_playerDisconnectedEvent(System::Action_1<GlobalNamespace::IConnectedPlayer*>* value); // public System.Void Activate() // Offset: 0xFFFFFFFF void Activate(); // public System.Void Deactivate() // Offset: 0xFFFFFFFF void Deactivate(); // public IConnectedPlayer GetPlayerById(System.String userId) // Offset: 0xFFFFFFFF GlobalNamespace::IConnectedPlayer* GetPlayerById(::Il2CppString* userId); }; // ILobbyStateDataModel #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ILobbyStateDataModel*, "", "ILobbyStateDataModel"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::get_isConnected // Il2CppName: get_isConnected template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::get_isConnected)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "get_isConnected", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::get_localPlayer // Il2CppName: get_localPlayer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::get_localPlayer)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "get_localPlayer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::get_connectedPlayers // Il2CppName: get_connectedPlayers template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::List_1<GlobalNamespace::IConnectedPlayer*>* (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::get_connectedPlayers)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "get_connectedPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::get_rawConnectedPlayers // Il2CppName: get_rawConnectedPlayers template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IConnectedPlayer*>* (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::get_rawConnectedPlayers)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "get_rawConnectedPlayers", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::get_gameServerMode // Il2CppName: get_gameServerMode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::GameplayServerMode (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::get_gameServerMode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "get_gameServerMode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::get_maxPartySize // Il2CppName: get_maxPartySize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::get_maxPartySize)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "get_maxPartySize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::add_playerConnectedEvent // Il2CppName: add_playerConnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ILobbyStateDataModel::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::ILobbyStateDataModel::add_playerConnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "add_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::remove_playerConnectedEvent // Il2CppName: remove_playerConnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ILobbyStateDataModel::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::ILobbyStateDataModel::remove_playerConnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "remove_playerConnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::add_playerDisconnectedEvent // Il2CppName: add_playerDisconnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ILobbyStateDataModel::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::ILobbyStateDataModel::add_playerDisconnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "add_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::remove_playerDisconnectedEvent // Il2CppName: remove_playerDisconnectedEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ILobbyStateDataModel::*)(System::Action_1<GlobalNamespace::IConnectedPlayer*>*)>(&GlobalNamespace::ILobbyStateDataModel::remove_playerDisconnectedEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IConnectedPlayer")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "remove_playerDisconnectedEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::Activate // Il2CppName: Activate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::Activate)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "Activate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::Deactivate // Il2CppName: Deactivate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ILobbyStateDataModel::*)()>(&GlobalNamespace::ILobbyStateDataModel::Deactivate)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "Deactivate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ILobbyStateDataModel::GetPlayerById // Il2CppName: GetPlayerById template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IConnectedPlayer* (GlobalNamespace::ILobbyStateDataModel::*)(::Il2CppString*)>(&GlobalNamespace::ILobbyStateDataModel::GetPlayerById)> { static const MethodInfo* get() { static auto* userId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ILobbyStateDataModel*), "GetPlayerById", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{userId}); } };
; A110962: Fractalization of Kimberling's sequence beginning with 0. ; 0,0,0,0,1,0,0,0,2,1,1,0,3,0,0,0,4,2,2,1,5,1,1,0,6,3,3,0,7,0,0,0,8,4,4,2,9,2,2,1,10,5,5,1,11,1,1,0,12,6,6,3,13,3 mul $0,2 mov $4,9 lpb $4,14 add $4,$0 div $0,2 mov $6,$4 add $4,45 gcd $4,2 lpe mov $1,$6 div $1,4
; A061066: a(n) = (prime(n)^2 - 1)/8. ; Submitted by Jon Maiga ; 1,3,6,15,21,36,45,66,105,120,171,210,231,276,351,435,465,561,630,666,780,861,990,1176,1275,1326,1431,1485,1596,2016,2145,2346,2415,2775,2850,3081,3321,3486,3741,4005,4095,4560,4656,4851,4950,5565,6216,6441,6555,6786,7140,7260,7875,8256,8646,9045,9180,9591,9870,10011,10731,11781,12090,12246,12561,13695,14196,15051,15225,15576,16110,16836,17391,17955,18336,18915,19701,20100,20910,21945,22155,23220,23436,24090,24531,25200,26106,26565,26796,27261,28680,29646,30135,31125,31626,32385,33930,34191 seq $0,65091 ; Odd primes. pow $0,2 div $0,8
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/04/Mult.asm // Multiplies R0 and R1 and stores the result in R2. // (R0, R1, R2 refer to RAM[0], RAM[1], and RAM[2], respectively.) @R0 D=M @FIRST M=D @R1 D=M @SECOND M=D @R2 M=0 (LOOP) @FIRST D=M @END D; JEQ @SECOND D=M @R2 M=M+D @FIRST M=M-1 @LOOP 0; JMP (END)
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "console/console.h" #include "graphics/dgl.h" #include "gui/guiTypes.h" #include "gui/guiControl.h" #include "gui/guiConsole.h" #include "gui/guiConsole_Binding.h" #include "gui/containers/guiScrollCtrl.h" IMPLEMENT_CONOBJECT(GuiConsole); GuiConsole::GuiConsole() { mBounds.extent.set(64, 64); mCellSize.set(1, 1); mSize.set(1, 0); } bool GuiConsole::onWake() { if (! Parent::onWake()) return false; //get the font mFont = mProfile->mFont; return true; } S32 GuiConsole::getMaxWidth(S32 startIndex, S32 endIndex) { //sanity check U32 size; ConsoleLogEntry *log; Con::getLockLog(log, size); if(startIndex < 0 || (U32)endIndex >= size || startIndex > endIndex) return 0; S32 result = 0; for(S32 i = startIndex; i <= endIndex; i++) result = getMax(result, (S32)(mFont->getStrWidth((const UTF8 *)log[i].mString))); Con::unlockLog(); return(result + 6); } void GuiConsole::onPreRender() { //see if the size has changed U32 size; ConsoleLogEntry *log; Con::getLockLog(log, size); Con::unlockLog(); // we unlock immediately because we only use size here, not log. U32 prevSize = mBounds.extent.y / mCellSize.y; if ( prevSize > size ) prevSize = 0; if(size != prevSize) { //first, find out if the console was scrolled up bool scrolled = false; GuiScrollCtrl *parent = dynamic_cast<GuiScrollCtrl*>(getParent()); if(parent) scrolled = parent->isScrolledToBottom(); //find the max cell width for the new entries S32 newMax = getMaxWidth(0, size - 1); if(newMax > mCellSize.x) mCellSize.set(newMax, mFont->getHeight()); //set the array size mSize.set(1, size); //resize the control resize(mBounds.point, Point2I(mCellSize.x, mCellSize.y * size)); //if the console was not scrolled, make the last entry visible if (scrolled) scrollCellVisible(Point2I(0,mSize.y - 1)); } } void GuiConsole::onRenderCell(Point2I offset, Point2I cell, bool /*selected*/, bool /*mouseOver*/) { U32 size; ConsoleLogEntry *log; Con::getLockLog(log, size); ConsoleLogEntry &entry = log[cell.y]; switch (entry.mLevel) { case ConsoleLogEntry::Normal: dglSetBitmapModulation(mProfile->mFontColor); break; case ConsoleLogEntry::Warning: dglSetBitmapModulation(mProfile->mFontColorHL); break; case ConsoleLogEntry::Error: dglSetBitmapModulation(mProfile->mFontColorNA); break; case ConsoleLogEntry::NUM_CLASS: Con::errorf("Unhandled case in GuiConsole::onRenderCell, NUM_CLASS"); } dglDrawText(mFont, Point2I(offset.x + 3, offset.y), entry.mString, mProfile->mFontColors); Con::unlockLog(); }
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 01482C move.w (A1)+, D6 01482E subq.w #1, D6 [base+6000, base+6080, base+6100, base+6180, base+6200, base+6280, base+6300, base+6380, base+6400, base+6480, base+6500, base+6580] 07EA7C move.w #$6, (A1)+ [base+607E, base+60FE, base+617E, base+61FE, base+627E, base+62FE, base+637E, base+63FE, base+647E, base+64FE] 07EA80 moveq #$5, D4 [base+6000, base+6080, base+6100, base+6180, base+6200, base+6280, base+6300, base+6380, base+6400, base+6480, base+6500] 0AAACA move.l (A0), D2 0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAACE move.w D0, ($2,A0) 0AAAD2 cmp.l (A0), D0 0AAAD4 bne $aaafc 0AAAD8 move.l D2, (A0)+ 0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAE6 move.l (A0), D2 0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAF4 move.l D2, (A0)+ 0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] copyright zengfr site:http://github.com/zengfr/romhack
; void *w_array_pop_back(w_array_t *a) SECTION code_clib SECTION code_adt_w_array PUBLIC w_array_pop_back EXTERN asm_w_array_pop_back defc w_array_pop_back = asm_w_array_pop_back ; SDCC bridge for Classic IF __CLASSIC PUBLIC _w_array_pop_back defc _w_array_pop_back = w_array_pop_back ENDIF
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r14 push %r15 push %rbp push %rcx push %rdi push %rsi lea addresses_UC_ht+0xf2f6, %rsi lea addresses_A_ht+0x1c44a, %rdi nop nop nop add $59997, %r12 mov $28, %rcx rep movsb nop nop nop nop dec %r14 lea addresses_normal_ht+0x1e5ca, %rsi nop nop nop nop add %r15, %r15 mov (%rsi), %r14w nop cmp %rcx, %rcx lea addresses_WT_ht+0x688a, %rsi lea addresses_D_ht+0x30ca, %rdi nop nop inc %r11 mov $127, %rcx rep movsq nop nop nop nop nop xor %r11, %r11 lea addresses_WT_ht+0x144aa, %r12 nop inc %r14 mov $0x6162636465666768, %rcx movq %rcx, (%r12) nop nop sub $60083, %r11 lea addresses_UC_ht+0x13b1e, %r15 cmp %rdi, %rdi movl $0x61626364, (%r15) nop nop cmp %r11, %r11 lea addresses_normal_ht+0x11dca, %rsi lea addresses_UC_ht+0x12d0a, %rdi nop nop nop nop and $30352, %rbp mov $12, %rcx rep movsb nop and $45861, %r15 lea addresses_WT_ht+0x15222, %rsi lea addresses_D_ht+0x370a, %rdi nop nop nop nop nop cmp %rbp, %rbp mov $78, %rcx rep movsb nop nop nop nop xor %r12, %r12 lea addresses_UC_ht+0x978a, %r14 nop nop sub %rcx, %rcx movb (%r14), %r11b nop nop nop nop inc %r14 lea addresses_D_ht+0x1145a, %r12 and $36455, %r14 mov (%r12), %edi sub $35589, %r11 lea addresses_WC_ht+0x30c2, %r11 nop nop cmp %rdi, %rdi mov (%r11), %r15 nop nop nop nop dec %r12 pop %rsi pop %rdi pop %rcx pop %rbp pop %r15 pop %r14 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %rax push %rbx push %rcx push %rdx push %rsi // Store lea addresses_PSE+0xbdfa, %rdx clflush (%rdx) nop and %rsi, %rsi mov $0x5152535455565758, %rbx movq %rbx, %xmm0 movups %xmm0, (%rdx) nop dec %rcx // Store lea addresses_D+0xb952, %rcx nop nop dec %rdx movl $0x51525354, (%rcx) inc %rsi // Load mov $0x151cbf00000005ca, %r14 nop nop nop nop cmp %r10, %r10 movups (%r14), %xmm6 vpextrq $0, %xmm6, %rsi xor %r10, %r10 // Faulty Load lea addresses_A+0xcdca, %r10 cmp %rax, %rax mov (%r10), %r14d lea oracles, %rdx and $0xff, %r14 shlq $12, %r14 mov (%rdx,%r14,1), %r14 pop %rsi pop %rdx pop %rcx pop %rbx pop %rax pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 16}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_D', 'AVXalign': False, 'size': 4}} {'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_NC', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_A', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4}} {'src': {'same': False, 'congruent': 8, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}} {'src': {'same': True, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}} {'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; uchar tshr_saddr2cy(void *saddr) SECTION code_clib SECTION code_arch PUBLIC _tshr_saddr2cy_fastcall EXTERN _zx_saddr2cy_fastcall defc _tshr_saddr2cy_fastcall = _zx_saddr2cy_fastcall
%include "include/u7bg-all-includes.asm" %include "../u7-common/patch-eop-determineItemBulk.asm"
; A145813: 1/2 the number of islands of ones fitting in an n X n array symmetric about main diagonal with all ones connected only either three adjacent vertically or three adjacent horizontally. ; 0,0,0,1,2,2,3,4,6,7,8,10,12,14,16,19,21,24,27,30 mov $2,$0 pow $0,2 add $0,1 mul $0,2 sub $0,1 add $2,13 add $0,$2 add $0,25 mov $3,25 lpb $0,1 mov $1,$0 mov $0,1 div $1,$3 sub $1,1 lpe
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "td/telegram/SponsoredMessageManager.h" #include "td/telegram/ChannelId.h" #include "td/telegram/ConfigShared.h" #include "td/telegram/ContactsManager.h" #include "td/telegram/Global.h" #include "td/telegram/MessageContent.h" #include "td/telegram/MessageEntity.h" #include "td/telegram/MessagesManager.h" #include "td/telegram/net/NetQueryCreator.h" #include "td/telegram/ServerMessageId.h" #include "td/telegram/Td.h" #include "td/telegram/telegram_api.h" #include "td/utils/algorithm.h" #include "td/utils/buffer.h" #include "td/utils/logging.h" #include "td/utils/SliceBuilder.h" #include "td/utils/Status.h" #include <limits> namespace td { class GetSponsoredMessagesQuery final : public Td::ResultHandler { Promise<telegram_api::object_ptr<telegram_api::messages_sponsoredMessages>> promise_; ChannelId channel_id_; public: explicit GetSponsoredMessagesQuery( Promise<telegram_api::object_ptr<telegram_api::messages_sponsoredMessages>> &&promise) : promise_(std::move(promise)) { } void send(ChannelId channel_id) { channel_id_ = channel_id; auto input_channel = td_->contacts_manager_->get_input_channel(channel_id); if (input_channel == nullptr) { return promise_.set_error(Status::Error(400, "Chat info not found")); } send_query(G()->net_query_creator().create(telegram_api::channels_getSponsoredMessages(std::move(input_channel)))); } void on_result(BufferSlice packet) final { auto result_ptr = fetch_result<telegram_api::channels_getSponsoredMessages>(packet); if (result_ptr.is_error()) { return on_error(result_ptr.move_as_error()); } promise_.set_value(result_ptr.move_as_ok()); } void on_error(Status status) final { td_->contacts_manager_->on_get_channel_error(channel_id_, status, "GetSponsoredMessagesQuery"); promise_.set_error(std::move(status)); } }; class ViewSponsoredMessageQuery final : public Td::ResultHandler { Promise<Unit> promise_; ChannelId channel_id_; public: explicit ViewSponsoredMessageQuery(Promise<Unit> &&promise) : promise_(std::move(promise)) { } void send(ChannelId channel_id, const string &message_id) { channel_id_ = channel_id; auto input_channel = td_->contacts_manager_->get_input_channel(channel_id); if (input_channel == nullptr) { return promise_.set_error(Status::Error(400, "Chat info not found")); } send_query(G()->net_query_creator().create( telegram_api::channels_viewSponsoredMessage(std::move(input_channel), BufferSlice(message_id)))); } void on_result(BufferSlice packet) final { auto result_ptr = fetch_result<telegram_api::channels_viewSponsoredMessage>(packet); if (result_ptr.is_error()) { return on_error(result_ptr.move_as_error()); } promise_.set_value(Unit()); } void on_error(Status status) final { td_->contacts_manager_->on_get_channel_error(channel_id_, status, "ViewSponsoredMessageQuery"); promise_.set_error(std::move(status)); } }; struct SponsoredMessageManager::SponsoredMessage { int32 local_id = 0; DialogId sponsor_dialog_id; ServerMessageId server_message_id; string start_param; unique_ptr<MessageContent> content; SponsoredMessage() = default; SponsoredMessage(int32 local_id, DialogId sponsor_dialog_id, ServerMessageId server_message_id, string start_param, unique_ptr<MessageContent> content) : local_id(local_id) , sponsor_dialog_id(sponsor_dialog_id) , server_message_id(server_message_id) , start_param(std::move(start_param)) , content(std::move(content)) { } }; struct SponsoredMessageManager::DialogSponsoredMessages { vector<Promise<td_api::object_ptr<td_api::sponsoredMessages>>> promises; vector<SponsoredMessage> messages; std::unordered_map<int32, string> message_random_ids; }; SponsoredMessageManager::SponsoredMessageManager(Td *td, ActorShared<> parent) : td_(td), parent_(std::move(parent)) { delete_cached_sponsored_messages_timeout_.set_callback(on_delete_cached_sponsored_messages_timeout_callback); delete_cached_sponsored_messages_timeout_.set_callback_data(static_cast<void *>(this)); } SponsoredMessageManager::~SponsoredMessageManager() = default; void SponsoredMessageManager::tear_down() { parent_.reset(); } void SponsoredMessageManager::on_delete_cached_sponsored_messages_timeout_callback(void *sponsored_message_manager_ptr, int64 dialog_id_int) { if (G()->close_flag()) { return; } auto sponsored_message_manager = static_cast<SponsoredMessageManager *>(sponsored_message_manager_ptr); send_closure_later(sponsored_message_manager->actor_id(sponsored_message_manager), &SponsoredMessageManager::delete_cached_sponsored_messages, DialogId(dialog_id_int)); } void SponsoredMessageManager::delete_cached_sponsored_messages(DialogId dialog_id) { if (G()->close_flag()) { return; } auto it = dialog_sponsored_messages_.find(dialog_id); CHECK(it != dialog_sponsored_messages_.end()); CHECK(it->second->promises.empty()); dialog_sponsored_messages_.erase(it); } td_api::object_ptr<td_api::sponsoredMessage> SponsoredMessageManager::get_sponsored_message_object( DialogId dialog_id, const SponsoredMessage &sponsored_message) const { td_api::object_ptr<td_api::InternalLinkType> link; switch (sponsored_message.sponsor_dialog_id.get_type()) { case DialogType::User: { auto user_id = sponsored_message.sponsor_dialog_id.get_user_id(); if (!td_->contacts_manager_->is_user_bot(user_id)) { break; } auto bot_username = td_->contacts_manager_->get_user_username(user_id); if (bot_username.empty()) { break; } link = td_api::make_object<td_api::internalLinkTypeBotStart>(bot_username, sponsored_message.start_param); break; } case DialogType::Channel: { auto channel_id = sponsored_message.sponsor_dialog_id.get_channel_id(); auto t_me = G()->shared_config().get_option_string("t_me_url", "https://t.me/"); link = td_api::make_object<td_api::internalLinkTypeMessage>( PSTRING() << t_me << "/c" << channel_id.get() << '/' << sponsored_message.server_message_id.get()); break; } default: break; } return td_api::make_object<td_api::sponsoredMessage>( sponsored_message.local_id, sponsored_message.sponsor_dialog_id.get(), std::move(link), get_message_content_object(sponsored_message.content.get(), td_, dialog_id, 0, false, true, -1)); } td_api::object_ptr<td_api::sponsoredMessages> SponsoredMessageManager::get_sponsored_messages_object( DialogId dialog_id, const DialogSponsoredMessages &sponsored_messages) const { return td_api::make_object<td_api::sponsoredMessages>( transform(sponsored_messages.messages, [this, dialog_id](const SponsoredMessage &sponsored_message) { return get_sponsored_message_object(dialog_id, sponsored_message); })); } void SponsoredMessageManager::get_dialog_sponsored_messages( DialogId dialog_id, Promise<td_api::object_ptr<td_api::sponsoredMessages>> &&promise) { if (!td_->messages_manager_->have_dialog_force(dialog_id, "get_sponsored_messages")) { return promise.set_error(Status::Error(400, "Chat not found")); } if (dialog_id.get_type() != DialogType::Channel || td_->contacts_manager_->get_channel_type(dialog_id.get_channel_id()) != ContactsManager::ChannelType::Broadcast) { return promise.set_value(td_api::make_object<td_api::sponsoredMessages>()); } auto &messages = dialog_sponsored_messages_[dialog_id]; if (messages != nullptr && messages->promises.empty()) { return promise.set_value(get_sponsored_messages_object(dialog_id, *messages)); } if (messages == nullptr) { messages = make_unique<DialogSponsoredMessages>(); } messages->promises.push_back(std::move(promise)); if (messages->promises.size() == 1) { auto query_promise = PromiseCreator::lambda( [actor_id = actor_id(this), dialog_id](Result<telegram_api::object_ptr<telegram_api::messages_sponsoredMessages>> &&result) mutable { send_closure(actor_id, &SponsoredMessageManager::on_get_dialog_sponsored_messages, dialog_id, std::move(result)); }); td_->create_handler<GetSponsoredMessagesQuery>(std::move(query_promise))->send(dialog_id.get_channel_id()); } } void SponsoredMessageManager::on_get_dialog_sponsored_messages( DialogId dialog_id, Result<telegram_api::object_ptr<telegram_api::messages_sponsoredMessages>> &&result) { auto &messages = dialog_sponsored_messages_[dialog_id]; CHECK(messages != nullptr); auto promises = std::move(messages->promises); reset_to_empty(messages->promises); CHECK(messages->messages.empty()); CHECK(messages->message_random_ids.empty()); if (result.is_ok() && G()->close_flag()) { result = Global::request_aborted_error(); } if (result.is_error()) { dialog_sponsored_messages_.erase(dialog_id); for (auto &promise : promises) { promise.set_error(result.error().clone()); } return; } auto sponsored_messages = result.move_as_ok(); td_->contacts_manager_->on_get_users(std::move(sponsored_messages->users_), "on_get_dialog_sponsored_messages"); td_->contacts_manager_->on_get_chats(std::move(sponsored_messages->chats_), "on_get_dialog_sponsored_messages"); for (auto &sponsored_message : sponsored_messages->messages_) { DialogId sponsor_dialog_id(sponsored_message->from_id_); if (!sponsor_dialog_id.is_valid() || !td_->messages_manager_->have_dialog_info_force(sponsor_dialog_id)) { LOG(ERROR) << "Receive unknown sponsor " << sponsor_dialog_id; continue; } auto server_message_id = ServerMessageId(sponsored_message->channel_post_); if (!server_message_id.is_valid() && server_message_id != ServerMessageId()) { LOG(ERROR) << "Receive invalid channel post in " << to_string(sponsored_message); server_message_id = ServerMessageId(); } td_->messages_manager_->force_create_dialog(sponsor_dialog_id, "on_get_dialog_sponsored_messages"); auto message_text = get_message_text(td_->contacts_manager_.get(), std::move(sponsored_message->message_), std::move(sponsored_message->entities_), true, true, 0, false, "on_get_dialog_sponsored_messages"); int32 ttl = 0; bool disable_web_page_preview = false; auto content = get_message_content(td_, std::move(message_text), nullptr, sponsor_dialog_id, true, UserId(), &ttl, &disable_web_page_preview); if (ttl != 0) { LOG(ERROR) << "Receive sponsored message with TTL " << ttl; continue; } CHECK(disable_web_page_preview); CHECK(current_sponsored_message_id_ < std::numeric_limits<int32>::max()); auto local_id = ++current_sponsored_message_id_; messages->message_random_ids[local_id] = sponsored_message->random_id_.as_slice().str(); messages->messages.emplace_back(local_id, sponsor_dialog_id, server_message_id, std::move(sponsored_message->start_param_), std::move(content)); } for (auto &promise : promises) { promise.set_value(get_sponsored_messages_object(dialog_id, *messages)); } delete_cached_sponsored_messages_timeout_.set_timeout_in(dialog_id.get(), 300.0); } void SponsoredMessageManager::view_sponsored_message(DialogId dialog_id, int32 sponsored_message_id, Promise<Unit> &&promise) { if (!td_->messages_manager_->have_dialog_force(dialog_id, "view_sponsored_message")) { return promise.set_error(Status::Error(400, "Chat not found")); } auto it = dialog_sponsored_messages_.find(dialog_id); if (it == dialog_sponsored_messages_.end()) { return promise.set_value(Unit()); } auto random_id_it = it->second->message_random_ids.find(sponsored_message_id); if (random_id_it == it->second->message_random_ids.end()) { return promise.set_value(Unit()); } auto random_id = std::move(random_id_it->second); it->second->message_random_ids.erase(random_id_it); td_->create_handler<ViewSponsoredMessageQuery>(std::move(promise))->send(dialog_id.get_channel_id(), random_id); } } // namespace td
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %r14 push %r9 push %rcx push %rdi push %rsi lea addresses_normal_ht+0x424f, %r9 nop nop cmp $22087, %rdi mov (%r9), %r14d nop nop add %rsi, %rsi lea addresses_D_ht+0x750f, %r10 nop nop nop sub %r13, %r13 movups (%r10), %xmm2 vpextrq $1, %xmm2, %r12 nop nop inc %r9 lea addresses_UC_ht+0x1bd0f, %r12 nop nop xor %rsi, %rsi movups (%r12), %xmm1 vpextrq $1, %xmm1, %r10 nop nop nop nop nop cmp %r13, %r13 lea addresses_UC_ht+0xff8f, %r12 nop cmp $22988, %r10 mov (%r12), %di nop nop nop nop nop dec %r10 lea addresses_WC_ht+0x360f, %rsi clflush (%rsi) nop nop nop nop nop sub %r14, %r14 mov $0x6162636465666768, %r9 movq %r9, %xmm6 and $0xffffffffffffffc0, %rsi vmovaps %ymm6, (%rsi) nop nop nop nop cmp %r9, %r9 lea addresses_WC_ht+0x7cf, %r12 nop dec %rsi mov $0x6162636465666768, %r13 movq %r13, %xmm4 movups %xmm4, (%r12) nop nop nop cmp %r14, %r14 lea addresses_normal_ht+0x19d0f, %rdi nop nop add %r14, %r14 movl $0x61626364, (%rdi) and %rdi, %rdi lea addresses_UC_ht+0x1a08f, %r12 nop xor %r14, %r14 mov $0x6162636465666768, %r13 movq %r13, (%r12) nop nop nop nop add $179, %rsi lea addresses_A_ht+0x12e9a, %rsi lea addresses_WC_ht+0xf90f, %rdi nop nop nop nop and $18969, %r9 mov $96, %rcx rep movsq cmp %r10, %r10 lea addresses_A_ht+0xc083, %rsi lea addresses_A_ht+0x1730f, %rdi clflush (%rsi) nop nop nop dec %r14 mov $62, %rcx rep movsw nop nop nop nop nop xor %r10, %r10 lea addresses_UC_ht+0x1410f, %r13 nop cmp $19064, %r12 mov (%r13), %r9d nop inc %r14 lea addresses_normal_ht+0xca0f, %rcx nop nop nop nop sub $31804, %r12 mov $0x6162636465666768, %r13 movq %r13, (%rcx) nop inc %r10 lea addresses_UC_ht+0x986b, %rdi and $32055, %r9 movw $0x6162, (%rdi) nop nop nop sub $25380, %r14 lea addresses_normal_ht+0x1950f, %rsi lea addresses_UC_ht+0x7d0f, %rdi clflush (%rsi) nop nop and $8749, %r13 mov $37, %rcx rep movsw nop nop sub %r10, %r10 pop %rsi pop %rdi pop %rcx pop %r9 pop %r14 pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %rax push %rbp push %rdi push %rsi // Store lea addresses_PSE+0x1b15f, %rdi nop nop nop nop sub $22666, %rbp mov $0x5152535455565758, %rax movq %rax, (%rdi) nop nop nop nop sub $3948, %rdi // Faulty Load lea addresses_RW+0xcd0f, %rdi nop nop nop nop nop inc %r14 mov (%rdi), %r10w lea oracles, %rbp and $0xff, %r10 shlq $12, %r10 mov (%rbp,%r10,1), %r10 pop %rsi pop %rdi pop %rbp pop %rax pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_PSE', 'size': 8, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 2, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 5, 'NT': True, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': True}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': True}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': True}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 11, 'NT': True, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}} {'src': {'same': False, 'congruent': 10, 'NT': True, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False}} {'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
; A064429: a(n) = floor(n / 3) * 3 + sign(n mod 3) * (3 - n mod 3). ; 0,2,1,3,5,4,6,8,7,9,11,10,12,14,13,15,17,16,18,20,19,21,23,22,24,26,25,27,29,28,30,32,31,33,35,34,36,38,37,39,41,40,42,44,43,45,47,46,48,50,49,51,53,52,54,56,55,57,59,58,60,62,61,63,65,64,66,68,67,69,71,70,72,74,73,75,77,76,78,80,79,81,83,82,84,86,85,87,89,88,90,92,91,93,95,94,96,98,97,99,101,100,102,104,103,105,107,106,108,110,109,111,113,112,114,116,115,117,119,118,120,122,121,123,125,124,126,128,127,129,131,130,132,134,133,135,137,136,138,140,139,141,143,142,144,146,145,147,149,148,150,152,151,153,155,154,156,158,157,159,161,160,162,164,163,165,167,166,168,170,169,171,173,172,174,176,175,177,179,178,180,182,181,183,185,184,186,188,187,189,191,190,192,194,193,195,197,196,198,200,199,201,203,202,204,206,205,207,209,208,210,212,211,213,215,214,216,218,217,219,221,220,222,224,223,225,227,226,228,230,229,231,233,232,234,236,235,237,239,238,240,242,241,243,245,244,246,248,247,249 add $0,16 mov $1,$0 mod $0,3 add $1,$0 sub $1,17
; long __lmod_callee (long left, long right) SECTION code_clib SECTION code_fp_am9511 PUBLIC cam32_sccz80_lmod_callee EXTERN asm_am9511_lmod_callee ; modulus of sccz80 long by sccz80 long ; ; enter : stack = sccz80_long left, ret ; DEHL = sccz80_long right ; ; exit : DEHL = sccz80_long(left/right) ; ; uses : af, bc, de, hl, af', bc', de', hl' defc cam32_sccz80_lmod_callee = asm_am9511_lmod_callee ; enter stack = sccz80_long left, ret ; DEHL = sccz80_long right ; return DEHL = sccz80_long
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; FxSave.Asm ; ; Abstract: ; ; AsmFxSave function ; ; Notes: ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; InternalX86FxSave ( ; OUT IA32_FX_BUFFER *Buffer ; ); ;------------------------------------------------------------------------------ global ASM_PFX(InternalX86FxSave) ASM_PFX(InternalX86FxSave): mov eax, [esp + 4] ; Buffer must be 16-byte aligned fxsave [eax] ret
; A005971: Sum of cubes of Lucas numbers. ; 1,28,92,435,1766,7598,31987,135810,574786,2435653,10316252,43702500,185123261,784200368,3321916912,14071880655,59609419066,252509590018,1069647725567,4531100578950,19194049901126,81307300410353,344423251175392,1459000305705960,6180424473038041 mov $16,$0 mov $18,$0 add $18,1 lpb $18 clr $0,16 mov $0,$16 sub $18,1 sub $0,$18 mov $13,$0 mov $15,$0 add $15,1 lpb $15 mov $0,$13 sub $15,1 sub $0,$15 mov $9,$0 mov $11,2 lpb $11 mov $0,$9 sub $11,1 add $0,$11 sub $0,1 add $3,1 mov $4,2 mov $6,1 trn $6,$0 mul $6,$0 add $6,1 mov $7,1 lpb $0 trn $0,1 add $4,$6 add $7,$3 mov $3,1 mov $6,$7 mov $7,$4 lpe pow $6,3 mov $1,$6 mul $1,36 mov $12,$11 lpb $12 mov $10,$1 sub $12,1 lpe lpe lpb $9 mov $9,0 sub $10,$1 lpe mov $1,$10 sub $1,36 div $1,36 add $1,1 add $14,$1 lpe add $17,$14 lpe mov $1,$17
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1994 -- All Rights Reserved PROJECT: Clavin MODULE: UI FILE: uiC.asm AUTHOR: Chung Liu, Nov 23, 1994 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- CL 11/23/94 Initial revision DESCRIPTION: C Interface $Id: uiC.asm,v 1.1 97/04/05 01:19:04 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SetGeosConvention C_Mailbox segment resource COMMENT @---------------------------------------------------------------------- C FUNCTION: MailboxConvertToMailboxTransferItem C DECLARATION: void (VMFileHandle clipboardFile, VMBlockHandle clipboardBlock, VMFileHandle vmFile, word userID, MemHandle nameLMemBlock, ChunkHandle nameChunk, VMBlockHandle *transferItemBlock); KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- CHL 11/94 Initial version ------------------------------------------------------------------------------@ MAILBOXCONVERTTOMAILBOXTRANSFERITEM proc far clipbrdFile:hptr, clipbrdBlk:word, vmFile:hptr, userID:word, nameBlk:hptr, nameChunk:lptr, transferBlock:fptr uses ds, si .enter mov si, nameChunk tst si jz dontSetDS mov bx, nameBlk call MemLock mov ds, ax dontSetDS: mov bx, clipbrdFile mov cx, clipbrdBlk mov dx, vmFile mov ax, userID call MailboxConvertToMailboxTransferItem lds si, transferBlock mov ds:[si], ax tst nameChunk jz exit mov bx, nameBlk call MemUnlock exit: .leave ret MAILBOXCONVERTTOMAILBOXTRANSFERITEM endp COMMENT @---------------------------------------------------------------------- C FUNCTION: MailboxConvertToClipboardTransferItem C DECLARATION: void (VMFileHandle mailboxFile, VMBlockHandle mailboxBlock, VMFileHandle vmFile, word userID, transferBlock *VMBlockHandle) KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- CHL 11/94 Initial version ------------------------------------------------------------------------------@ MAILBOXCONVERTTOCLIPBOARDTRANSFERITEM proc far mboxFile:hptr, mboxBlk:word, vmFile:hptr, userID:word, transferBlock:fptr uses ds, si .enter mov bx, mboxFile mov cx, mboxBlk mov dx, vmFile mov ax, userID call MailboxConvertToClipboardTransferItem lds si, transferBlock mov ds:[si], ax .leave ret MAILBOXCONVERTTOCLIPBOARDTRANSFERITEM endp C_Mailbox ends SetDefaultConvention
// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #include "cl_common.hpp" #include "platform/context.hpp" #include "device/device.hpp" #include "platform/runtime.hpp" #include "platform/agent.hpp" #ifdef _WIN32 #include <d3d10_1.h> #include "CL/cl_d3d10.h" #include "CL/cl_d3d11.h" #include "cl_d3d9_amd.hpp" #include "cl_d3d10_amd.hpp" #include "cl_d3d11_amd.hpp" #endif // _WIN32 #include "cl_kernel_info_amd.h" #include "cl_profile_amd.h" #include "cl_platform_amd.h" #include "cl_sdi_amd.h" #include "cl_thread_trace_amd.h" #include "cl_debugger_amd.h" #include "cl_lqdflash_amd.h" #include "cl_p2p_amd.h" #include <GL/gl.h> #include <GL/glext.h> #include "CL/cl_gl.h" /*! \addtogroup API * @{ * * \addtogroup CL_Contexts * @{ */ /*! \brief Create an OpenCL context. * * An OpenCL context is created with one or more devices. Contexts are used by * the OpenCL runtime for managing objects such as command-queues, memory, * program and kernel objects and for executing kernels on one or more devices * specified in the context. * * \param properties is reserved and must be zero. * * \param num_devices is the number of devices specified in the \a devices * argument. * * \param devices is a pointer to a list of unique devices returned by * clGetDevices. If more than one device is specified in devices, * a selection criteria may be applied to determine if the list of devices * specified can be used together to create a context. * * \param pfn_notify is a callback function that can be registered by the * application. This callback function will be used by the runtime to report * information on errors that occur in this context. This callback function * may be called asynchronously by the runtime. If \a pfn_notify is NULL, * no callback function is registered. * * \param user_data will be passed as the user_data argument when \a pfn_notify * is called. \a user_data can be NULL. * * \param errcode_ret will return an appropriate error code. If \a errcode_ret * is NULL, no error code is returned. * * \return A valid non-zero context and errcode_ret is set to CL_SUCCESS * if the context is created successfully or NULL with the following * error values stored in \a errcode_ret: * - CL_INVALID_VALUE if \a properties is not zero. * - CL_INVALID_VALUE if \a devices is NULL. * - CL_INVALID_VALUE if \a num_devices is equal to zero. * - CL_INVALID_DEVICE if \a devices contains an invalid device. * - CL_INVALID_DEVICE_LIST if more than one device is specified in * \a devices and the list of devices specified cannot be used together * to create a context. * - CL_DEVICE_NOT_AVAILABLE if a device in \a devices is currently not * available even though the device was returned by clGetDevices. * - CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources * required by the runtime. * * \version 1.0r33 */ RUNTIME_ENTRY_RET(cl_context, clCreateContext, (const cl_context_properties* properties, cl_uint num_devices, const cl_device_id* devices, void(CL_CALLBACK* pfn_notify)(const char*, const void*, size_t, void*), void* user_data, cl_int* errcode_ret)) { cl_int errcode; amd::Context::Info info; errcode = amd::Context::checkProperties(properties, &info); if (CL_SUCCESS != errcode) { *not_null(errcode_ret) = errcode; return (cl_context)0; } if (num_devices == 0 || devices == NULL) { *not_null(errcode_ret) = CL_INVALID_VALUE; return (cl_context)0; } std::vector<amd::Device*> devices_; for (cl_uint i = 0; i < num_devices; ++i) { // FIXME_lmoriche: Set errcode_ret to CL_DEVICE_NOT_AVAILABLE if a // device in devices is no longer available. cl_device_id device = devices[i]; if (!is_valid(device)) { *not_null(errcode_ret) = CL_INVALID_DEVICE; return (cl_context)0; } devices_.push_back(as_amd(device)); } amd::Context* context = new amd::Context(devices_, info); if (context == NULL) { *not_null(errcode_ret) = CL_OUT_OF_HOST_MEMORY; return (cl_context)0; } if (CL_SUCCESS != (errcode = context->create(properties))) { context->release(); *not_null(errcode_ret) = errcode; return (cl_context)0; } if (amd::Agent::shouldPostContextEvents()) { amd::Agent::postContextCreate(as_cl(context)); } *not_null(errcode_ret) = CL_SUCCESS; return as_cl(context); } RUNTIME_EXIT /*! \brief Create an OpenCL context from a device type that identifies the * specific device(s) to use. * * \param properties is reserved and must be zero. * * \param device_type is a bit-field that identifies the type of device. * * \param pfn_notify described in clCreateContext. * * \param user_data described in clCreateContext. * * \param errcode_ret will return an appropriate error code. If \a errcode_ret * is NULL, no error code is returned. * * \return A valid non-zero context and errcode_ret is set to CL_SUCCESS * if the context is created successfully or NULL with the following error * values stored in errcode_ret: * - CL_INVALID_VALUE if \a properties is not zero. * - CL_INVALID_DEVICE_TYPE if \a device_type is not a valid value. * - CL_DEVICE_NOT_AVAILABLE if no devices that match \a device_type * are currently available. * - CL_DEVICE_NOT_FOUND if no devices that match \a device_type were found. * - CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources * required by the runtime. * * \version 1.0r33 */ RUNTIME_ENTRY_RET(cl_context, clCreateContextFromType, (const cl_context_properties* properties, cl_device_type device_type, void(CL_CALLBACK* pfn_notify)(const char*, const void*, size_t, void*), void* user_data, cl_int* errcode_ret)) { amd::Context::Info info; cl_int errcode = amd::Context::checkProperties(properties, &info); if (errcode != CL_SUCCESS) { *not_null(errcode_ret) = errcode; return (cl_context)0; } // Get the devices of the given type. cl_uint num_devices; bool offlineDevices = (info.flags_ & amd::Context::OfflineDevices) ? true : false; if (!amd::Device::getDeviceIDs(device_type, 0, NULL, &num_devices, offlineDevices)) { *not_null(errcode_ret) = CL_DEVICE_NOT_FOUND; return (cl_context)0; } assert(num_devices > 0 && "Should have returned an error!"); cl_device_id* devices = (cl_device_id*)alloca(num_devices * sizeof(cl_device_id)); if (!amd::Device::getDeviceIDs(device_type, num_devices, devices, NULL, offlineDevices)) { *not_null(errcode_ret) = CL_DEVICE_NOT_FOUND; return (cl_context)0; } // Create a new context with the devices cl_context context = clCreateContext(properties, num_devices, devices, pfn_notify, user_data, errcode_ret); return context; } RUNTIME_EXIT /*! \brief Increment the context reference count. * * \return One of the following values: * - CL_INVALID_CONTEXT if context is not a valid OpenCL context. * - CL_SUCCESS if the function is executed successfully. * * clCreateContext and clCreateContextFromType perform an implicit retain. * This is very helpful for 3rd party libraries, which typically get a context * passed to them by the application. * However, it is possible that the application may delete the context without * informing the library. Allowing functions to attach to (i.e. retain) and * release a context solves the problem of a context being used by a library * no longer being valid. * * \version 1.0r33 */ RUNTIME_ENTRY(cl_int, clRetainContext, (cl_context context)) { if (!is_valid(context)) { return CL_INVALID_CONTEXT; } as_amd(context)->retain(); return CL_SUCCESS; } RUNTIME_EXIT /*! \brief Decrement the context reference count. * * \return One of the following values: * - CL_INVALID_CONTEXT if context is not a valid OpenCL context. * - CL_SUCCESS if the function is executed successfully. * * After the context reference count becomes zero and all the objects attached * to context (such as memory objects, command-queues) are released, * the context is deleted. * * \version 1.0r33 */ RUNTIME_ENTRY(cl_int, clReleaseContext, (cl_context context)) { if (!is_valid(context)) { return CL_INVALID_CONTEXT; } as_amd(context)->release(); return CL_SUCCESS; } RUNTIME_EXIT /*! \brief Query information about a context. * * \param context specifies the OpenCL context being queried. * * \param param_name is an enum that specifies the information to query. * * \param param_value is a pointer to memory where the appropriate result being * queried is returned. If \a param_value is NULL, it is ignored. * * \param param_value_size specifies the size in bytes of memory pointed to by * \a param_value. This size must be greater than or equal to the size of * return type. * * \param param_value_size_ret returns the actual size in bytes of data being * queried by \a param_value. If \a param_value_size_ret is NULL, * it is ignored. * * \return One of the following values: * - CL_INVALID_CONTEXT if context is not a valid context. * - CL_INVALID_VALUE if \a param_name is not one of the supported values * or if size in bytes specified by \a param_value_size is < size of return * type and \a param_value is not a NULL value. * - CL_SUCCESS if the function is executed successfully. * * \version 1.0r33 */ RUNTIME_ENTRY(cl_int, clGetContextInfo, (cl_context context, cl_context_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret)) { if (!is_valid(context)) { return CL_INVALID_CONTEXT; } switch (param_name) { case CL_CONTEXT_REFERENCE_COUNT: { cl_uint count = as_amd(context)->referenceCount(); return amd::clGetInfo(count, param_value_size, param_value, param_value_size_ret); } case CL_CONTEXT_NUM_DEVICES: { cl_uint numDevices = (cl_uint)as_amd(context)->devices().size(); return amd::clGetInfo(numDevices, param_value_size, param_value, param_value_size_ret); } case CL_CONTEXT_DEVICES: { const std::vector<amd::Device*>& devices = as_amd(context)->devices(); size_t numDevices = devices.size(); size_t valueSize = numDevices * sizeof(cl_device_id*); if (param_value != NULL && param_value_size < valueSize) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = valueSize; if (param_value != NULL) { cl_device_id* device_list = (cl_device_id*)param_value; std::vector<amd::Device*>::const_iterator it; for (it = devices.begin(); it != devices.end(); ++it) { *device_list++ = const_cast<cl_device_id>(as_cl(*it)); } } return CL_SUCCESS; } case CL_CONTEXT_PROPERTIES: { const amd::Context* amdContext = as_amd(context); size_t valueSize = amdContext->info().propertiesSize_; if (param_value != NULL && param_value_size < valueSize) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = valueSize; if ((param_value != NULL) && (valueSize != 0)) { ::memcpy(param_value, amdContext->properties(), valueSize); } return CL_SUCCESS; } #ifdef _WIN32 case CL_CONTEXT_D3D10_DEVICE_KHR: { // Not defined in the ext.spec, but tested in the conf.test // Guessing functionality from the test... if (param_value != NULL && param_value_size < sizeof(void*)) { return CL_INVALID_VALUE; } const amd::Context* amdContext = as_amd(context); if (!(amdContext->info().flags_ & amd::Context::D3D10DeviceKhr)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(intptr_t); if (param_value != NULL) { *(intptr_t*)param_value = reinterpret_cast<intptr_t>(amdContext->info().hDev_[amd::Context::D3D10DeviceKhrIdx]); } return CL_SUCCESS; } case CL_CONTEXT_D3D10_PREFER_SHARED_RESOURCES_KHR: { if (param_value != NULL && param_value_size < sizeof(cl_bool)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(cl_bool); if (param_value != NULL) { *(cl_bool*)param_value = CL_TRUE; } return CL_SUCCESS; } case CL_CONTEXT_D3D11_DEVICE_KHR: { // Not defined in the ext.spec, but tested in the conf.test // Guessing functionality from the test... if (param_value != NULL && param_value_size < sizeof(void*)) { return CL_INVALID_VALUE; } const amd::Context* amdContext = as_amd(context); if (!(amdContext->info().flags_ & amd::Context::D3D11DeviceKhr)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(intptr_t); if (param_value != NULL) { *(intptr_t*)param_value = reinterpret_cast<intptr_t>(amdContext->info().hDev_[amd::Context::D3D11DeviceKhrIdx]); } return CL_SUCCESS; } case CL_CONTEXT_D3D11_PREFER_SHARED_RESOURCES_KHR: { if (param_value != NULL && param_value_size < sizeof(cl_bool)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(cl_bool); if (param_value != NULL) { *(cl_bool*)param_value = CL_TRUE; } return CL_SUCCESS; } case CL_CONTEXT_ADAPTER_D3D9_KHR: { if (param_value != NULL && param_value_size < sizeof(void*)) { return CL_INVALID_VALUE; } const amd::Context* amdContext = as_amd(context); if (!(amdContext->info().flags_ & amd::Context::D3D9DeviceKhr)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(intptr_t); if (param_value != NULL) { *(intptr_t*)param_value = reinterpret_cast<intptr_t>(amdContext->info().hDev_[amd::Context::D3D9DeviceKhrIdx]); } return CL_SUCCESS; } case CL_CONTEXT_ADAPTER_D3D9EX_KHR: { if (param_value != NULL && param_value_size < sizeof(void*)) { return CL_INVALID_VALUE; } const amd::Context* amdContext = as_amd(context); if (!(amdContext->info().flags_ & amd::Context::D3D9DeviceEXKhr)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(intptr_t); if (param_value != NULL) { *(intptr_t*)param_value = reinterpret_cast<intptr_t>(amdContext->info().hDev_[amd::Context::D3D9DeviceEXKhrIdx]); } return CL_SUCCESS; } case CL_CONTEXT_ADAPTER_DXVA_KHR: { if (param_value != NULL && param_value_size < sizeof(void*)) { return CL_INVALID_VALUE; } const amd::Context* amdContext = as_amd(context); if (!(amdContext->info().flags_ & amd::Context::D3D9DeviceVAKhr)) { return CL_INVALID_VALUE; } *not_null(param_value_size_ret) = sizeof(intptr_t); if (param_value != NULL) { *(intptr_t*)param_value = reinterpret_cast<intptr_t>(amdContext->info().hDev_[amd::Context::D3D9DeviceVAKhrIdx]); } return CL_SUCCESS; } #endif //_WIN32 default: break; } return CL_INVALID_VALUE; } RUNTIME_EXIT /*! \brief returns the address of the extension function named by * funcname for a given platform. The pointer returned should be cast * to a function pointer type matching the extension functions definition * defined in the appropriate extension specification and header file. * A return value of NULL indicates that the specified function does not * exist for the implementation or platform is not a valid platform. * A non-NULL return value for \a clGetExtensionFunctionAddressForPlatform * does not guarantee that an extension function is actually supported by * the platform. The application must also make a corresponding query using * \a clGetPlatformInfo(platform, CL_PLATFORM_EXTENSIONS, ... ) or * \a clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, ... ) to determine if * an extension is supported by the OpenCL implementation. * * \version 1.2r07 */ CL_API_ENTRY void* CL_API_CALL clGetExtensionFunctionAddressForPlatform(cl_platform_id platform, const char* funcname) { if (platform != NULL && platform != AMD_PLATFORM) { return NULL; } return clGetExtensionFunctionAddress(funcname); } CL_API_ENTRY void* CL_API_CALL clGetExtensionFunctionAddress(const char* func_name) { #define CL_EXTENSION_ENTRYPOINT_CHECK(name) \ if (!strcmp(func_name, #name)) return reinterpret_cast<void*>(name); #define CL_EXTENSION_ENTRYPOINT_CHECK2(name1, name2) \ if (!strcmp(func_name, #name1)) return reinterpret_cast<void*>(name2); switch (func_name[2]) { case 'C': CL_EXTENSION_ENTRYPOINT_CHECK(clCreateEventFromGLsyncKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clCreatePerfCounterAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateThreadTraceAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromGLBuffer); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromGLTexture2D); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromGLTexture3D); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromGLRenderbuffer); #ifdef _WIN32 CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromD3D10BufferKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromD3D10Texture2DKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromD3D10Texture3DKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateFromDX9MediaSurfaceKHR); #endif //_WIN32 #ifdef cl_ext_device_fission CL_EXTENSION_ENTRYPOINT_CHECK(clCreateSubDevicesEXT); #endif // cl_ext_device_fission CL_EXTENSION_ENTRYPOINT_CHECK(clCreateKeyAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clConvertImageAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clCreateBufferFromImageAMD); #if cl_khr_il_program CL_EXTENSION_ENTRYPOINT_CHECK(clCreateProgramWithILKHR); #endif // cl_khr_il_program #if cl_amd_liquid_flash CL_EXTENSION_ENTRYPOINT_CHECK(clCreateSsgFileObjectAMD); #endif // cl_amd_liquid_flash break; case 'D': break; case 'E': CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueBeginPerfCounterAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueEndPerfCounterAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueAcquireGLObjects); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueReleaseGLObjects); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueBindThreadTraceBufferAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueThreadTraceCommandAMD); #ifdef _WIN32 CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueAcquireD3D10ObjectsKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueReleaseD3D10ObjectsKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueAcquireDX9MediaSurfacesKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueReleaseDX9MediaSurfacesKHR); #endif //_WIN32 CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueWaitSignalAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueWriteSignalAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueMakeBuffersResidentAMD); #if cl_amd_liquid_flash CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueReadSsgFileAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueWriteSsgFileAMD); #endif // cl_amd_liquid_flash #if cl_amd_copy_buffer_p2p CL_EXTENSION_ENTRYPOINT_CHECK(clEnqueueCopyBufferP2PAMD); #endif // cl_amd_liquid_flash break; case 'G': CL_EXTENSION_ENTRYPOINT_CHECK(clGetKernelInfoAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clGetPerfCounterInfoAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clGetGLObjectInfo); CL_EXTENSION_ENTRYPOINT_CHECK(clGetGLTextureInfo); CL_EXTENSION_ENTRYPOINT_CHECK(clGetGLContextInfoKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clGetThreadTraceInfoAMD); #ifdef _WIN32 CL_EXTENSION_ENTRYPOINT_CHECK(clGetDeviceIDsFromD3D10KHR); CL_EXTENSION_ENTRYPOINT_CHECK(clGetDeviceIDsFromDX9MediaAdapterKHR); CL_EXTENSION_ENTRYPOINT_CHECK(clGetPlaneFromImageAMD); #endif //_WIN32 CL_EXTENSION_ENTRYPOINT_CHECK(clGetKernelSubGroupInfoKHR); #if cl_amd_liquid_flash CL_EXTENSION_ENTRYPOINT_CHECK(clGetSsgFileObjectInfoAMD); #endif // cl_amd_liquid_flash break; case 'H': #ifdef _WIN32 CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgSetCallBackFunctionsAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgSetCallBackArgumentsAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgFlushCacheAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgSetExceptionPolicyAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgGetExceptionPolicyAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgSetKernelExecutionModeAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgGetKernelExecutionModeAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgCreateEventAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgWaitEventAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgDestroyEventAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgRegisterDebuggerAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgUnregisterDebuggerAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgSetAclBinaryAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgWaveControlAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgAddressWatchAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgGetAqlPacketInfoAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgGetDispatchDebugInfoAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgMapKernelCodeAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgUnmapKernelCodeAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgMapScratchRingAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgUnmapScratchRingAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgGetKernelParamMemAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgSetGlobalMemoryAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clHwDbgInstallTrapAMD); #endif //_WIN32 break; case 'I': CL_EXTENSION_ENTRYPOINT_CHECK(clIcdGetPlatformIDsKHR); break; case 'O': CL_EXTENSION_ENTRYPOINT_CHECK(clObjectGetValueForKeyAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clObjectSetValueForKeyAMD); break; case 'R': CL_EXTENSION_ENTRYPOINT_CHECK(clReleasePerfCounterAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clRetainPerfCounterAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clReleaseThreadTraceAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clRetainThreadTraceAMD); #ifdef cl_ext_device_fission CL_EXTENSION_ENTRYPOINT_CHECK(clRetainDeviceEXT); CL_EXTENSION_ENTRYPOINT_CHECK(clReleaseDeviceEXT); #endif // cl_ext_device_fission #if cl_amd_liquid_flash CL_EXTENSION_ENTRYPOINT_CHECK(clRetainSsgFileObjectAMD); CL_EXTENSION_ENTRYPOINT_CHECK(clReleaseSsgFileObjectAMD); #endif // cl_amd_liquid_flash break; case 'S': CL_EXTENSION_ENTRYPOINT_CHECK(clSetThreadTraceParamAMD); break; case 'U': CL_EXTENSION_ENTRYPOINT_CHECK(clUnloadPlatformAMD); default: break; } return NULL; } RUNTIME_ENTRY(cl_int, clTerminateContextKHR, (cl_context context)) { return CL_INVALID_CONTEXT; } RUNTIME_EXIT /*! @} * @} */
editTable: .IF SRAM_MAP=32 lda #SRAM_TABLE_BANK jsr setMMC1r1 .ENDIF ldx tableCursorY lda tableRowsIndex,x ldx editorCurrentTable clc adc editTableAddressLo,x sta tableVector lda editTableAddressHi,x adc #$00 sta tableVector+1 lda writeScreen ;need to write screen? beq @a jsr writeTableScreen ;yes dec writeScreen ;if writeScreen was 1, only write main window, else beq @a ; write header and title too jsr writeTableHeaderFooter dec writeScreen ;reset screen writing flag lda #$01 sta dmaUpdateHeader sta dmaUpdateTitle jmp editorLoop @a: jsr globalKeys ;global keys lda writeScreen ;if mode has changed, this flag will be !=0 beq @b jmp editTableExit ;if changed, don't do any more keys @b: jsr processKeys .IF SRAM_MAP=32 lda #SRAM_TABLE_BANK jsr setMMC1r1 .ENDIF ldy tableCursorX jsr tableHintSystem ldy tableCursorX jsr tableKeysTapA jsr tableKeysTapB jsr tableKeysHoldA_UDLR jsr tableKeysHoldAB_TapUDLR jsr tableKeysHoldSelect_UDLR jsr moveAroundEditor editTableExit: jsr tablePlayMarkers updateCursor tableCursorX,tableCursorY,tableCursorColumns,tableCursorRows,tableColumnCursorType jsr tableSmartTranspose jmp editorLoop tableSmartTranspose: lda PAD1_firea beq @x lda PAD1_sel beq @x lda PAD1_dlr bne @transpose lda PAD1_dud eor #$FF clc adc #$01 bne @transpose @x: rts @transpose: sta tmp4 ldy editorCurrentTable lda editTableAddressLo,y sta tmp0 lda editTableAddressHi,y sta tmp1 ldy tableCursorX cpy #TABLE_COLUMN_FX1 bcc @notCommand cpy #TABLE_COLUMN_FX2 ldy #TABLE_COLUMN_FX2_DATA bcs @fx2 ldy #TABLE_COLUMN_FX1_DATA @fx2: lda (tableVector),y sta tmp3 dey @notCommand: lda (tableVector),y sta tmp2 lda tableCursorX cmp #TABLE_COLUMN_PITCH beq @tranPitch cmp #TABLE_COLUMN_VOLUME beq @tranVol jmp @tranCom @tranVol: tay lda (tmp0),y ldx PAD1_dud beq @freeVol cmp tmp2 bne @noVol @freeVol: clc adc tmp4 bmi @noVol cmp #$10 bcs @noVol sta (tmp0),y @noVol: tya clc adc #BYTES_PER_TABLE_STEP cmp #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @tranVol ldy tableCursorX lda (tableVector),y sta editBuffer lda #$01 sta writeScreen rts @tranPitch: tay lda (tmp0),y ldx PAD1_dud beq @freePitch cmp tmp2 bne @noPitch @freePitch: clc adc tmp4 sta (tmp0),y @noPitch: tya clc adc #BYTES_PER_TABLE_STEP cmp #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @tranPitch ldy tableCursorX lda (tableVector),y sta editBuffer lda #$01 sta writeScreen rts @tranCom: cmp #TABLE_COLUMN_FX1 beq @tranCom1 cmp #TABLE_COLUMN_FX2 bne @comData @tranCom1: tay lda (tmp0),y cmp #$FF beq @noCom ldx PAD1_dud beq @freeCom cmp tmp2 bne @noCom @freeCom: clc adc tmp4 bmi @noCom cmp #COMMAND_Z bcs @noCom sta (tmp0),y @noCom: tya clc adc #BYTES_PER_TABLE_STEP cmp #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @tranCom1 ldy tableCursorX lda (tableVector),y sta editBuffer lda #$01 sta writeScreen rts @comData: tay dey tya @comData1: tay lda (tmp0),y cmp #$FF beq @noComData ldx PAD1_dud beq @freeComData cmp tmp2 bne @noComData @freeComData: iny lda (tmp0),y clc adc tmp4 sta (tmp0),y dey @noComData: tya clc adc #BYTES_PER_TABLE_STEP cmp #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @comData1 ldy tableCursorX lda (tableVector),y sta editBuffer lda #$01 sta writeScreen rts tableHintSystem: ldy tableCursorX cpy #TABLE_COLUMN_FX1 ;beq @yes ;cpy #TABLE_COLUMN_FX2 ;bne @x bcc @x @yes: lda PAD1_sel bne @x lda PAD1_firea bne @a lda hintMode beq @x @c: lda #$00 sta hintMode lda #$01 sta writeScreen rts @a: clc adc hintMode cmp #$20 bcc @b lda editBuffer ;cmp #$FF ;beq @c ldy tableCursorX cpy #TABLE_COLUMN_FX1 beq @d cpy #TABLE_COLUMN_FX2 beq @d dey lda (tableVector),y cmp #$FF beq @x @d: ldy tableCursorY jsr editorShowHint rts @b: sta hintMode @x: rts tableKeysHoldAB_TapUDLR: lda PAD1_firea beq @x lda PAD1_fireb beq @x lda PAD1_dud beq @noUD bpl @down jsr tableDeleteRow ldy tableCursorX lda (tableVector),y cmp #$FF beq @a sta editTableLastValue,x @a: sta editBuffer lda #$01 sta editBufferFlag @a1: lda #$01 sta writeScreen rts @down: jsr tableInsertRow ldy tableCursorX lda (tableVector),y sta editBuffer lda #$01 sta writeScreen lda #$01 sta editBufferFlag rts @noUD: lda PAD1_dlr beq @x @x: rts tableDeleteRow: ldx editorCurrentTable lda editTableAddressLo,x sta tmp0 lda editTableAddressHi,x sta tmp1 lda tableCursorY cmp #STEPS_PER_TABLE-1 beq @x tay iny lda tableRowsIndex,y tay ldx #$00 @a: lda (tmp0),y sta copyBuffer,x inx iny cpy #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @a lda tableCursorY tay lda tableRowsIndex,y tay ldx #$00 @b: lda copyBuffer,x sta (tmp0),y inx iny cpy #((STEPS_PER_TABLE-1) * BYTES_PER_TABLE_STEP) bcc @b ldy #STEPS_PER_TABLE-1 lda tableRowsIndex,y tay lda #$0F sta (tmp0),y ;vol iny lda #$00 sta (tmp0),y ;pitch iny lda #$FF sta (tmp0),y ;fx iny lda #$00 sta (tmp0),y ;fx data iny lda #$FF sta (tmp0),y ;fx iny lda #$00 sta (tmp0),y ;fx data lda #$FF sta copyBufferObjectType jsr editorUpdateCopyInfo @x: rts tableInsertRow: ldx editorCurrentTable lda editTableAddressLo,x sta tmp0 lda editTableAddressHi,x sta tmp1 lda tableCursorY cmp #STEPS_PER_TABLE-1 beq @x tay lda tableRowsIndex,y tay ldx #$00 @a: lda (tmp0),y sta copyBuffer,x inx iny cpy #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @a lda tableCursorY tay iny lda tableRowsIndex,y tay ldx #$00 @b: lda copyBuffer,x sta (tmp0),y inx iny cpy #(STEPS_PER_TABLE * BYTES_PER_TABLE_STEP) bcc @b lda #$FF sta copyBufferObjectType jsr editorUpdateCopyInfo @x: rts tablePlayMarkers: ldx editorCurrentTrack lda editorInstrumentAddressLo,x sta tmp0 lda editorInstrumentAddressHi,x sta tmp1 ldy #INSTRUMENT_ROW_TABLE lda (tmp0),y cmp editorCurrentTable bne @x lda plyrTableIndex,x tay lda tableCursorRows,y sec sbc #$01 sta SPR05_Y sta SPR06_Y lda #SPR_RIGHT_ARROW sta SPR05_CHAR lda #SPR_LEFT_ARROW sta SPR06_CHAR lda #26+48 sta SPR05_X clc adc #14*8 sta SPR06_X @x: rts tableKeysHoldSelect_UDLR: ;rts ;*new controls* lda PAD1_sel beq @x lda PAD1_firea ora PAD1_fireb bne @x lda PAD1_dud ora keysRepeatUD beq @noUD clc adc editorCurrentTable bpl @a lda #$00 beq @b @a: cmp #NUMBER_OF_TABLES bcs @x @b: sta editorCurrentTable lda #$02 sta writeScreen rts @noUD: lda PAD1_dlr beq @x bmi tableCopyData jsr tablePasteData @x: rts tableCopyData: lda editorMode sta copyBufferObjectType ldx editorCurrentTable stx copyBufferObject lda editTableAddressLo,x sta tmp0 lda editTableAddressHi,x sta tmp1 ldx #$00 ldy tableCursorY sty copyBufferStartIndex lda tableRowsIndex,y tay @copyLoop: lda (tmp0),y sta copyBuffer,x inx iny cpy #(STEPS_PER_TABLE*BYTES_PER_TABLE_STEP) bcc @copyLoop stx copyBufferLength @x: jsr editorUpdateCopyInfo rts tablePasteData: lda copyBufferObjectType bmi @x ;nothing to copy cmp editorMode bne @x ;wrong object type ldx editorCurrentTable lda editTableAddressLo,x sta tmp0 lda editTableAddressHi,x sta tmp1 ldy tableCursorY lda tableRowsIndex,y tay ldx #$00 @b: lda copyBuffer,x sta (tmp0),y inx iny cpx copyBufferLength bcs @a cpy #(STEPS_PER_TABLE*BYTES_PER_TABLE_STEP) bcc @b @a: lda #$01 sta writeScreen rts @x: lda #ERROR_PASTE sta errorMessageNumber rts tableKeysHoldA_UDLR: lda PAD1_fireb;keysHoldB beq @noB @y: rts @noB: lda PAD1_sel bne @y lda PAD1_firea;keysHoldA ;hold A + U/D/L/R = modify value bne @holdA lda editBufferFlag beq @x lda editBuffer sta (tableVector),y @notEditing: lda #$00 sta editBufferFlag beq @x @holdA: lda editBufferFlag bne @editing inc editBufferFlag lda (tableVector),y cpy #TABLE_COLUMN_PITCH beq @notEmpty cpy #TABLE_COLUMN_FX1_DATA beq @notEmpty cpy #TABLE_COLUMN_FX2_DATA beq @notEmpty cmp #$FF bne @notEmpty lda editTableLastValue,y @notEmpty: sta editBuffer jsr editTableUpdateScreenValue ldy tableCursorX @editing: lda keysRepeatLR ora PAD1_dlr bne @addValue lda keysRepeatUD ora PAD1_dud beq @x bpl @negative lda tablePositiveAdd,y jmp @addValue @negative: lda tableNegativeAdd,y @addValue: clc adc editBuffer cpy #TABLE_COLUMN_PITCH beq @noLimit1 cpy #TABLE_COLUMN_FX1_DATA beq @noLimit1 cpy #TABLE_COLUMN_FX2_DATA beq @noLimit1 and #$FF bpl @notNeg0 lda #$00 beq @noLimit1 @notNeg0: cmp tableMaxValues,y bcc @noLimit1 lda tableMaxValues,y sec sbc #$01 @noLimit1: sta editBuffer sta editTableLastValue,y jsr editTableUpdateScreenValue @x: rts tableKeysTapB: lda PAD1_sel beq @x lda keysTapB beq @x ldy tableCursorX lda tableClearValues,y sta (tableVector),y sta editBuffer jmp editTableUpdateScreenValue @x: rts tableKeysTapA: lda keysTapA beq @x .IF 0=1 lda PAD1_fireb beq @notDel ldy tableCursorX lda tableClearValues,y sta (tableVector),y sta editBuffer jmp editTableUpdateScreenValue .ENDIF @notDel: lda editTableLastValue,y sta (tableVector),y sta editBuffer jsr editTableUpdateScreenValue ldy tableCursorX @x: rts tableClearValues: .BYTE $0F,$00,$FF,$00,$FF,$00 tableMaxValues: .BYTE $10,$00,(editorCommandsEnd-editorCommands),0,(editorCommandsEnd-editorCommands),0 tablePositiveAdd: .BYTE $01,$0C,$01,$10,$01,$10 tableNegativeAdd: .BYTE -1, -12, -1, -16, -1, -16 printTableCommand: cmp #$FF bne @a lda #CHR_EMPTY sta windowBuffer,x inx rts @a: sty tmp2 tay lda editorCommands,y sta windowBuffer,x ldy tmp2 inx rts editTableUpdateScreenValue: sta tmp3 ldx tableCursorY lda rowOffsetTable,x ldx tableCursorX clc adc columnOffsetTable,x tax lda tableCursorX lda tmp3 cpy #TABLE_COLUMN_FX1 bcs @a jmp phexWindow @a: beq @command cpy #TABLE_COLUMN_FX2 beq @command dey lda (tableVector),y cmp #COMMAND_W bne @notDuty lda tmp3 jmp instrumentPrintDuty @notDuty: lda tmp3 jmp phexWindow @command: jsr printTableCommand lda tmp3 cmp #COMMAND_W bne @notDuty2 iny lda (tableVector),y jmp instrumentPrintDuty @notDuty2: iny lda (tableVector),y jmp phexWindow writeTableScreen: ldx #$00 ldy tableFirstRow ;first write row numbers to buffer @a: tya jsr phexRow iny cpx #$20 bcc @a ldx editorCurrentTable lda editTableAddressLo,x sta tmp0 lda editTableAddressHi,x sta tmp1 ldx #$00 lda tableFirstRow tay lda tableRowsIndex,y tay @b: lda (tmp0),y ;volume jsr phexWindow lda #CHR_SPACE sta windowBuffer,x inx iny lda (tmp0),y ;pitch jsr phexWindow lda #CHR_SPACE sta windowBuffer,x inx iny lda (tmp0),y ;FX1 pha jsr printTableCommand iny pla cmp #COMMAND_W bne @notDuty1 lda (tmp0),y jsr instrumentPrintDuty jmp @skipDuty1 @notDuty1: lda (tmp0),y ;FX1 data jsr phexWindow @skipDuty1: lda #CHR_SPACE sta windowBuffer,x inx iny lda (tmp0),y ;FX2 pha jsr printTableCommand iny pla cmp #COMMAND_W bne @notDuty2 lda (tmp0),y jsr instrumentPrintDuty jmp @skipDuty2 @notDuty2: lda (tmp0),y ;FX1 data jsr phexWindow @skipDuty2: lda #CHR_SPACE sta windowBuffer,x inx iny cpx #(14 * 16) bcc @b rts writeTableHeaderFooter: ldx #$00 ;write header and title bars to buffer @c: lda titleTable,x sta titleBuffer,x lda headerTable,x sta headerBuffer,x inx cpx #$11 bne @c ldx #$08 ;print current chain number in title bar lda editorCurrentTable jsr phexTitle rts tableCursorColumns: .BYTE $53, $53+(3*8), $53+(6*8), $53+(7*8), $53+(10*8), $53+(11*8) tableCursorRows: .REPEAT 16,i .BYTE $28 + (i * 8) .ENDREPEAT rowOffsetTable: .REPEAT 16,i .BYTE i*14 .ENDREPEAT columnOffsetTable: .BYTE 0,3,6,7,10,11 ; ;0 = no cursor, 1=8x8, 2=8x16, 3=8x24 ; tableColumnCursorType: .BYTE 2,2,1,2,1,2
; A181973: Prime-generating polynomial: 16*n^2 - 300*n + 1447. ; 1447,1163,911,691,503,347,223,131,71,43,47,83,151,251,383,547,743,971,1231,1523,1847,2203,2591,3011,3463,3947,4463,5011,5591,6203,6847,7523,8231,8971,9743,10547,11383,12251,13151,14083,15047,16043,17071,18131,19223,20347,21503,22691,23911,25163,26447,27763,29111,30491,31903,33347,34823,36331,37871,39443,41047,42683,44351,46051,47783,49547,51343,53171,55031,56923,58847,60803,62791,64811,66863,68947,71063,73211,75391,77603,79847,82123,84431,86771,89143,91547,93983,96451,98951,101483,104047,106643,109271,111931,114623,117347,120103,122891,125711,128563 sub $0,7 mov $1,2 sub $1,$0 mul $1,4 add $1,2 bin $1,2 div $1,2 mul $1,4 add $1,43 mov $0,$1
; void exit_success() PUBLIC exit_success EXTERN libspectranet include "spectranet.asm" .exit_success pop hl ; unwind return address from the stack jp EXIT_SUCCESS_ROM
/* * StreamEncoderRAW.cpp * -------------------- * Purpose: Exporting streamed music files. * Notes : none * Authors: Joern Heusipp * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "StreamEncoder.h" #include "StreamEncoderRAW.h" #include "Mptrack.h" #include "TrackerSettings.h" #include "../common/mptFileIO.h" #include "../soundlib/Sndfile.h" OPENMPT_NAMESPACE_BEGIN class RawStreamWriter : public IAudioStreamEncoder { private: const RAWEncoder &enc; std::ostream &f; Encoder::Format formatInfo; public: RawStreamWriter(const RAWEncoder &enc_, std::ostream &file, const Encoder::Settings &settings, const FileTags &tags) : enc(enc_) , f(file) { formatInfo = enc.GetTraits().formats[settings.Format]; ASSERT(formatInfo.Sampleformat.IsValid()); ASSERT(formatInfo.Samplerate > 0); ASSERT(formatInfo.Channels > 0); MPT_UNREFERENCED_PARAMETER(tags); } mpt::endian GetConvertedEndianness() const override { return mpt::get_endian(); } void WriteInterleaved(size_t count, const float *interleaved) override { ASSERT(formatInfo.Sampleformat.IsFloat()); WriteInterleavedConverted(count, reinterpret_cast<const std::byte*>(interleaved)); } void WriteInterleavedConverted(size_t frameCount, const std::byte *data) override { mpt::IO::WriteRaw(f, data, frameCount * formatInfo.Channels * (formatInfo.Sampleformat.GetBitsPerSample() / 8)); } void WriteCues(const std::vector<uint64> &cues) override { MPT_UNREFERENCED_PARAMETER(cues); } void WriteFinalize() override { // nothing } virtual ~RawStreamWriter() { // nothing } }; RAWEncoder::RAWEncoder() { Encoder::Traits traits; traits.fileExtension = P_("raw"); traits.fileShortDescription = U_("Raw PCM"); traits.fileDescription = U_("Headerless raw little-endian PCM"); traits.encoderSettingsName = U_("RAW"); traits.canTags = false; traits.canCues = false; traits.maxChannels = 4; traits.samplerates = TrackerSettings::Instance().GetSampleRates(); traits.modes = Encoder::ModeEnumerated; for(std::size_t i = 0; i < traits.samplerates.size(); ++i) { int samplerate = traits.samplerates[i]; for(int channels = 1; channels <= traits.maxChannels; channels *= 2) { const std::array<SampleFormat, 7> sampleFormats = { SampleFormatFloat64, SampleFormatFloat32, SampleFormatInt32, SampleFormatInt24, SampleFormatInt16, SampleFormatInt8, SampleFormatUnsigned8 }; for(const auto sampleFormat : sampleFormats) { Encoder::Format format; format.Samplerate = samplerate; format.Channels = channels; format.Sampleformat = sampleFormat; if(sampleFormat.IsFloat()) { format.Description = MPT_UFORMAT("{} Bit Floating Point Little-Endian")(sampleFormat.GetBitsPerSample()); } else if(sampleFormat.IsUnsigned()) { format.Description = MPT_UFORMAT("{} Bit Little-Endian (unsigned)")(sampleFormat.GetBitsPerSample()); } else { format.Description = MPT_UFORMAT("{} Bit Little-Endian")(sampleFormat.GetBitsPerSample()); } format.Bitrate = 0; traits.formats.push_back(format); } } } traits.defaultSamplerate = 48000; traits.defaultChannels = 2; traits.defaultMode = Encoder::ModeEnumerated; traits.defaultFormat = 1; // 32-bit float SetTraits(traits); } bool RAWEncoder::IsAvailable() const { return true; } std::unique_ptr<IAudioStreamEncoder> RAWEncoder::ConstructStreamEncoder(std::ostream &file, const Encoder::Settings &settings, const FileTags &tags) const { if(!IsAvailable()) { return nullptr; } return std::make_unique<RawStreamWriter>(*this, file, settings, tags); } OPENMPT_NAMESPACE_END
; ; Amstrad CPC library ; ; ****************************************************** ; ** Librería de rutinas para Amstrad CPC ** ; ** Raúl Simarro, Artaburu 2009 ** ; ****************************************************** ; ; void __LIB__ cpc_AssignKey(unsigned char key, int value) __smallc __z88dk_callee; ; ; $Id: cpc_AssignKey_callee.asm $ ; SECTION code_clib PUBLIC cpc_AssignKey_callee PUBLIC _cpc_AssignKey_callee PUBLIC asm_cpc_AssignKey EXTERN tabla_teclas .cpc_AssignKey_callee ._cpc_AssignKey_callee pop bc pop hl pop de push bc .asm_cpc_AssignKey ;HL = linea, byte ;DE = value ld a,l ;linea, byte ld b,h ; DE tiene el valor de la tecla a escribir en la tabla ; En A se tiene "key", el valor de la tecla seleccionada a comprobar [0..11] ; A*2 ;______________________________________________________________________________________________ ; ;En A viene la tecla a redefinir (0..11) ;srl e ;A*2 ; sla e ;ld e,a ;ld d,0 ld hl,tabla_teclas ; gracias a Mochilote por detectar un error aquí: add hl,de ;Nos colocamos en la tecla a redefinir y la borramos ld (hl),$ff inc hl ld (hl),$ff dec hl push hl ;call ejecutar_deteccion_teclado ;A tiene el valor del teclado ;ld a,d ; A tiene el byte (<>0) ; B tiene la linea ;guardo linea y byte pop hl ;ld a,(linea) ld (hl),a ;byte inc hl ;ld a,b ;linea ;ld a,(bte) ld (hl),b ret
; A005995: Alkane (or paraffin) numbers l(8,n). ; 1,3,12,28,66,126,236,396,651,1001,1512,2184,3108,4284,5832,7752,10197,13167,16852,21252,26598,32890,40404,49140,59423,71253,85008,100688,118728,139128,162384,188496,218025,250971,287964,329004,374794,425334,481404,543004,610995,685377,767096,856152,953580,1059380,1174680,1299480,1435005,1581255,1739556,1909908,2093742,2291058,2503396,2730756,2974791,3235501,3514656,3812256,4130192,4468464,4829088,5212064,5619537,6051507,6510252,6995772,7510482,8054382,8630028,9237420,9879259,10555545,11269128 mov $2,$0 add $2,1 mov $3,$0 lpb $2 mov $0,$3 sub $2,1 sub $0,$2 mov $4,$0 add $4,1 mov $5,0 mov $6,$0 lpb $4 mov $0,$6 sub $4,1 sub $0,$4 div $0,2 mul $0,2 seq $0,23855 ; a(n) = 1*(n) + 2*(n-1) + 3*(n-2) + ... + (n+1-k)*k, where k = floor((n+1)/2). add $5,$0 lpe add $1,$5 lpe mov $0,$1
PIC_WIDTH = 320 PIC_HEIGHT equ 256 DEBUG_LEVEL set 10 DOUBLE_BUFFER_1 = 1 AUTO_COMPLETE_2 = 1 dood2 = 1 entry: bsr init bsr main bsr exit rts init move.w #PIC_HEIGHT,d1 .looph move.w #PIC_WIDTH,d0 .loopw clr.b (a0)+ subq.w #1,d0 bne.s .loopw subq.w #1,d1 bne.s .looph move.w a1,d2<caret> move.w e<caret> move.w ex<caret> move.w PW<caret> move.w A<caret> move.w DEB<caret> move.w A2<caret> move.w D1<caret> rts main moveq.l #0,d0 rts exit illegal rts
#include "GuiInstanceLoader_WorkflowCodegen.h" #include "../../Resources/GuiParserManager.h" namespace vl { namespace presentation { using namespace stream; using namespace reflection::description; using namespace workflow; using namespace workflow::analyzer; /*********************************************************************** Parser ***********************************************************************/ template<typename T> Ptr<T> Workflow_Parse(GuiResourcePrecompileContext& precompileContext, const WString& parserName, GuiResourceLocation location, const WString& code, GuiResourceTextPos position, collections::List<GuiResourceError>& errors, glr::ParsingTextPos availableAfter) { vint errorCount = errors.Count(); auto parser = GetParserManager()->GetParser<T>(parserName); auto result = parser->Parse(location, code, position, errors); if (availableAfter.row != 0 || availableAfter.column != 0) { for (vint i = errorCount; i < errors.Count(); i++) { auto& error = errors[i]; if (error.position.row > position.row) { error.position.row -= availableAfter.row; } else if (error.position.row == position.row && error.position.column >= position.column) { error.position.column -= availableAfter.column; } } } if (result) { Workflow_RecordScriptPosition(precompileContext, position, result, availableAfter); } return result; } Ptr<workflow::WfType> Workflow_ParseType(GuiResourcePrecompileContext& precompileContext, GuiResourceLocation location, const WString& code, GuiResourceTextPos position, collections::List<GuiResourceError>& errors, glr::ParsingTextPos availableAfter) { return Workflow_Parse<WfType>(precompileContext, L"WORKFLOW-TYPE", location, code, position, errors, availableAfter); } Ptr<workflow::WfExpression> Workflow_ParseExpression(GuiResourcePrecompileContext& precompileContext, GuiResourceLocation location, const WString& code, GuiResourceTextPos position, collections::List<GuiResourceError>& errors, glr::ParsingTextPos availableAfter) { return Workflow_Parse<WfExpression>(precompileContext, L"WORKFLOW-EXPRESSION", location, code, position, errors, availableAfter); } Ptr<workflow::WfStatement> Workflow_ParseStatement(GuiResourcePrecompileContext& precompileContext, GuiResourceLocation location, const WString& code, GuiResourceTextPos position, collections::List<GuiResourceError>& errors, glr::ParsingTextPos availableAfter) { return Workflow_Parse<WfStatement>(precompileContext, L"WORKFLOW-STATEMENT", location, code, position, errors, availableAfter); } Ptr<workflow::WfStatement> Workflow_ParseCoProviderStatement(GuiResourcePrecompileContext& precompileContext, GuiResourceLocation location, const WString& code, GuiResourceTextPos position, collections::List<GuiResourceError>& errors, glr::ParsingTextPos availableAfter) { return Workflow_Parse<WfStatement>(precompileContext, L"WORKFLOW-COPROVIDER-STATEMENT", location, code, position, errors, availableAfter); } Ptr<workflow::WfModule> Workflow_ParseModule(GuiResourcePrecompileContext& precompileContext, GuiResourceLocation location, const WString& code, GuiResourceTextPos position, collections::List<GuiResourceError>& errors, glr::ParsingTextPos availableAfter) { return Workflow_Parse<WfModule>(precompileContext, L"WORKFLOW-MODULE", location, code, position, errors, availableAfter); } /*********************************************************************** Workflow_ModuleToString ***********************************************************************/ WString Workflow_ModuleToString(Ptr<workflow::WfModule> module) { return GenerateToStream([&](StreamWriter& writer) { WfPrint(module, L"", writer); }); } /*********************************************************************** Converter ***********************************************************************/ Ptr<workflow::WfExpression> Workflow_ParseTextValue(GuiResourcePrecompileContext& precompileContext, description::ITypeDescriptor* typeDescriptor, GuiResourceLocation location, const WString& textValue, GuiResourceTextPos position, collections::List<GuiResourceError>& errors) { if (typeDescriptor == description::GetTypeDescriptor<WString>()) { auto valueExpr = MakePtr<WfStringExpression>(); valueExpr->value.value = textValue; return valueExpr; } else if (typeDescriptor == description::GetTypeDescriptor<bool>()) { bool value = false; if (!TypedValueSerializerProvider<bool>::Deserialize(textValue, value)) return nullptr; auto valueExpr = MakePtr<WfLiteralExpression>(); valueExpr->value = value ? WfLiteralValue::True : WfLiteralValue::False; return valueExpr; } #define INTEGER_BRANCH(TYPE) \ else if (typeDescriptor == description::GetTypeDescriptor<TYPE>()) \ { \ auto valueExpr = MakePtr<WfIntegerExpression>(); \ valueExpr->value.value = textValue; \ auto type = MakePtr<TypeDescriptorTypeInfo>(typeDescriptor, TypeInfoHint::Normal); \ auto infer = MakePtr<WfInferExpression>(); \ infer->type = GetTypeFromTypeInfo(type.Obj()); \ infer->expression = valueExpr; \ return infer; \ } INTEGER_BRANCH(vint8_t) INTEGER_BRANCH(vint16_t) INTEGER_BRANCH(vint32_t) INTEGER_BRANCH(vint64_t) INTEGER_BRANCH(vuint8_t) INTEGER_BRANCH(vuint16_t) INTEGER_BRANCH(vuint32_t) INTEGER_BRANCH(vuint64_t) #undef INTEGER_BRANCH #define FLOATING_BRANCH(TYPE) \ else if (typeDescriptor == description::GetTypeDescriptor<TYPE>()) \ { \ auto valueExpr = MakePtr<WfFloatingExpression>(); \ valueExpr->value.value = textValue; \ auto type = MakePtr<TypeDescriptorTypeInfo>(typeDescriptor, TypeInfoHint::Normal); \ auto infer = MakePtr<WfInferExpression>(); \ infer->type = GetTypeFromTypeInfo(type.Obj()); \ infer->expression = valueExpr; \ return infer; \ } FLOATING_BRANCH(float) FLOATING_BRANCH(double) #undef FLOATING_BRANCH else if (typeDescriptor->GetSerializableType()) { auto str = MakePtr<WfStringExpression>(); str->value.value = textValue; auto type = MakePtr<TypeDescriptorTypeInfo>(typeDescriptor, TypeInfoHint::Normal); auto cast = MakePtr<WfTypeCastingExpression>(); cast->type = GetTypeFromTypeInfo(type.Obj()); cast->strategy = WfTypeCastingStrategy::Strong; cast->expression = str; return cast; } else if (typeDescriptor->GetTypeDescriptorFlags() == TypeDescriptorFlags::Struct) { if (auto valueExpr = Workflow_ParseExpression(precompileContext, location, L"{" + textValue + L"}", position, errors, { 0,1 })) // { { auto type = MakePtr<TypeDescriptorTypeInfo>(typeDescriptor, TypeInfoHint::Normal); auto infer = MakePtr<WfInferExpression>(); infer->type = GetTypeFromTypeInfo(type.Obj()); infer->expression = valueExpr; return infer; } return nullptr; } else if ((typeDescriptor->GetTypeDescriptorFlags() & TypeDescriptorFlags::EnumType) != TypeDescriptorFlags::Undefined) { if (auto valueExpr = Workflow_ParseExpression(precompileContext, location, L"(" + textValue + L")", position, errors, { 0,1 })) // { { auto type = MakePtr<TypeDescriptorTypeInfo>(typeDescriptor, TypeInfoHint::Normal); auto infer = MakePtr<WfInferExpression>(); infer->type = GetTypeFromTypeInfo(type.Obj()); infer->expression = valueExpr; return infer; } return nullptr; } else { CHECK_FAIL(L"vl::presentation::Workflow_ParseTextValue(ITypeDescriptor*, const WString&, GuiResourceError::List&)#This is not a value type."); } } } }
; L0311.asm ; Generated 10.20.2000 by mlevel ; Modified 10.20.2000 by Abe Pralle INCLUDE "Source/Defs.inc" INCLUDE "Source/Levels.inc" FIRST_HOLE EQU 25 ;--------------------------------------------------------------------- SECTION "Level0311Section",ROMX ;--------------------------------------------------------------------- L0311_Contents:: DW L0311_Load DW L0311_Init DW L0311_Check DW L0311_Map ;--------------------------------------------------------------------- ; Load ;--------------------------------------------------------------------- L0311_Load: DW ((L0311_LoadFinished - L0311_Load2)) ;size L0311_Load2: call ParseMap ;alter yellow palette to purple w/black ld a,FADEBANK ld bc,6 ld de,gamePalette + 5*8 + 2 ld hl,((.purpleBlackPalette-L0311_Load2)+levelCheckRAM) call MemCopy ret .purpleBlackPalette DW $4008,$5192,$0000 L0311_LoadFinished: ;--------------------------------------------------------------------- ; Map ;--------------------------------------------------------------------- L0311_Map: INCBIN "Data/Levels/L0311_tower.lvl" ;--------------------------------------------------------------------- ; Init ;--------------------------------------------------------------------- L0311_Init: DW ((L0311_InitFinished - L0311_Init2)) ;size L0311_Init2: ret L0311_InitFinished: ;--------------------------------------------------------------------- ; Check ;--------------------------------------------------------------------- L0311_Check: DW ((L0311_CheckFinished - L0311_Check2)) ;size L0311_Check2: call ((.checkFalling-L0311_Check2)+levelCheckRAM) ret .checkFalling ld a,[timeToChangeLevel] or a ret z ld a,[exitTileIndex] cp FIRST_HOLE ret c ld hl,((.fallSound-L0311_Check2)+levelCheckRAM) call PlaySound ld a,15 call Delay ret .fallSound DB 1,$7e,$80,$f5,$00,$86 L0311_CheckFinished: PRINT "0311 Script Sizes (Load/Init/Check) (of $500): " PRINT (L0311_LoadFinished - L0311_Load2) PRINT " / " PRINT (L0311_InitFinished - L0311_Init2) PRINT " / " PRINT (L0311_CheckFinished - L0311_Check2) PRINT "\n"
db DEX_BEEDRILL ; pokedex id db 65 ; base hp db 80 ; base attack db 40 ; base defense db 75 ; base speed db 45 ; base special db BUG ; species type 1 db POISON ; species type 2 db 46 ; catch rate db 159 ; base exp yield INCBIN "pic/ymon/beedrill.pic",0,1 ; 77, sprite dimensions dw BeedrillPicFront dw BeedrillPicBack ; attacks known at lvl 0 db FURY_ATTACK db 0 db 0 db 0 db 0 ; growth rate ; learnset tmlearn 3,6 tmlearn 9,10,15 tmlearn 20,21 tmlearn 31,32 tmlearn 33,34,39,40 tmlearn 44 tmlearn 50,51,52 db BANK(BeedrillPicFront)
/** * Copyright (C) 2021-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/catalog/clustered_collection_util.h" #include "mongo/db/namespace_string.h" #include "mongo/logv2/log.h" #include "mongo/util/represent_as.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault namespace mongo { namespace clustered_util { static constexpr StringData kDefaultClusteredIndexName = "_id_"_sd; void ensureClusteredIndexName(ClusteredIndexSpec& indexSpec) { if (!indexSpec.getName()) { auto clusterKey = indexSpec.getKey().firstElement().fieldNameStringData(); if (clusterKey == "_id") { indexSpec.setName(kDefaultClusteredIndexName); } else { indexSpec.setName(StringData(clusterKey + "_1")); } } } ClusteredCollectionInfo makeCanonicalClusteredInfoForLegacyFormat() { auto indexSpec = ClusteredIndexSpec{BSON("_id" << 1), true /* unique */}; indexSpec.setName(kDefaultClusteredIndexName); return ClusteredCollectionInfo(std::move(indexSpec), true /* legacy */); } ClusteredCollectionInfo makeDefaultClusteredIdIndex() { auto indexSpec = ClusteredIndexSpec{BSON("_id" << 1), true /* unique */}; indexSpec.setName(kDefaultClusteredIndexName); return makeCanonicalClusteredInfo(indexSpec); } ClusteredCollectionInfo makeCanonicalClusteredInfo(ClusteredIndexSpec indexSpec) { ensureClusteredIndexName(indexSpec); return ClusteredCollectionInfo(std::move(indexSpec), false); } boost::optional<ClusteredCollectionInfo> parseClusteredInfo(const BSONElement& elem) { uassert(5979702, "'clusteredIndex' has to be a boolean or object.", elem.type() == mongo::Bool || elem.type() == mongo::Object); bool isLegacyFormat = elem.type() == mongo::Bool; if (isLegacyFormat) { // Legacy format implies the collection was created with format {clusteredIndex: <bool>}. // The legacy format is maintained for backward compatibility with time series buckets // collection creation. if (!elem.Bool()) { // clusteredIndex was specified as false. return boost::none; } return makeCanonicalClusteredInfoForLegacyFormat(); } auto indexSpec = ClusteredIndexSpec::parse({"ClusteredUtil::parseClusteredInfo"}, elem.Obj()); ensureClusteredIndexName(indexSpec); return makeCanonicalClusteredInfo(std::move(indexSpec)); } boost::optional<ClusteredCollectionInfo> createClusteredInfoForNewCollection( const BSONObj& indexSpec) { if (!indexSpec["clustered"]) { return boost::none; } auto filteredIndexSpec = indexSpec.removeField("clustered"_sd); auto clusteredIndexSpec = ClusteredIndexSpec::parse( {"ClusteredUtil::createClusteredInfoForNewCollection"}, filteredIndexSpec); ensureClusteredIndexName(clusteredIndexSpec); return makeCanonicalClusteredInfo(std::move(clusteredIndexSpec)); }; bool requiresLegacyFormat(const NamespaceString& nss) { return nss.isTimeseriesBucketsCollection() || nss.isChangeStreamPreImagesCollection(); } BSONObj formatClusterKeyForListIndexes(const ClusteredCollectionInfo& collInfo, const BSONObj& collation) { BSONObjBuilder bob; collInfo.getIndexSpec().serialize(&bob); if (!collation.isEmpty()) { bob.append("collation", collation); } bob.append("clustered", true); return bob.obj(); } bool isClusteredOnId(const boost::optional<ClusteredCollectionInfo>& collInfo) { return clustered_util::matchesClusterKey(BSON("_id" << 1), collInfo); } bool matchesClusterKey(const BSONObj& keyPatternObj, const boost::optional<ClusteredCollectionInfo>& collInfo) { if (!collInfo) { return false; } const auto nFields = keyPatternObj.nFields(); invariant(nFields > 0); if (nFields > 1) { // Clustered key cannot be compound. return false; } if (!keyPatternObj.firstElement().isNumber()) { // Clustered index can't be of any special type. return false; } return keyPatternObj.firstElement().fieldNameStringData() == collInfo->getIndexSpec().getKey().firstElement().fieldNameStringData(); } StringData getClusterKeyFieldName(const ClusteredIndexSpec& indexSpec) { return indexSpec.getKey().firstElement().fieldNameStringData(); } BSONObj getSortPattern(const ClusteredIndexSpec& indexSpec) { return indexSpec.getKey(); } } // namespace clustered_util } // namespace mongo
; ; ; Z88 Maths Routines ; ; C Interface for Small C+ Compiler ; ; 7/12/98 djm ;Convert from integer to FP.. ;We could enter in here with a long in dehl, so, mod to compiler I think! INCLUDE "fpp.def" PUBLIC ufloat EXTERN fa .ufloat push de ;msb exx pop hl ld c,0 ;no exponent ld a,h push af res 7,h fpp(FP_FLT) pop af rlca jr nc,ufloat_out ;no high bit ;to multiply by two, increment the exponent inc c .ufloat_out ld (fa+3),hl ld a,c ld (fa+5),a exx ld (fa+1),hl xor a ld (fa),a ret
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r15 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0xbf, %rsi nop nop nop cmp $37237, %r14 movw $0x6162, (%rsi) nop nop nop nop nop xor $19030, %rsi lea addresses_D_ht+0x1447f, %rcx add $6512, %rbp mov $0x6162636465666768, %r12 movq %r12, %xmm7 movups %xmm7, (%rcx) and $63972, %rsi lea addresses_WC_ht+0xd21f, %rsi lea addresses_UC_ht+0x823f, %rdi add $28556, %rbx mov $84, %rcx rep movsw nop nop nop nop nop xor $40690, %rsi lea addresses_D_ht+0x26bf, %rbx nop nop nop cmp %r12, %r12 mov (%rbx), %bp nop nop dec %r15 lea addresses_D_ht+0x8233, %rsi lea addresses_A_ht+0xfcbf, %rdi clflush (%rsi) inc %rbx mov $70, %rcx rep movsq nop nop nop nop cmp %r12, %r12 lea addresses_normal_ht+0x13e3f, %rbx nop nop nop add %r15, %r15 mov (%rbx), %rcx nop nop cmp %rdi, %rdi lea addresses_WT_ht+0x885f, %rsi nop inc %r12 mov $0x6162636465666768, %rbp movq %rbp, (%rsi) nop nop nop nop xor $40861, %rbp pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r15 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r8 push %rax push %rbp push %rdx // Load lea addresses_D+0x1817f, %r10 nop lfence movb (%r10), %r11b dec %rbp // Faulty Load lea addresses_RW+0x1dcbf, %rbp nop inc %r8 vmovups (%rbp), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $0, %xmm3, %r12 lea oracles, %r10 and $0xff, %r12 shlq $12, %r12 mov (%r10,%r12,1), %r12 pop %rdx pop %rbp pop %rax pop %r8 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 32, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}} {'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 7}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 3}} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
; A260644: Four steps forward, three steps back. ; 0,1,2,3,4,3,2,1,2,3,4,5,4,3,2,3,4,5,6,5,4,3,4,5,6,7,6,5,4,5,6,7,8,7,6,5,6,7,8,9,8,7,6,7,8,9,10,9,8,7,8,9,10,11,10,9,8,9,10,11,12,11,10,9,10,11,12,13,12,11,10,11,12,13,14,13,12,11,12,13,14,15,14,13,12,13,14,15,16,15,14,13,14,15,16,17,16,15,14,15,16,17,18,17,16,15,16,17,18,19,18,17,16,17,18,19,20,19,18,17,18,19,20,21,20,19,18,19,20,21,22,21,20,19,20,21,22,23,22,21,20,21,22,23,24,23,22,21,22,23,24,25,24,23,22,23,24,25,26,25,24,23,24,25,26,27,26,25,24,25,26,27,28,27,26,25,26,27,28,29,28,27,26,27,28,29,30,29,28,27,28,29,30,31,30,29,28,29,30,31,32,31,30,29,30,31,32,33,32,31,30,31,32,33,34,33,32,31,32,33,34,35,34,33,32,33,34,35,36,35,34,33,34,35,36,37,36,35,34,35,36,37,38,37,36,35,36,37,38,39 lpb $0,1 sub $0,2 add $1,1 add $2,5 trn $2,$0 trn $0,5 add $0,$2 lpe add $1,$0
Name: zel_edt0.asm Type: file Size: 1894 Last-Modified: '2016-05-13T04:36:32Z' SHA-1: D8362C7DA722E78E3B99B384BFDE955F22542946 Description: null
db "BIG HORN@" ; species name dw 407, 1570 ; height, weight db "The round balls" next "found on the" next "fallen antlers can" page "be ground into a" next "powder that aids" next "in sleeping.@"
<% from pwnlib.shellcraft.amd64.linux import syscall %> <%page args="fd, buf, n, offset"/> <%docstring> Invokes the syscall pwrite. See 'man 2 pwrite' for more information. Arguments: fd(int): fd buf(void): buf n(size_t): n offset(off_t): offset </%docstring> ${syscall('SYS_pwrite', fd, buf, n, offset)}
; A322054: Number of decimal strings of length n that do not contain a specific string xx (where x is a single digit). ; Submitted by Jamie Morken(s2) ; 10,99,981,9720,96309,954261,9455130,93684519,928256841,9197472240,91131561729,902961305721,8946835807050,88648174014939,878355088397901,8703029361715560,86232460051021149,854419404714630381,8465866782890863770,83882575688449447359,831135982242062800161,8235167021374610227680,81596727032550057250569,808487046485322007304241,8010753961660848580993290,79373169073315535294677779,786455307314787454881039621,7792456287492926911581456600,77210204353269429298162465989,765023945766861205887695303301 add $0,1 mov $3,1 lpb $0 sub $0,1 mov $2,$3 add $3,$1 mov $1,$2 mul $3,9 lpe add $2,$3 mov $0,$2
//===- CompilerInvocation.cpp ---------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Frontend/CompilerInvocation.h" #include "TestModuleFileExtension.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/CodeGenOptions.h" #include "clang/Basic/CommentOptions.h" #include "clang/Basic/DebugInfoOptions.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticDriver.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/LangStandard.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/Sanitizers.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TargetOptions.h" #include "clang/Basic/Version.h" #include "clang/Basic/Visibility.h" #include "clang/Basic/XRayInstr.h" #include "clang/Config/config.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "clang/Frontend/CommandLineSourceLoc.h" #include "clang/Frontend/DependencyOutputOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/FrontendOptions.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/Frontend/MigratorOptions.h" #include "clang/Frontend/PreprocessorOutputOptions.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/Frontend/Utils.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Sema/CodeCompleteOptions.h" #include "clang/Serialization/ASTBitCodes.h" #include "clang/Serialization/ModuleFileExtension.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/CachedHashString.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/FloatingPointMode.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" #include "llvm/Config/llvm-config.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/Linker/Linker.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptSpecifier.h" #include "llvm/Option/OptTable.h" #include "llvm/Option/Option.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/Remarks/HotnessThresholdParser.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VersionTuple.h" #include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetOptions.h" #include <algorithm> #include <atomic> #include <cassert> #include <cstddef> #include <cstring> #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> using namespace clang; using namespace driver; using namespace options; using namespace llvm::opt; //===----------------------------------------------------------------------===// // Initialization. //===----------------------------------------------------------------------===// CompilerInvocationBase::CompilerInvocationBase() : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()), DiagnosticOpts(new DiagnosticOptions()), HeaderSearchOpts(new HeaderSearchOptions()), PreprocessorOpts(new PreprocessorOptions()) {} CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X) : LangOpts(new LangOptions(*X.getLangOpts())), TargetOpts(new TargetOptions(X.getTargetOpts())), DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())), HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())), PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {} CompilerInvocationBase::~CompilerInvocationBase() = default; //===----------------------------------------------------------------------===// // Normalizers //===----------------------------------------------------------------------===// #define SIMPLE_ENUM_VALUE_TABLE #include "clang/Driver/Options.inc" #undef SIMPLE_ENUM_VALUE_TABLE static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags, bool &Success) { if (Args.hasArg(Opt)) return true; return None; } static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &, bool &Success) { if (Args.hasArg(Opt)) return false; return None; } /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with /// unnecessary template instantiations and just ignore it with a variadic /// argument. static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator, Option::OptionClass, unsigned, /*T*/...) { Args.push_back(Spelling); } template <typename T> static constexpr bool is_uint64_t_convertible() { return !std::is_same<T, uint64_t>::value && llvm::is_integral_or_enum<T>::value; } template <typename T, std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false> static auto makeFlagToValueNormalizer(T Value) { return [Value](OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &, bool &Success) -> Optional<T> { if (Args.hasArg(Opt)) return Value; return None; }; } template <typename T, std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false> static auto makeFlagToValueNormalizer(T Value) { return makeFlagToValueNormalizer(uint64_t(Value)); } static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue, OptSpecifier OtherOpt) { return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned, const ArgList &Args, DiagnosticsEngine &, bool &Success) -> Optional<bool> { if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) { return A->getOption().matches(Opt) ? Value : OtherValue; } return None; }; } static auto makeBooleanOptionDenormalizer(bool Value) { return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator, Option::OptionClass, unsigned, bool KeyPath) { if (KeyPath == Value) Args.push_back(Spelling); }; } static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned, const Twine &Value) { switch (OptClass) { case Option::SeparateClass: case Option::JoinedOrSeparateClass: Args.push_back(Spelling); Args.push_back(SA(Value)); break; case Option::JoinedClass: case Option::CommaJoinedClass: Args.push_back(SA(Twine(Spelling) + Value)); break; default: llvm_unreachable("Cannot denormalize an option with option class " "incompatible with string denormalization."); } } template <typename T> static void denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, T Value) { denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value)); } static Optional<SimpleEnumValue> findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) { for (int I = 0, E = Table.Size; I != E; ++I) if (Name == Table.Table[I].Name) return Table.Table[I]; return None; } static Optional<SimpleEnumValue> findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) { for (int I = 0, E = Table.Size; I != E; ++I) if (Value == Table.Table[I].Value) return Table.Table[I]; return None; } static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args, DiagnosticsEngine &Diags, bool &Success) { assert(TableIndex < SimpleEnumValueTablesSize); const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; auto *Arg = Args.getLastArg(Opt); if (!Arg) return None; StringRef ArgValue = Arg->getValue(); if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue)) return MaybeEnumVal->Value; Success = false; Diags.Report(diag::err_drv_invalid_value) << Arg->getAsString(Args) << ArgValue; return None; } static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, unsigned Value) { assert(TableIndex < SimpleEnumValueTablesSize); const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex]; if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) { denormalizeString(Args, Spelling, SA, OptClass, TableIndex, MaybeEnumVal->Name); } else { llvm_unreachable("The simple enum value was not correctly defined in " "the tablegen option description"); } } template <typename T> static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, T Value) { return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex, static_cast<unsigned>(Value)); } static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex, const ArgList &Args, DiagnosticsEngine &Diags, bool &Success) { auto *Arg = Args.getLastArg(Opt); if (!Arg) return None; return std::string(Arg->getValue()); } template <typename IntTy> static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &Diags, bool &Success) { auto *Arg = Args.getLastArg(Opt); if (!Arg) return None; IntTy Res; if (StringRef(Arg->getValue()).getAsInteger(0, Res)) { Success = false; Diags.Report(diag::err_drv_invalid_int_value) << Arg->getAsString(Args) << Arg->getValue(); return None; } return Res; } static Optional<std::vector<std::string>> normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args, DiagnosticsEngine &, bool &Success) { return Args.getAllArgValues(Opt); } static void denormalizeStringVector(SmallVectorImpl<const char *> &Args, const char *Spelling, CompilerInvocation::StringAllocator SA, Option::OptionClass OptClass, unsigned TableIndex, const std::vector<std::string> &Values) { switch (OptClass) { case Option::CommaJoinedClass: { std::string CommaJoinedValue; if (!Values.empty()) { CommaJoinedValue.append(Values.front()); for (const std::string &Value : llvm::drop_begin(Values, 1)) { CommaJoinedValue.append(","); CommaJoinedValue.append(Value); } } denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass, TableIndex, CommaJoinedValue); break; } case Option::JoinedClass: case Option::SeparateClass: case Option::JoinedOrSeparateClass: for (const std::string &Value : Values) denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value); break; default: llvm_unreachable("Cannot denormalize an option with option class " "incompatible with string vector denormalization."); } } static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex, const ArgList &Args, DiagnosticsEngine &Diags, bool &Success) { auto *Arg = Args.getLastArg(Opt); if (!Arg) return None; return llvm::Triple::normalize(Arg->getValue()); } template <typename T, typename U> static T mergeForwardValue(T KeyPath, U Value) { return static_cast<T>(Value); } template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) { return KeyPath | Value; } template <typename T> static T extractForwardValue(T KeyPath) { return KeyPath; } template <typename T, typename U, U Value> static T extractMaskValue(T KeyPath) { return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T(); } #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, \ NORMALIZER, MERGER, TABLE_INDEX) \ if ((FLAGS)&options::CC1Option) { \ KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \ if (IMPLIED_CHECK) \ KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \ if (SHOULD_PARSE) \ if (auto MaybeValue = \ NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS, SUCCESS)) \ KEYPATH = \ MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \ } // Capture the extracted value as a lambda argument to avoid potential issues // with lifetime extension of the reference. #define GENERATE_OPTION_WITH_MARSHALLING( \ ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, \ TABLE_INDEX) \ if ((FLAGS)&options::CC1Option) { \ [&](const auto &Extracted) { \ if (ALWAYS_EMIT || \ (Extracted != \ static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \ : (DEFAULT_VALUE)))) \ DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class, \ TABLE_INDEX, Extracted); \ }(EXTRACTOR(KEYPATH)); \ } static const StringRef GetInputKindName(InputKind IK); static bool FixupInvocation(CompilerInvocation &Invocation, DiagnosticsEngine &Diags, const ArgList &Args, InputKind IK) { unsigned NumErrorsBefore = Diags.getNumErrors(); LangOptions &LangOpts = *Invocation.getLangOpts(); CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts(); TargetOptions &TargetOpts = Invocation.getTargetOpts(); FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument; CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents; CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents; CodeGenOpts.DisableFree = FrontendOpts.DisableFree; FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex; LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables; LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening; LangOpts.CurrentModule = LangOpts.ModuleName; llvm::Triple T(TargetOpts.Triple); llvm::Triple::ArchType Arch = T.getArch(); CodeGenOpts.CodeModel = TargetOpts.CodeModel; if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None && T.isWindowsMSVCEnvironment()) Diags.Report(diag::err_fe_invalid_exception_model) << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str(); if (LangOpts.AppleKext && !LangOpts.CPlusPlus) Diags.Report(diag::warn_c_kext); if (Args.hasArg(OPT_fconcepts_ts)) Diags.Report(diag::warn_fe_concepts_ts_flag); if (LangOpts.NewAlignOverride && !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) { Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ); Diags.Report(diag::err_fe_invalid_alignment) << A->getAsString(Args) << A->getValue(); LangOpts.NewAlignOverride = 0; } // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host. if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost) Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device" << "-fsycl-is-host"; if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus) Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fgnu89-inline" << GetInputKindName(IK); if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP) Diags.Report(diag::warn_ignored_hip_only_option) << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args); if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP) Diags.Report(diag::warn_ignored_hip_only_option) << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args); // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0. // This option should be deprecated for CL > 1.0 because // this option was added for compatibility with OpenCL 1.0. if (Args.getLastArg(OPT_cl_strict_aliasing) && LangOpts.OpenCLVersion > 100) Diags.Report(diag::warn_option_invalid_ocl_version) << LangOpts.getOpenCLVersionTuple().getAsString() << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args); if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) { auto DefaultCC = LangOpts.getDefaultCallingConv(); bool emitError = (DefaultCC == LangOptions::DCC_FastCall || DefaultCC == LangOptions::DCC_StdCall) && Arch != llvm::Triple::x86; emitError |= (DefaultCC == LangOptions::DCC_VectorCall || DefaultCC == LangOptions::DCC_RegCall) && !T.isX86(); if (emitError) Diags.Report(diag::err_drv_argument_not_allowed_with) << A->getSpelling() << T.getTriple(); } if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager) Diags.Report(diag::err_drv_argument_only_allowed_with) << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args) << "-fno-legacy-pass-manager"; return Diags.getNumErrors() == NumErrorsBefore; } //===----------------------------------------------------------------------===// // Deserialization (from args) //===----------------------------------------------------------------------===// static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, DiagnosticsEngine &Diags) { unsigned DefaultOpt = llvm::CodeGenOpt::None; if (IK.getLanguage() == Language::OpenCL && !Args.hasArg(OPT_cl_opt_disable)) DefaultOpt = llvm::CodeGenOpt::Default; if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { if (A->getOption().matches(options::OPT_O0)) return llvm::CodeGenOpt::None; if (A->getOption().matches(options::OPT_Ofast)) return llvm::CodeGenOpt::Aggressive; assert(A->getOption().matches(options::OPT_O)); StringRef S(A->getValue()); if (S == "s" || S == "z") return llvm::CodeGenOpt::Default; if (S == "g") return llvm::CodeGenOpt::Less; return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); } return DefaultOpt; } static unsigned getOptimizationLevelSize(ArgList &Args) { if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { if (A->getOption().matches(options::OPT_O)) { switch (A->getValue()[0]) { default: return 0; case 's': return 1; case 'z': return 2; } } } return 0; } static void GenerateArg(SmallVectorImpl<const char *> &Args, llvm::opt::OptSpecifier OptSpecifier, CompilerInvocation::StringAllocator SA) { Option Opt = getDriverOptTable().getOption(OptSpecifier); denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA, Option::OptionClass::FlagClass, 0); } static void GenerateArg(SmallVectorImpl<const char *> &Args, llvm::opt::OptSpecifier OptSpecifier, const Twine &Value, CompilerInvocation::StringAllocator SA) { Option Opt = getDriverOptTable().getOption(OptSpecifier); denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA, Opt.getKind(), 0, Value); } // Parse command line arguments into CompilerInvocation. using ParseFn = llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>, DiagnosticsEngine &, const char *)>; // Generate command line arguments from CompilerInvocation. using GenerateFn = llvm::function_ref<void( CompilerInvocation &, SmallVectorImpl<const char *> &, CompilerInvocation::StringAllocator)>; // May perform round-trip of command line arguments. By default, the round-trip // is enabled if CLANG_ROUND_TRIP_CC1_ARGS was defined during build. This can be // overwritten at run-time via the "-round-trip-args" and "-no-round-trip-args" // command line flags. // During round-trip, the command line arguments are parsed into a dummy // instance of CompilerInvocation which is used to generate the command line // arguments again. The real CompilerInvocation instance is then created by // parsing the generated arguments, not the original ones. static bool RoundTrip(ParseFn Parse, GenerateFn Generate, CompilerInvocation &RealInvocation, CompilerInvocation &DummyInvocation, ArrayRef<const char *> CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0) { // FIXME: Switch to '#ifndef NDEBUG' when possible. #ifdef CLANG_ROUND_TRIP_CC1_ARGS bool DoRoundTripDefault = true; #else bool DoRoundTripDefault = false; #endif bool DoRoundTrip = DoRoundTripDefault; for (const auto *Arg : CommandLineArgs) { if (Arg == StringRef("-round-trip-args")) DoRoundTrip = true; if (Arg == StringRef("-no-round-trip-args")) DoRoundTrip = false; } // If round-trip was not requested, simply run the parser with the real // invocation diagnostics. if (!DoRoundTrip) return Parse(RealInvocation, CommandLineArgs, Diags, Argv0); // Serializes quoted (and potentially escaped) arguments. auto SerializeArgs = [](ArrayRef<const char *> Args) { std::string Buffer; llvm::raw_string_ostream OS(Buffer); for (const char *Arg : Args) { llvm::sys::printArg(OS, Arg, /*Quote=*/true); OS << ' '; } OS.flush(); return Buffer; }; // Setup a dummy DiagnosticsEngine. DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions()); DummyDiags.setClient(new TextDiagnosticBuffer()); // Run the first parse on the original arguments with the dummy invocation and // diagnostics. if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) || DummyDiags.getNumWarnings() != 0) { // If the first parse did not succeed, it must be user mistake (invalid // command line arguments). We won't be able to generate arguments that // would reproduce the same result. Let's fail again with the real // invocation and diagnostics, so all side-effects of parsing are visible. unsigned NumWarningsBefore = Diags.getNumWarnings(); auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0); if (!Success || Diags.getNumWarnings() != NumWarningsBefore) return Success; // Parse with original options and diagnostics succeeded even though it // shouldn't have. Something is off. Diags.Report(diag::err_cc1_round_trip_fail_then_ok); Diags.Report(diag::note_cc1_round_trip_original) << SerializeArgs(CommandLineArgs); return false; } // Setup string allocator. llvm::BumpPtrAllocator Alloc; llvm::StringSaver StringPool(Alloc); auto SA = [&StringPool](const Twine &Arg) { return StringPool.save(Arg).data(); }; // Generate arguments from the dummy invocation. If Generate is the // inverse of Parse, the newly generated arguments must have the same // semantics as the original. SmallVector<const char *> GeneratedArgs1; Generate(DummyInvocation, GeneratedArgs1, SA); // Run the second parse, now on the generated arguments, and with the real // invocation and diagnostics. The result is what we will end up using for the // rest of compilation, so if Generate is not inverse of Parse, something down // the line will break. bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0); // The first parse on original arguments succeeded, but second parse of // generated arguments failed. Something must be wrong with the generator. if (!Success2) { Diags.Report(diag::err_cc1_round_trip_ok_then_fail); Diags.Report(diag::note_cc1_round_trip_generated) << 1 << SerializeArgs(GeneratedArgs1); return false; } // Generate arguments again, this time from the options we will end up using // for the rest of the compilation. SmallVector<const char *> GeneratedArgs2; Generate(RealInvocation, GeneratedArgs2, SA); // Compares two lists of generated arguments. auto Equal = [](const ArrayRef<const char *> A, const ArrayRef<const char *> B) { return std::equal(A.begin(), A.end(), B.begin(), B.end(), [](const char *AElem, const char *BElem) { return StringRef(AElem) == StringRef(BElem); }); }; // If we generated different arguments from what we assume are two // semantically equivalent CompilerInvocations, the Generate function may // be non-deterministic. if (!Equal(GeneratedArgs1, GeneratedArgs2)) { Diags.Report(diag::err_cc1_round_trip_mismatch); Diags.Report(diag::note_cc1_round_trip_generated) << 1 << SerializeArgs(GeneratedArgs1); Diags.Report(diag::note_cc1_round_trip_generated) << 2 << SerializeArgs(GeneratedArgs2); return false; } Diags.Report(diag::remark_cc1_round_trip_generated) << 1 << SerializeArgs(GeneratedArgs1); Diags.Report(diag::remark_cc1_round_trip_generated) << 2 << SerializeArgs(GeneratedArgs2); return Success2; } static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, OptSpecifier GroupWithValue, std::vector<std::string> &Diagnostics) { for (auto *A : Args.filtered(Group)) { if (A->getOption().getKind() == Option::FlagClass) { // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add // its name (minus the "W" or "R" at the beginning) to the diagnostics. Diagnostics.push_back( std::string(A->getOption().getName().drop_front(1))); } else if (A->getOption().matches(GroupWithValue)) { // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic // group. Add only the group name to the diagnostics. Diagnostics.push_back( std::string(A->getOption().getName().drop_front(1).rtrim("=-"))); } else { // Otherwise, add its value (for OPT_W_Joined and similar). Diagnostics.push_back(A->getValue()); } } } // Parse the Static Analyzer configuration. If \p Diags is set to nullptr, // it won't verify the input. static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, DiagnosticsEngine *Diags); static void getAllNoBuiltinFuncValues(ArgList &Args, std::vector<std::string> &Funcs) { std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_); auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) { return Builtin::Context::isBuiltinFunc(FuncName); }); Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd); } static void GenerateAnalyzerArgs(AnalyzerOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA) { const AnalyzerOptions *AnalyzerOpts = &Opts; #define ANALYZER_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef ANALYZER_OPTION_WITH_MARSHALLING if (Opts.AnalysisStoreOpt != RegionStoreModel) { switch (Opts.AnalysisStoreOpt) { #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \ case NAME##Model: \ GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA); \ break; #include "clang/StaticAnalyzer/Core/Analyses.def" default: llvm_unreachable("Tried to generate unknown analysis store."); } } if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) { switch (Opts.AnalysisConstraintsOpt) { #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ case NAME##Model: \ GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA); \ break; #include "clang/StaticAnalyzer/Core/Analyses.def" default: llvm_unreachable("Tried to generate unknown analysis constraint."); } } if (Opts.AnalysisDiagOpt != PD_HTML) { switch (Opts.AnalysisDiagOpt) { #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ case PD_##NAME: \ GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA); \ break; #include "clang/StaticAnalyzer/Core/Analyses.def" default: llvm_unreachable("Tried to generate unknown analysis diagnostic client."); } } if (Opts.AnalysisPurgeOpt != PurgeStmt) { switch (Opts.AnalysisPurgeOpt) { #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ case NAME: \ GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA); \ break; #include "clang/StaticAnalyzer/Core/Analyses.def" default: llvm_unreachable("Tried to generate unknown analysis purge mode."); } } if (Opts.InliningMode != NoRedundancy) { switch (Opts.InliningMode) { #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ case NAME: \ GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA); \ break; #include "clang/StaticAnalyzer/Core/Analyses.def" default: llvm_unreachable("Tried to generate unknown analysis inlining mode."); } } for (const auto &CP : Opts.CheckersAndPackages) { OptSpecifier Opt = CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker; GenerateArg(Args, Opt, CP.first, SA); } AnalyzerOptions ConfigOpts; parseAnalyzerConfigs(ConfigOpts, nullptr); for (const auto &C : Opts.Config) { // Don't generate anything that came from parseAnalyzerConfigs. It would be // redundant and may not be valid on the command line. auto Entry = ConfigOpts.Config.find(C.getKey()); if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue()) continue; GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA); } // Nothing to generate for FullCompilerInvocation. } static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags) { AnalyzerOptions *AnalyzerOpts = &Opts; bool Success = true; #define ANALYZER_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef ANALYZER_OPTION_WITH_MARSHALLING if (Arg *A = Args.getLastArg(OPT_analyzer_store)) { StringRef Name = A->getValue(); AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name) #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \ .Case(CMDFLAG, NAME##Model) #include "clang/StaticAnalyzer/Core/Analyses.def" .Default(NumStores); if (Value == NumStores) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } else { Opts.AnalysisStoreOpt = Value; } } if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { StringRef Name = A->getValue(); AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ .Case(CMDFLAG, NAME##Model) #include "clang/StaticAnalyzer/Core/Analyses.def" .Default(NumConstraints); if (Value == NumConstraints) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } else { Opts.AnalysisConstraintsOpt = Value; } } if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { StringRef Name = A->getValue(); AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ .Case(CMDFLAG, PD_##NAME) #include "clang/StaticAnalyzer/Core/Analyses.def" .Default(NUM_ANALYSIS_DIAG_CLIENTS); if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } else { Opts.AnalysisDiagOpt = Value; } } if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { StringRef Name = A->getValue(); AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ .Case(CMDFLAG, NAME) #include "clang/StaticAnalyzer/Core/Analyses.def" .Default(NumPurgeModes); if (Value == NumPurgeModes) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } else { Opts.AnalysisPurgeOpt = Value; } } if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { StringRef Name = A->getValue(); AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ .Case(CMDFLAG, NAME) #include "clang/StaticAnalyzer/Core/Analyses.def" .Default(NumInliningModes); if (Value == NumInliningModes) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } else { Opts.InliningMode = Value; } } Opts.CheckersAndPackages.clear(); for (const Arg *A : Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { A->claim(); bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker; // We can have a list of comma separated checker names, e.g: // '-analyzer-checker=cocoa,unix' StringRef CheckerAndPackageList = A->getValue(); SmallVector<StringRef, 16> CheckersAndPackages; CheckerAndPackageList.split(CheckersAndPackages, ","); for (const StringRef &CheckerOrPackage : CheckersAndPackages) Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage), IsEnabled); } // Go through the analyzer configuration options. for (const auto *A : Args.filtered(OPT_analyzer_config)) { // We can have a list of comma separated config names, e.g: // '-analyzer-config key1=val1,key2=val2' StringRef configList = A->getValue(); SmallVector<StringRef, 4> configVals; configList.split(configVals, ","); for (const auto &configVal : configVals) { StringRef key, val; std::tie(key, val) = configVal.split("="); if (val.empty()) { Diags.Report(SourceLocation(), diag::err_analyzer_config_no_value) << configVal; Success = false; break; } if (val.find('=') != StringRef::npos) { Diags.Report(SourceLocation(), diag::err_analyzer_config_multiple_values) << configVal; Success = false; break; } // TODO: Check checker options too, possibly in CheckerRegistry. // Leave unknown non-checker configs unclaimed. if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) { if (Opts.ShouldEmitErrorsOnInvalidConfigValue) { Diags.Report(diag::err_analyzer_config_unknown) << key; Success = false; } continue; } A->claim(); Opts.Config[key] = std::string(val); } } if (Opts.ShouldEmitErrorsOnInvalidConfigValue) parseAnalyzerConfigs(Opts, &Diags); else parseAnalyzerConfigs(Opts, nullptr); llvm::raw_string_ostream os(Opts.FullCompilerInvocation); for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) { if (i != 0) os << " "; os << Args.getArgString(i); } os.flush(); return Success; } static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config, StringRef OptionName, StringRef DefaultVal) { return Config.insert({OptionName, std::string(DefaultVal)}).first->second; } static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, StringRef &OptionField, StringRef Name, StringRef DefaultVal) { // String options may be known to invalid (e.g. if the expected string is a // file name, but the file does not exist), those will have to be checked in // parseConfigs. OptionField = getStringOption(Config, Name, DefaultVal); } static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, bool &OptionField, StringRef Name, bool DefaultVal) { auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>( getStringOption(Config, Name, (DefaultVal ? "true" : "false"))) .Case("true", true) .Case("false", false) .Default(None); if (!PossiblyInvalidVal) { if (Diags) Diags->Report(diag::err_analyzer_config_invalid_input) << Name << "a boolean"; else OptionField = DefaultVal; } else OptionField = PossiblyInvalidVal.getValue(); } static void initOption(AnalyzerOptions::ConfigTable &Config, DiagnosticsEngine *Diags, unsigned &OptionField, StringRef Name, unsigned DefaultVal) { OptionField = DefaultVal; bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal)) .getAsInteger(0, OptionField); if (Diags && HasFailed) Diags->Report(diag::err_analyzer_config_invalid_input) << Name << "an unsigned"; } static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts, DiagnosticsEngine *Diags) { // TODO: There's no need to store the entire configtable, it'd be plenty // enough tostore checker options. #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL); #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ SHALLOW_VAL, DEEP_VAL) \ switch (AnOpts.getUserMode()) { \ case UMK_Shallow: \ initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \ break; \ case UMK_Deep: \ initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \ break; \ } \ #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" #undef ANALYZER_OPTION #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE // At this point, AnalyzerOptions is configured. Let's validate some options. // FIXME: Here we try to validate the silenced checkers or packages are valid. // The current approach only validates the registered checkers which does not // contain the runtime enabled checkers and optimally we would validate both. if (!AnOpts.RawSilencedCheckersAndPackages.empty()) { std::vector<StringRef> Checkers = AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true); std::vector<StringRef> Packages = AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true); SmallVector<StringRef, 16> CheckersAndPackages; AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";"); for (const StringRef &CheckerOrPackage : CheckersAndPackages) { if (Diags) { bool IsChecker = CheckerOrPackage.contains('.'); bool IsValidName = IsChecker ? llvm::find(Checkers, CheckerOrPackage) != Checkers.end() : llvm::find(Packages, CheckerOrPackage) != Packages.end(); if (!IsValidName) Diags->Report(diag::err_unknown_analyzer_checker_or_package) << CheckerOrPackage; } AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage); } } if (!Diags) return; if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions) Diags->Report(diag::err_analyzer_config_invalid_input) << "track-conditions-debug" << "'track-conditions' to also be enabled"; if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir)) Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir" << "a filename"; if (!AnOpts.ModelPath.empty() && !llvm::sys::fs::is_directory(AnOpts.ModelPath)) Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path" << "a filename"; } /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`. static void GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA, OptSpecifier OptEQ, StringRef Name, const CodeGenOptions::OptRemark &Remark) { if (Remark.hasValidPattern()) { GenerateArg(Args, OptEQ, Remark.Pattern, SA); } else if (Remark.Kind == CodeGenOptions::RK_Enabled) { GenerateArg(Args, OPT_R_Joined, Name, SA); } else if (Remark.Kind == CodeGenOptions::RK_Disabled) { GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA); } } /// Parse a remark command line argument. It may be missing, disabled/enabled by /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'. /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'. static CodeGenOptions::OptRemark ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args, OptSpecifier OptEQ, StringRef Name) { CodeGenOptions::OptRemark Result; auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A) { Result.Pattern = A->getValue(); std::string RegexError; Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern); if (!Result.Regex->isValid(RegexError)) { Diags.Report(diag::err_drv_optimization_remark_pattern) << RegexError << A->getAsString(Args); return false; } return true; }; for (Arg *A : Args) { if (A->getOption().matches(OPT_R_Joined)) { StringRef Value = A->getValue(); if (Value == Name) Result.Kind = CodeGenOptions::RK_Enabled; else if (Value == "everything") Result.Kind = CodeGenOptions::RK_EnabledEverything; else if (Value.split('-') == std::make_pair(StringRef("no"), Name)) Result.Kind = CodeGenOptions::RK_Disabled; else if (Value == "no-everything") Result.Kind = CodeGenOptions::RK_DisabledEverything; } else if (A->getOption().matches(OptEQ)) { Result.Kind = CodeGenOptions::RK_WithPattern; if (!InitializeResultPattern(A)) return CodeGenOptions::OptRemark(); } } if (Result.Kind == CodeGenOptions::RK_Disabled || Result.Kind == CodeGenOptions::RK_DisabledEverything) { Result.Pattern = ""; Result.Regex = nullptr; } return Result; } static bool parseDiagnosticLevelMask(StringRef FlagName, const std::vector<std::string> &Levels, DiagnosticsEngine &Diags, DiagnosticLevelMask &M) { bool Success = true; for (const auto &Level : Levels) { DiagnosticLevelMask const PM = llvm::StringSwitch<DiagnosticLevelMask>(Level) .Case("note", DiagnosticLevelMask::Note) .Case("remark", DiagnosticLevelMask::Remark) .Case("warning", DiagnosticLevelMask::Warning) .Case("error", DiagnosticLevelMask::Error) .Default(DiagnosticLevelMask::None); if (PM == DiagnosticLevelMask::None) { Success = false; Diags.Report(diag::err_drv_invalid_value) << FlagName << Level; } M = M | PM; } return Success; } static void parseSanitizerKinds(StringRef FlagName, const std::vector<std::string> &Sanitizers, DiagnosticsEngine &Diags, SanitizerSet &S) { for (const auto &Sanitizer : Sanitizers) { SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); if (K == SanitizerMask()) Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; else S.set(K, true); } } static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) { SmallVector<StringRef, 4> Values; serializeSanitizerSet(S, Values); return Values; } static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle, ArgList &Args, DiagnosticsEngine &D, XRayInstrSet &S) { llvm::SmallVector<StringRef, 2> BundleParts; llvm::SplitString(Bundle, BundleParts, ","); for (const auto &B : BundleParts) { auto Mask = parseXRayInstrValue(B); if (Mask == XRayInstrKind::None) if (B != "none") D.Report(diag::err_drv_invalid_value) << FlagName << Bundle; else S.Mask = Mask; else if (Mask == XRayInstrKind::All) S.Mask = Mask; else S.set(Mask, true); } } static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) { llvm::SmallVector<StringRef, 2> BundleParts; serializeXRayInstrValue(S, BundleParts); std::string Buffer; llvm::raw_string_ostream OS(Buffer); llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ","); return OS.str(); } // Set the profile kind using fprofile-instrument-use-path. static void setPGOUseInstrumentor(CodeGenOptions &Opts, const Twine &ProfileName) { auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName); // In error, return silently and let Clang PGOUse report the error message. if (auto E = ReaderOrErr.takeError()) { llvm::consumeError(std::move(E)); Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); return; } std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader = std::move(ReaderOrErr.get()); if (PGOReader->isIRLevelProfile()) { if (PGOReader->hasCSIRLevelProfile()) Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr); else Opts.setProfileUse(CodeGenOptions::ProfileIRInstr); } else Opts.setProfileUse(CodeGenOptions::ProfileClangInstr); } void CompilerInvocation::GenerateCodeGenArgs( const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args, StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile, const LangOptions *LangOpts) { const CodeGenOptions &CodeGenOpts = Opts; if (Opts.OptimizationLevel == 0) GenerateArg(Args, OPT_O0, SA); else GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA); #define CODEGEN_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef CODEGEN_OPTION_WITH_MARSHALLING if (Opts.OptimizationLevel > 0) { if (Opts.Inlining == CodeGenOptions::NormalInlining) GenerateArg(Args, OPT_finline_functions, SA); else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining) GenerateArg(Args, OPT_finline_hint_functions, SA); else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining) GenerateArg(Args, OPT_fno_inline, SA); } if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0) GenerateArg(Args, OPT_fdirect_access_external_data, SA); else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0) GenerateArg(Args, OPT_fno_direct_access_external_data, SA); Optional<StringRef> DebugInfoVal; switch (Opts.DebugInfo) { case codegenoptions::DebugLineTablesOnly: DebugInfoVal = "line-tables-only"; break; case codegenoptions::DebugDirectivesOnly: DebugInfoVal = "line-directives-only"; break; case codegenoptions::DebugInfoConstructor: DebugInfoVal = "constructor"; break; case codegenoptions::LimitedDebugInfo: DebugInfoVal = "limited"; break; case codegenoptions::FullDebugInfo: DebugInfoVal = "standalone"; break; case codegenoptions::UnusedTypeInfo: DebugInfoVal = "unused-types"; break; case codegenoptions::NoDebugInfo: // default value DebugInfoVal = None; break; case codegenoptions::LocTrackingOnly: // implied value DebugInfoVal = None; break; } if (DebugInfoVal) GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA); if (Opts.DebugInfo == codegenoptions::DebugInfoConstructor) GenerateArg(Args, OPT_fuse_ctor_homing, SA); for (const auto &Prefix : Opts.DebugPrefixMap) GenerateArg(Args, OPT_fdebug_prefix_map_EQ, Prefix.first + "=" + Prefix.second, SA); for (const auto &Prefix : Opts.CoveragePrefixMap) GenerateArg(Args, OPT_fcoverage_prefix_map_EQ, Prefix.first + "=" + Prefix.second, SA); if (Opts.NewStructPathTBAA) GenerateArg(Args, OPT_new_struct_path_tbaa, SA); if (Opts.OptimizeSize == 1) GenerateArg(Args, OPT_O, "s", SA); else if (Opts.OptimizeSize == 2) GenerateArg(Args, OPT_O, "z", SA); // SimplifyLibCalls is set only in the absence of -fno-builtin and // -ffreestanding. We'll consider that when generating them. // NoBuiltinFuncs are generated by LangOptions. if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1) GenerateArg(Args, OPT_funroll_loops, SA); else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1) GenerateArg(Args, OPT_fno_unroll_loops, SA); if (!Opts.BinutilsVersion.empty()) GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA); if (Opts.DebugNameTable == static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU)) GenerateArg(Args, OPT_ggnu_pubnames, SA); else if (Opts.DebugNameTable == static_cast<unsigned>( llvm::DICompileUnit::DebugNameTableKind::Default)) GenerateArg(Args, OPT_gpubnames, SA); // ProfileInstrumentUsePath is marshalled automatically, no need to generate // it or PGOUseInstrumentor. if (Opts.TimePasses) { if (Opts.TimePassesPerRun) GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA); else GenerateArg(Args, OPT_ftime_report, SA); } if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO) GenerateArg(Args, OPT_flto, SA); if (Opts.PrepareForThinLTO) GenerateArg(Args, OPT_flto_EQ, "thin", SA); if (!Opts.ThinLTOIndexFile.empty()) GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA); if (Opts.SaveTempsFilePrefix == OutputFile) GenerateArg(Args, OPT_save_temps_EQ, "obj", SA); StringRef MemProfileBasename("memprof.profraw"); if (!Opts.MemoryProfileOutput.empty()) { if (Opts.MemoryProfileOutput == MemProfileBasename) { GenerateArg(Args, OPT_fmemory_profile, SA); } else { size_t ArgLength = Opts.MemoryProfileOutput.size() - MemProfileBasename.size(); GenerateArg(Args, OPT_fmemory_profile_EQ, Opts.MemoryProfileOutput.substr(0, ArgLength), SA); } } if (memcmp(Opts.CoverageVersion, "408*", 4) != 0) GenerateArg(Args, OPT_coverage_version_EQ, StringRef(Opts.CoverageVersion, 4), SA); // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely // '-fembed_bitcode', which does not map to any CompilerInvocation field and // won't be generated.) if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) { std::string InstrBundle = serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle); if (!InstrBundle.empty()) GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA); } if (Opts.CFProtectionReturn && Opts.CFProtectionBranch) GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA); else if (Opts.CFProtectionReturn) GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA); else if (Opts.CFProtectionBranch) GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA); for (const auto &F : Opts.LinkBitcodeFiles) { bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded && F.PropagateAttrs && F.Internalize; GenerateArg(Args, Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file, F.Filename, SA); } // TODO: Consider removing marshalling annotations from f[no_]emulated_tls. // That would make it easy to generate the option only **once** if it was // explicitly set to non-default value. if (Opts.ExplicitEmulatedTLS) { GenerateArg( Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA); } if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE()) GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA); if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()) GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(), SA); if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) { OptSpecifier Opt = T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return; GenerateArg(Args, Opt, SA); } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) { OptSpecifier Opt = T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return; GenerateArg(Args, Opt, SA); } if (Opts.EnableAIXExtendedAltivecABI) GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA); if (!Opts.OptRecordPasses.empty()) GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA); if (!Opts.OptRecordFormat.empty()) GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA); GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass", Opts.OptimizationRemark); GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed", Opts.OptimizationRemarkMissed); GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis", Opts.OptimizationRemarkAnalysis); GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ, Opts.DiagnosticsHotnessThreshold ? Twine(*Opts.DiagnosticsHotnessThreshold) : "auto", SA); for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover)) GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA); for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap)) GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA); if (!Opts.EmitVersionIdentMetadata) GenerateArg(Args, OPT_Qn, SA); switch (Opts.FiniteLoops) { case CodeGenOptions::FiniteLoopsKind::Language: break; case CodeGenOptions::FiniteLoopsKind::Always: GenerateArg(Args, OPT_ffinite_loops, SA); break; case CodeGenOptions::FiniteLoopsKind::Never: GenerateArg(Args, OPT_fno_finite_loops, SA); break; } } bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, DiagnosticsEngine &Diags, const llvm::Triple &T, const std::string &OutputFile, const LangOptions &LangOptsRef) { unsigned NumErrorsBefore = Diags.getNumErrors(); bool Success = true; unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); // TODO: This could be done in Driver unsigned MaxOptLevel = 3; if (OptimizationLevel > MaxOptLevel) { // If the optimization level is not supported, fall back on the default // optimization Diags.Report(diag::warn_drv_optimization_value) << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; OptimizationLevel = MaxOptLevel; } Opts.OptimizationLevel = OptimizationLevel; // The key paths of codegen options defined in Options.td start with // "CodeGenOpts.". Let's provide the expected variable name and type. CodeGenOptions &CodeGenOpts = Opts; // Some codegen options depend on language options. Let's provide the expected // variable name and type. const LangOptions *LangOpts = &LangOptsRef; #define CODEGEN_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef CODEGEN_OPTION_WITH_MARSHALLING // At O0 we want to fully disable inlining outside of cases marked with // 'alwaysinline' that are required for correctness. Opts.setInlining((Opts.OptimizationLevel == 0) ? CodeGenOptions::OnlyAlwaysInlining : CodeGenOptions::NormalInlining); // Explicit inlining flags can disable some or all inlining even at // optimization levels above zero. if (Arg *InlineArg = Args.getLastArg( options::OPT_finline_functions, options::OPT_finline_hint_functions, options::OPT_fno_inline_functions, options::OPT_fno_inline)) { if (Opts.OptimizationLevel > 0) { const Option &InlineOpt = InlineArg->getOption(); if (InlineOpt.matches(options::OPT_finline_functions)) Opts.setInlining(CodeGenOptions::NormalInlining); else if (InlineOpt.matches(options::OPT_finline_hint_functions)) Opts.setInlining(CodeGenOptions::OnlyHintInlining); else Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining); } } // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to // -fdirect-access-external-data. Opts.DirectAccessExternalData = Args.hasArg(OPT_fdirect_access_external_data) || (!Args.hasArg(OPT_fno_direct_access_external_data) && LangOpts->PICLevel == 0); if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) { unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) .Case("line-tables-only", codegenoptions::DebugLineTablesOnly) .Case("line-directives-only", codegenoptions::DebugDirectivesOnly) .Case("constructor", codegenoptions::DebugInfoConstructor) .Case("limited", codegenoptions::LimitedDebugInfo) .Case("standalone", codegenoptions::FullDebugInfo) .Case("unused-types", codegenoptions::UnusedTypeInfo) .Default(~0U); if (Val == ~0U) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); else Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val)); } // If -fuse-ctor-homing is set and limited debug info is already on, then use // constructor homing. if (Args.getLastArg(OPT_fuse_ctor_homing)) if (Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo) Opts.setDebugInfo(codegenoptions::DebugInfoConstructor); for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) { auto Split = StringRef(Arg).split('='); Opts.DebugPrefixMap.insert( {std::string(Split.first), std::string(Split.second)}); } for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) { auto Split = StringRef(Arg).split('='); Opts.CoveragePrefixMap.insert( {std::string(Split.first), std::string(Split.second)}); } const llvm::Triple::ArchType DebugEntryValueArchs[] = { llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64, llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips, llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el}; if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() && llvm::is_contained(DebugEntryValueArchs, T.getArch())) Opts.EmitCallSiteInfo = true; Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) && Args.hasArg(OPT_new_struct_path_tbaa); Opts.OptimizeSize = getOptimizationLevelSize(Args); Opts.SimplifyLibCalls = !LangOpts->NoBuiltin; if (Opts.SimplifyLibCalls) Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs; Opts.UnrollLoops = Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, (Opts.OptimizationLevel > 1)); Opts.BinutilsVersion = std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ)); Opts.DebugNameTable = static_cast<unsigned>( Args.hasArg(OPT_ggnu_pubnames) ? llvm::DICompileUnit::DebugNameTableKind::GNU : Args.hasArg(OPT_gpubnames) ? llvm::DICompileUnit::DebugNameTableKind::Default : llvm::DICompileUnit::DebugNameTableKind::None); if (!Opts.ProfileInstrumentUsePath.empty()) setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath); if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) { Opts.TimePasses = true; // -ftime-report= is only for new pass manager. if (A->getOption().getID() == OPT_ftime_report_EQ) { if (Opts.LegacyPassManager) Diags.Report(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) << "-fno-legacy-pass-manager"; StringRef Val = A->getValue(); if (Val == "per-pass") Opts.TimePassesPerRun = false; else if (Val == "per-pass-run") Opts.TimePassesPerRun = true; else Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); } } Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ); Opts.PrepareForThinLTO = false; if (Arg *A = Args.getLastArg(OPT_flto_EQ)) { StringRef S = A->getValue(); if (S == "thin") Opts.PrepareForThinLTO = true; else if (S != "full") Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S; } if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { if (IK.getLanguage() != Language::LLVM_IR) Diags.Report(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) << "-x ir"; Opts.ThinLTOIndexFile = std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ)); } if (Arg *A = Args.getLastArg(OPT_save_temps_EQ)) Opts.SaveTempsFilePrefix = llvm::StringSwitch<std::string>(A->getValue()) .Case("obj", OutputFile) .Default(llvm::sys::path::filename(OutputFile).str()); // The memory profile runtime appends the pid to make this name more unique. const char *MemProfileBasename = "memprof.profraw"; if (Args.hasArg(OPT_fmemory_profile_EQ)) { SmallString<128> Path( std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ))); llvm::sys::path::append(Path, MemProfileBasename); Opts.MemoryProfileOutput = std::string(Path); } else if (Args.hasArg(OPT_fmemory_profile)) Opts.MemoryProfileOutput = MemProfileBasename; memcpy(Opts.CoverageVersion, "408*", 4); if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) { if (Args.hasArg(OPT_coverage_version_EQ)) { StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); if (CoverageVersion.size() != 4) { Diags.Report(diag::err_drv_invalid_value) << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) << CoverageVersion; } else { memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); } } } // FIXME: For backend options that are not yet recorded as function // attributes in the IR, keep track of them so we can embed them in a // separate data section and use them when building the bitcode. for (const auto &A : Args) { // Do not encode output and input. if (A->getOption().getID() == options::OPT_o || A->getOption().getID() == options::OPT_INPUT || A->getOption().getID() == options::OPT_x || A->getOption().getID() == options::OPT_fembed_bitcode || A->getOption().matches(options::OPT_W_Group)) continue; ArgStringList ASL; A->render(Args, ASL); for (const auto &arg : ASL) { StringRef ArgStr(arg); Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end()); // using \00 to separate each commandline options. Opts.CmdArgs.push_back('\0'); } } auto XRayInstrBundles = Args.getAllArgValues(OPT_fxray_instrumentation_bundle); if (XRayInstrBundles.empty()) Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All; else for (const auto &A : XRayInstrBundles) parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args, Diags, Opts.XRayInstrumentationBundle); if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { StringRef Name = A->getValue(); if (Name == "full") { Opts.CFProtectionReturn = 1; Opts.CFProtectionBranch = 1; } else if (Name == "return") Opts.CFProtectionReturn = 1; else if (Name == "branch") Opts.CFProtectionBranch = 1; else if (Name != "none") { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; Success = false; } } for (auto *A : Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) { CodeGenOptions::BitcodeFileToLink F; F.Filename = A->getValue(); if (A->getOption().matches(OPT_mlink_builtin_bitcode)) { F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded; // When linking CUDA bitcode, propagate function attributes so that // e.g. libdevice gets fast-math attrs if we're building with fast-math. F.PropagateAttrs = true; F.Internalize = true; } Opts.LinkBitcodeFiles.push_back(F); } if (Args.getLastArg(OPT_femulated_tls) || Args.getLastArg(OPT_fno_emulated_tls)) { Opts.ExplicitEmulatedTLS = true; } if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) { StringRef Val = A->getValue(); Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val); if (!Opts.FPDenormalMode.isValid()) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; } if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) { StringRef Val = A->getValue(); Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val); if (!Opts.FP32DenormalMode.isValid()) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; } // X86_32 has -fppc-struct-return and -freg-struct-return. // PPC32 has -maix-struct-return and -msvr4-struct-return. if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return, OPT_maix_struct_return, OPT_msvr4_struct_return)) { // TODO: We might want to consider enabling these options on AIX in the // future. if (T.isOSAIX()) Diags.Report(diag::err_drv_unsupported_opt_for_target) << A->getSpelling() << T.str(); const Option &O = A->getOption(); if (O.matches(OPT_fpcc_struct_return) || O.matches(OPT_maix_struct_return)) { Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); } else { assert(O.matches(OPT_freg_struct_return) || O.matches(OPT_msvr4_struct_return)); Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); } } if (Arg *A = Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) { if (!T.isOSAIX()) Diags.Report(diag::err_drv_unsupported_opt_for_target) << A->getSpelling() << T.str(); const Option &O = A->getOption(); if (O.matches(OPT_mabi_EQ_vec_default)) Diags.Report(diag::err_aix_default_altivec_abi) << A->getSpelling() << T.str(); else { assert(O.matches(OPT_mabi_EQ_vec_extabi)); Opts.EnableAIXExtendedAltivecABI = 1; } } bool NeedLocTracking = false; if (!Opts.OptRecordFile.empty()) NeedLocTracking = true; if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) { Opts.OptRecordPasses = A->getValue(); NeedLocTracking = true; } if (Arg *A = Args.getLastArg(OPT_opt_record_format)) { Opts.OptRecordFormat = A->getValue(); NeedLocTracking = true; } Opts.OptimizationRemark = ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass"); Opts.OptimizationRemarkMissed = ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed"); Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark( Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis"); NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() || Opts.OptimizationRemarkMissed.hasValidPattern() || Opts.OptimizationRemarkAnalysis.hasValidPattern(); bool UsingSampleProfile = !Opts.SampleProfileFile.empty(); bool UsingProfile = UsingSampleProfile || (Opts.getProfileUse() != CodeGenOptions::ProfileNone); if (Opts.DiagnosticsWithHotness && !UsingProfile && // An IR file will contain PGO as metadata IK.getLanguage() != Language::LLVM_IR) Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) << "-fdiagnostics-show-hotness"; // Parse remarks hotness threshold. Valid value is either integer or 'auto'. if (auto *arg = Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { auto ResultOrErr = llvm::remarks::parseHotnessThresholdOption(arg->getValue()); if (!ResultOrErr) { Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold) << "-fdiagnostics-hotness-threshold="; } else { Opts.DiagnosticsHotnessThreshold = *ResultOrErr; if ((!Opts.DiagnosticsHotnessThreshold.hasValue() || Opts.DiagnosticsHotnessThreshold.getValue() > 0) && !UsingProfile) Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo) << "-fdiagnostics-hotness-threshold="; } } // If the user requested to use a sample profile for PGO, then the // backend will need to track source location information so the profile // can be incorporated into the IR. if (UsingSampleProfile) NeedLocTracking = true; // If the user requested a flag that requires source locations available in // the backend, make sure that the backend tracks source location information. if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo) Opts.setDebugInfo(codegenoptions::LocTrackingOnly); // Parse -fsanitize-recover= arguments. // FIXME: Report unrecoverable sanitizers incorrectly specified here. parseSanitizerKinds("-fsanitize-recover=", Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, Opts.SanitizeRecover); parseSanitizerKinds("-fsanitize-trap=", Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, Opts.SanitizeTrap); Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true); if (Args.hasArg(options::OPT_ffinite_loops)) Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always; else if (Args.hasArg(options::OPT_fno_finite_loops)) Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never; return Success && Diags.getNumErrors() == NumErrorsBefore; } static void GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA) { const DependencyOutputOptions &DependencyOutputOpts = Opts; #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING if (Opts.ShowIncludesDest != ShowIncludesDestination::None) GenerateArg(Args, OPT_show_includes, SA); for (const auto &Dep : Opts.ExtraDeps) { switch (Dep.second) { case EDK_SanitizeBlacklist: // Sanitizer blacklist arguments are generated from LanguageOptions. continue; case EDK_ModuleFile: // Module file arguments are generated from FrontendOptions and // HeaderSearchOptions. continue; case EDK_ProfileList: // Profile list arguments are generated from LanguageOptions via the // marshalling infrastructure. continue; case EDK_DepFileEntry: GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA); break; } } } static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, bool ShowLineMarkers) { unsigned NumErrorsBefore = Diags.getNumErrors(); bool Success = true; DependencyOutputOptions &DependencyOutputOpts = Opts; #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING if (Args.hasArg(OPT_show_includes)) { // Writing both /showIncludes and preprocessor output to stdout // would produce interleaved output, so use stderr for /showIncludes. // This behaves the same as cl.exe, when /E, /EP or /P are passed. if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers) Opts.ShowIncludesDest = ShowIncludesDestination::Stderr; else Opts.ShowIncludesDest = ShowIncludesDestination::Stdout; } else { Opts.ShowIncludesDest = ShowIncludesDestination::None; } // Add sanitizer blacklists as extra dependencies. // They won't be discovered by the regular preprocessor, so // we let make / ninja to know about this implicit dependency. if (!Args.hasArg(OPT_fno_sanitize_blacklist)) { for (const auto *A : Args.filtered(OPT_fsanitize_blacklist)) { StringRef Val = A->getValue(); if (Val.find('=') == StringRef::npos) Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeBlacklist); } if (Opts.IncludeSystemHeaders) { for (const auto *A : Args.filtered(OPT_fsanitize_system_blacklist)) { StringRef Val = A->getValue(); if (Val.find('=') == StringRef::npos) Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeBlacklist); } } } // -fprofile-list= dependencies. for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ)) Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList); // Propagate the extra dependencies. for (const auto *A : Args.filtered(OPT_fdepfile_entry)) Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry); // Only the -fmodule-file=<file> form. for (const auto *A : Args.filtered(OPT_fmodule_file)) { StringRef Val = A->getValue(); if (Val.find('=') == StringRef::npos) Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile); } return Success && Diags.getNumErrors() == NumErrorsBefore; } static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) { // Color diagnostics default to auto ("on" if terminal supports) in the driver // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. // Support both clang's -f[no-]color-diagnostics and gcc's // -f[no-]diagnostics-colors[=never|always|auto]. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = DefaultColor ? Colors_Auto : Colors_Off; for (auto *A : Args) { const Option &O = A->getOption(); if (O.matches(options::OPT_fcolor_diagnostics) || O.matches(options::OPT_fdiagnostics_color)) { ShowColors = Colors_On; } else if (O.matches(options::OPT_fno_color_diagnostics) || O.matches(options::OPT_fno_diagnostics_color)) { ShowColors = Colors_Off; } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) { StringRef Value(A->getValue()); if (Value == "always") ShowColors = Colors_On; else if (Value == "never") ShowColors = Colors_Off; else if (Value == "auto") ShowColors = Colors_Auto; } } return ShowColors == Colors_On || (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()); } static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes, DiagnosticsEngine &Diags) { bool Success = true; for (const auto &Prefix : VerifyPrefixes) { // Every prefix must start with a letter and contain only alphanumeric // characters, hyphens, and underscores. auto BadChar = llvm::find_if(Prefix, [](char C) { return !isAlphanumeric(C) && C != '-' && C != '_'; }); if (BadChar != Prefix.end() || !isLetter(Prefix[0])) { Success = false; Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix; Diags.Report(diag::note_drv_verify_prefix_spelling); } } return Success; } static void GenerateFileSystemArgs(const FileSystemOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA) { const FileSystemOptions &FileSystemOpts = Opts; #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING } static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags) { FileSystemOptions &FileSystemOpts = Opts; bool Success = true; #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING return Success; } static void GenerateMigratorArgs(const MigratorOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA) { const MigratorOptions &MigratorOpts = Opts; #define MIGRATOR_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef MIGRATOR_OPTION_WITH_MARSHALLING } static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args, DiagnosticsEngine &Diags) { MigratorOptions &MigratorOpts = Opts; bool Success = true; #define MIGRATOR_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef MIGRATOR_OPTION_WITH_MARSHALLING return Success; } void CompilerInvocation::GenerateDiagnosticArgs( const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args, StringAllocator SA, bool DefaultDiagColor) { const DiagnosticOptions *DiagnosticOpts = &Opts; #define DIAG_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef DIAG_OPTION_WITH_MARSHALLING if (!Opts.DiagnosticSerializationFile.empty()) GenerateArg(Args, OPT_diagnostic_serialized_file, Opts.DiagnosticSerializationFile, SA); if (Opts.ShowColors) GenerateArg(Args, OPT_fcolor_diagnostics, SA); if (Opts.VerifyDiagnostics && llvm::is_contained(Opts.VerifyPrefixes, "expected")) GenerateArg(Args, OPT_verify, SA); for (const auto &Prefix : Opts.VerifyPrefixes) if (Prefix != "expected") GenerateArg(Args, OPT_verify_EQ, Prefix, SA); DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected(); if (VIU == DiagnosticLevelMask::None) { // This is the default, don't generate anything. } else if (VIU == DiagnosticLevelMask::All) { GenerateArg(Args, OPT_verify_ignore_unexpected, SA); } else { if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0) GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA); if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0) GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA); if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0) GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA); if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0) GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA); } for (const auto &Warning : Opts.Warnings) { // This option is automatically generated from UndefPrefixes. if (Warning == "undef-prefix") continue; Args.push_back(SA(StringRef("-W") + Warning)); } for (const auto &Remark : Opts.Remarks) { // These arguments are generated from OptimizationRemark fields of // CodeGenOptions. StringRef IgnoredRemarks[] = {"pass", "no-pass", "pass-analysis", "no-pass-analysis", "pass-missed", "no-pass-missed"}; if (llvm::is_contained(IgnoredRemarks, Remark)) continue; Args.push_back(SA(StringRef("-R") + Remark)); } } bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, DiagnosticsEngine *Diags, bool DefaultDiagColor) { Optional<DiagnosticsEngine> IgnoringDiags; if (!Diags) { IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(), new IgnoringDiagConsumer()); Diags = &*IgnoringDiags; } // The key paths of diagnostic options defined in Options.td start with // "DiagnosticOpts->". Let's provide the expected variable name and type. DiagnosticOptions *DiagnosticOpts = &Opts; bool Success = true; #define DIAG_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, *Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef DIAG_OPTION_WITH_MARSHALLING llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes); if (Arg *A = Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) Opts.DiagnosticSerializationFile = A->getValue(); Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor); Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ); Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ); if (Args.hasArg(OPT_verify)) Opts.VerifyPrefixes.push_back("expected"); // Keep VerifyPrefixes in its original order for the sake of diagnostics, and // then sort it to prepare for fast lookup using std::binary_search. if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags)) { Opts.VerifyDiagnostics = false; Success = false; } else llvm::sort(Opts.VerifyPrefixes); DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask); if (Args.hasArg(OPT_verify_ignore_unexpected)) DiagMask = DiagnosticLevelMask::All; Opts.setVerifyIgnoreUnexpected(DiagMask); if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { Opts.TabStop = DiagnosticOptions::DefaultTabStop; Diags->Report(diag::warn_ignoring_ftabstop_value) << Opts.TabStop << DiagnosticOptions::DefaultTabStop; } addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); return Success; } /// Parse the argument to the -ftest-module-file-extension /// command-line argument. /// /// \returns true on error, false on success. static bool parseTestModuleFileExtensionArg(StringRef Arg, std::string &BlockName, unsigned &MajorVersion, unsigned &MinorVersion, bool &Hashed, std::string &UserInfo) { SmallVector<StringRef, 5> Args; Arg.split(Args, ':', 5); if (Args.size() < 5) return true; BlockName = std::string(Args[0]); if (Args[1].getAsInteger(10, MajorVersion)) return true; if (Args[2].getAsInteger(10, MinorVersion)) return true; if (Args[3].getAsInteger(2, Hashed)) return true; if (Args.size() > 4) UserInfo = std::string(Args[4]); return false; } /// Return a table that associates command line option specifiers with the /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is /// intentionally missing, as this case is handled separately from other /// frontend options. static const auto &getFrontendActionTable() { static const std::pair<frontend::ActionKind, unsigned> Table[] = { {frontend::ASTDeclList, OPT_ast_list}, {frontend::ASTDump, OPT_ast_dump_all_EQ}, {frontend::ASTDump, OPT_ast_dump_all}, {frontend::ASTDump, OPT_ast_dump_EQ}, {frontend::ASTDump, OPT_ast_dump}, {frontend::ASTDump, OPT_ast_dump_lookups}, {frontend::ASTDump, OPT_ast_dump_decl_types}, {frontend::ASTPrint, OPT_ast_print}, {frontend::ASTView, OPT_ast_view}, {frontend::DumpCompilerOptions, OPT_compiler_options_dump}, {frontend::DumpRawTokens, OPT_dump_raw_tokens}, {frontend::DumpTokens, OPT_dump_tokens}, {frontend::EmitAssembly, OPT_S}, {frontend::EmitBC, OPT_emit_llvm_bc}, {frontend::EmitHTML, OPT_emit_html}, {frontend::EmitLLVM, OPT_emit_llvm}, {frontend::EmitLLVMOnly, OPT_emit_llvm_only}, {frontend::EmitCodeGenOnly, OPT_emit_codegen_only}, {frontend::EmitCodeGenOnly, OPT_emit_codegen_only}, {frontend::EmitObj, OPT_emit_obj}, {frontend::FixIt, OPT_fixit_EQ}, {frontend::FixIt, OPT_fixit}, {frontend::GenerateModule, OPT_emit_module}, {frontend::GenerateModuleInterface, OPT_emit_module_interface}, {frontend::GenerateHeaderModule, OPT_emit_header_module}, {frontend::GeneratePCH, OPT_emit_pch}, {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs}, {frontend::InitOnly, OPT_init_only}, {frontend::ParseSyntaxOnly, OPT_fsyntax_only}, {frontend::ModuleFileInfo, OPT_module_file_info}, {frontend::VerifyPCH, OPT_verify_pch}, {frontend::PrintPreamble, OPT_print_preamble}, {frontend::PrintPreprocessedInput, OPT_E}, {frontend::TemplightDump, OPT_templight_dump}, {frontend::RewriteMacros, OPT_rewrite_macros}, {frontend::RewriteObjC, OPT_rewrite_objc}, {frontend::RewriteTest, OPT_rewrite_test}, {frontend::RunAnalysis, OPT_analyze}, {frontend::MigrateSource, OPT_migrate}, {frontend::RunPreprocessorOnly, OPT_Eonly}, {frontend::PrintDependencyDirectivesSourceMinimizerOutput, OPT_print_dependency_directives_minimized_source}, }; return Table; } /// Maps command line option to frontend action. static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) { for (const auto &ActionOpt : getFrontendActionTable()) if (ActionOpt.second == Opt.getID()) return ActionOpt.first; return None; } /// Maps frontend action to command line option. static Optional<OptSpecifier> getProgramActionOpt(frontend::ActionKind ProgramAction) { for (const auto &ActionOpt : getFrontendActionTable()) if (ActionOpt.first == ProgramAction) return OptSpecifier(ActionOpt.second); return None; } static void GenerateFrontendArgs(const FrontendOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA, bool IsHeader) { const FrontendOptions &FrontendOpts = Opts; #define FRONTEND_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef FRONTEND_OPTION_WITH_MARSHALLING Optional<OptSpecifier> ProgramActionOpt = getProgramActionOpt(Opts.ProgramAction); // Generating a simple flag covers most frontend actions. std::function<void()> GenerateProgramAction = [&]() { GenerateArg(Args, *ProgramActionOpt, SA); }; if (!ProgramActionOpt) { // PluginAction is the only program action handled separately. assert(Opts.ProgramAction == frontend::PluginAction && "Frontend action without option."); GenerateProgramAction = [&]() { GenerateArg(Args, OPT_plugin, Opts.ActionName, SA); }; } // FIXME: Simplify the complex 'AST dump' command line. if (Opts.ProgramAction == frontend::ASTDump) { GenerateProgramAction = [&]() { // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via // marshalling infrastructure. if (Opts.ASTDumpFormat != ADOF_Default) { StringRef Format; switch (Opts.ASTDumpFormat) { case ADOF_Default: llvm_unreachable("Default AST dump format."); case ADOF_JSON: Format = "json"; break; } if (Opts.ASTDumpAll) GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA); if (Opts.ASTDumpDecls) GenerateArg(Args, OPT_ast_dump_EQ, Format, SA); } else { if (Opts.ASTDumpAll) GenerateArg(Args, OPT_ast_dump_all, SA); if (Opts.ASTDumpDecls) GenerateArg(Args, OPT_ast_dump, SA); } }; } if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) { GenerateProgramAction = [&]() { GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA); }; } GenerateProgramAction(); for (const auto &PluginArgs : Opts.PluginArgs) for (const auto &PluginArg : PluginArgs.second) GenerateArg(Args, OPT_plugin_arg, PluginArgs.first + PluginArg, SA); for (const auto &Ext : Opts.ModuleFileExtensions) if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get())) GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA); if (!Opts.CodeCompletionAt.FileName.empty()) GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(), SA); for (const auto &Plugin : Opts.Plugins) GenerateArg(Args, OPT_load, Plugin, SA); // ASTDumpDecls and ASTDumpAll already handled with ProgramAction. for (const auto &ModuleFile : Opts.ModuleFiles) GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA); if (Opts.AuxTargetCPU.hasValue()) GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA); if (Opts.AuxTargetFeatures.hasValue()) for (const auto &Feature : *Opts.AuxTargetFeatures) GenerateArg(Args, OPT_aux_target_feature, Feature, SA); { StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : ""; StringRef ModuleMap = Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : ""; StringRef Header = IsHeader ? "-header" : ""; StringRef Lang; switch (Opts.DashX.getLanguage()) { case Language::C: Lang = "c"; break; case Language::OpenCL: Lang = "cl"; break; case Language::CUDA: Lang = "cuda"; break; case Language::HIP: Lang = "hip"; break; case Language::CXX: Lang = "c++"; break; case Language::ObjC: Lang = "objective-c"; break; case Language::ObjCXX: Lang = "objective-c++"; break; case Language::RenderScript: Lang = "renderscript"; break; case Language::Asm: Lang = "assembler-with-cpp"; break; case Language::Unknown: assert(Opts.DashX.getFormat() == InputKind::Precompiled && "Generating -x argument for unknown language (not precompiled)."); Lang = "ast"; break; case Language::LLVM_IR: Lang = "ir"; break; } GenerateArg(Args, OPT_x, Lang + Header + ModuleMap + Preprocessed, SA); } // OPT_INPUT has a unique class, generate it directly. for (const auto &Input : Opts.Inputs) Args.push_back(SA(Input.getFile())); } static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, bool &IsHeaderFile) { FrontendOptions &FrontendOpts = Opts; bool Success = true; unsigned NumErrorsBefore = Diags.getNumErrors(); #define FRONTEND_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef FRONTEND_OPTION_WITH_MARSHALLING Opts.ProgramAction = frontend::ParseSyntaxOnly; if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { OptSpecifier Opt = OptSpecifier(A->getOption().getID()); Optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt); assert(ProgramAction && "Option specifier not in Action_Group."); if (ProgramAction == frontend::ASTDump && (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) { unsigned Val = llvm::StringSwitch<unsigned>(A->getValue()) .CaseLower("default", ADOF_Default) .CaseLower("json", ADOF_JSON) .Default(std::numeric_limits<unsigned>::max()); if (Val != std::numeric_limits<unsigned>::max()) Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val); else { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); Opts.ASTDumpFormat = ADOF_Default; } } if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ) Opts.FixItSuffix = A->getValue(); if (ProgramAction == frontend::GenerateInterfaceStubs) { StringRef ArgStr = Args.hasArg(OPT_interface_stub_version_EQ) ? Args.getLastArgValue(OPT_interface_stub_version_EQ) : "experimental-ifs-v2"; if (ArgStr == "experimental-yaml-elf-v1" || ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-tapi-elf-v1") { std::string ErrorMessage = "Invalid interface stub format: " + ArgStr.str() + " is deprecated."; Diags.Report(diag::err_drv_invalid_value) << "Must specify a valid interface stub format type, ie: " "-interface-stub-version=experimental-ifs-v2" << ErrorMessage; ProgramAction = frontend::ParseSyntaxOnly; } else if (!ArgStr.startswith("experimental-ifs-")) { std::string ErrorMessage = "Invalid interface stub format: " + ArgStr.str() + "."; Diags.Report(diag::err_drv_invalid_value) << "Must specify a valid interface stub format type, ie: " "-interface-stub-version=experimental-ifs-v2" << ErrorMessage; ProgramAction = frontend::ParseSyntaxOnly; } } Opts.ProgramAction = *ProgramAction; } if (const Arg* A = Args.getLastArg(OPT_plugin)) { Opts.Plugins.emplace_back(A->getValue(0)); Opts.ProgramAction = frontend::PluginAction; Opts.ActionName = A->getValue(); } for (const auto *AA : Args.filtered(OPT_plugin_arg)) Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1)); for (const std::string &Arg : Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { std::string BlockName; unsigned MajorVersion; unsigned MinorVersion; bool Hashed; std::string UserInfo; if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)) { Diags.Report(diag::err_test_module_file_extension_format) << Arg; continue; } // Add the testing module file extension. Opts.ModuleFileExtensions.push_back( std::make_shared<TestModuleFileExtension>( BlockName, MajorVersion, MinorVersion, Hashed, UserInfo)); } if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { Opts.CodeCompletionAt = ParsedSourceLocation::FromString(A->getValue()); if (Opts.CodeCompletionAt.FileName.empty()) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); } Opts.Plugins = Args.getAllArgValues(OPT_load); Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ); Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ); // Only the -fmodule-file=<file> form. for (const auto *A : Args.filtered(OPT_fmodule_file)) { StringRef Val = A->getValue(); if (Val.find('=') == StringRef::npos) Opts.ModuleFiles.push_back(std::string(Val)); } if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule) Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module" << "-emit-module"; if (Args.hasArg(OPT_aux_target_cpu)) Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu)); if (Args.hasArg(OPT_aux_target_feature)) Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature); if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { Diags.Report(diag::err_drv_argument_not_allowed_with) << "ARC migration" << "ObjC migration"; } InputKind DashX(Language::Unknown); if (const Arg *A = Args.getLastArg(OPT_x)) { StringRef XValue = A->getValue(); // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'. // FIXME: Supporting '<lang>-header-cpp-output' would be useful. bool Preprocessed = XValue.consume_back("-cpp-output"); bool ModuleMap = XValue.consume_back("-module-map"); IsHeaderFile = !Preprocessed && !ModuleMap && XValue != "precompiled-header" && XValue.consume_back("-header"); // Principal languages. DashX = llvm::StringSwitch<InputKind>(XValue) .Case("c", Language::C) .Case("cl", Language::OpenCL) .Case("cuda", Language::CUDA) .Case("hip", Language::HIP) .Case("c++", Language::CXX) .Case("objective-c", Language::ObjC) .Case("objective-c++", Language::ObjCXX) .Case("renderscript", Language::RenderScript) .Default(Language::Unknown); // "objc[++]-cpp-output" is an acceptable synonym for // "objective-c[++]-cpp-output". if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap) DashX = llvm::StringSwitch<InputKind>(XValue) .Case("objc", Language::ObjC) .Case("objc++", Language::ObjCXX) .Default(Language::Unknown); // Some special cases cannot be combined with suffixes. if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile) DashX = llvm::StringSwitch<InputKind>(XValue) .Case("cpp-output", InputKind(Language::C).getPreprocessed()) .Case("assembler-with-cpp", Language::Asm) .Cases("ast", "pcm", "precompiled-header", InputKind(Language::Unknown, InputKind::Precompiled)) .Case("ir", Language::LLVM_IR) .Default(Language::Unknown); if (DashX.isUnknown()) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); if (Preprocessed) DashX = DashX.getPreprocessed(); if (ModuleMap) DashX = DashX.withFormat(InputKind::ModuleMap); } // '-' is the default input if none is given. std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); Opts.Inputs.clear(); if (Inputs.empty()) Inputs.push_back("-"); for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { InputKind IK = DashX; if (IK.isUnknown()) { IK = FrontendOptions::getInputKindForExtension( StringRef(Inputs[i]).rsplit('.').second); // FIXME: Warn on this? if (IK.isUnknown()) IK = Language::C; // FIXME: Remove this hack. if (i == 0) DashX = IK; } bool IsSystem = false; // The -emit-module action implicitly takes a module map. if (Opts.ProgramAction == frontend::GenerateModule && IK.getFormat() == InputKind::Source) { IK = IK.withFormat(InputKind::ModuleMap); IsSystem = Opts.IsSystemModule; } Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem); } Opts.DashX = DashX; return Diags.getNumErrors() == NumErrorsBefore; } std::string CompilerInvocation::GetResourcesPath(const char *Argv0, void *MainAddr) { std::string ClangExecutable = llvm::sys::fs::getMainExecutable(Argv0, MainAddr); return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR); } static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA) { const HeaderSearchOptions *HeaderSearchOpts = &Opts; #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING if (Opts.UseLibcxx) GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA); if (!Opts.ModuleCachePath.empty()) GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA); for (const auto &File : Opts.PrebuiltModuleFiles) GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA); for (const auto &Path : Opts.PrebuiltModulePaths) GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA); for (const auto &Macro : Opts.ModulesIgnoreMacros) GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA); auto Matches = [](const HeaderSearchOptions::Entry &Entry, llvm::ArrayRef<frontend::IncludeDirGroup> Groups, llvm::Optional<bool> IsFramework, llvm::Optional<bool> IgnoreSysRoot) { return llvm::find(Groups, Entry.Group) != Groups.end() && (!IsFramework || (Entry.IsFramework == *IsFramework)) && (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot)); }; auto It = Opts.UserEntries.begin(); auto End = Opts.UserEntries.end(); // Add -I..., -F..., and -index-header-map options in order. for (; It < End && Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true); ++It) { OptSpecifier Opt = [It, Matches]() { if (Matches(*It, frontend::IndexHeaderMap, true, true)) return OPT_F; if (Matches(*It, frontend::IndexHeaderMap, false, true)) return OPT_I; if (Matches(*It, frontend::Angled, true, true)) return OPT_F; if (Matches(*It, frontend::Angled, false, true)) return OPT_I; llvm_unreachable("Unexpected HeaderSearchOptions::Entry."); }(); if (It->Group == frontend::IndexHeaderMap) GenerateArg(Args, OPT_index_header_map, SA); GenerateArg(Args, Opt, It->Path, SA); }; // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may // have already been generated as "-I[xx]yy". If that's the case, their // position on command line was such that this has no semantic impact on // include paths. for (; It < End && Matches(*It, {frontend::After, frontend::Angled}, false, true); ++It) { OptSpecifier Opt = It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore; GenerateArg(Args, Opt, It->Path, SA); } // Note: Some paths that came from "-idirafter=xxyy" may have already been // generated as "-iwithprefix=xxyy". If that's the case, their position on // command line was such that this has no semantic impact on include paths. for (; It < End && Matches(*It, {frontend::After}, false, true); ++It) GenerateArg(Args, OPT_idirafter, It->Path, SA); for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It) GenerateArg(Args, OPT_iquote, It->Path, SA); for (; It < End && Matches(*It, {frontend::System}, false, None); ++It) GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot, It->Path, SA); for (; It < End && Matches(*It, {frontend::System}, true, true); ++It) GenerateArg(Args, OPT_iframework, It->Path, SA); for (; It < End && Matches(*It, {frontend::System}, true, false); ++It) GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA); // Add the paths for the various language specific isystem flags. for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It) GenerateArg(Args, OPT_c_isystem, It->Path, SA); for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It) GenerateArg(Args, OPT_cxx_isystem, It->Path, SA); for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It) GenerateArg(Args, OPT_objc_isystem, It->Path, SA); for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It) GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA); // Add the internal paths from a driver that detects standard include paths. // Note: Some paths that came from "-internal-isystem" arguments may have // already been generated as "-isystem". If that's the case, their position on // command line was such that this has no semantic impact on include paths. for (; It < End && Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true); ++It) { OptSpecifier Opt = It->Group == frontend::System ? OPT_internal_isystem : OPT_internal_externc_isystem; GenerateArg(Args, Opt, It->Path, SA); } assert(It == End && "Unhandled HeaderSearchOption::Entry."); // Add the path prefixes which are implicitly treated as being system headers. for (const auto &P : Opts.SystemHeaderPrefixes) { OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix : OPT_no_system_header_prefix; GenerateArg(Args, Opt, P.Prefix, SA); } for (const std::string &F : Opts.VFSOverlayFiles) GenerateArg(Args, OPT_ivfsoverlay, F, SA); } static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, const std::string &WorkingDir) { HeaderSearchOptions *HeaderSearchOpts = &Opts; bool Success = true; #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); // Canonicalize -fmodules-cache-path before storing it. SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path)); if (!(P.empty() || llvm::sys::path::is_absolute(P))) { if (WorkingDir.empty()) llvm::sys::fs::make_absolute(P); else llvm::sys::fs::make_absolute(WorkingDir, P); } llvm::sys::path::remove_dots(P); Opts.ModuleCachePath = std::string(P.str()); // Only the -fmodule-file=<name>=<file> form. for (const auto *A : Args.filtered(OPT_fmodule_file)) { StringRef Val = A->getValue(); if (Val.find('=') != StringRef::npos){ auto Split = Val.split('='); Opts.PrebuiltModuleFiles.insert( {std::string(Split.first), std::string(Split.second)}); } } for (const auto *A : Args.filtered(OPT_fprebuilt_module_path)) Opts.AddPrebuiltModulePath(A->getValue()); for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) { StringRef MacroDef = A->getValue(); Opts.ModulesIgnoreMacros.insert( llvm::CachedHashString(MacroDef.split('=').first)); } // Add -I..., -F..., and -index-header-map options in order. bool IsIndexHeaderMap = false; bool IsSysrootSpecified = Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot); for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { if (A->getOption().matches(OPT_index_header_map)) { // -index-header-map applies to the next -I or -F. IsIndexHeaderMap = true; continue; } frontend::IncludeDirGroup Group = IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; bool IsFramework = A->getOption().matches(OPT_F); std::string Path = A->getValue(); if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') { SmallString<32> Buffer; llvm::sys::path::append(Buffer, Opts.Sysroot, llvm::StringRef(A->getValue()).substr(1)); Path = std::string(Buffer.str()); } Opts.AddPath(Path, Group, IsFramework, /*IgnoreSysroot*/ true); IsIndexHeaderMap = false; } // Add -iprefix/-iwithprefix/-iwithprefixbefore options. StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. for (const auto *A : Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { if (A->getOption().matches(OPT_iprefix)) Prefix = A->getValue(); else if (A->getOption().matches(OPT_iwithprefix)) Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); else Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); } for (const auto *A : Args.filtered(OPT_idirafter)) Opts.AddPath(A->getValue(), frontend::After, false, true); for (const auto *A : Args.filtered(OPT_iquote)) Opts.AddPath(A->getValue(), frontend::Quoted, false, true); for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) Opts.AddPath(A->getValue(), frontend::System, false, !A->getOption().matches(OPT_iwithsysroot)); for (const auto *A : Args.filtered(OPT_iframework)) Opts.AddPath(A->getValue(), frontend::System, true, true); for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot)) Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true, /*IgnoreSysRoot=*/false); // Add the paths for the various language specific isystem flags. for (const auto *A : Args.filtered(OPT_c_isystem)) Opts.AddPath(A->getValue(), frontend::CSystem, false, true); for (const auto *A : Args.filtered(OPT_cxx_isystem)) Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); for (const auto *A : Args.filtered(OPT_objc_isystem)) Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); for (const auto *A : Args.filtered(OPT_objcxx_isystem)) Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); // Add the internal paths from a driver that detects standard include paths. for (const auto *A : Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { frontend::IncludeDirGroup Group = frontend::System; if (A->getOption().matches(OPT_internal_externc_isystem)) Group = frontend::ExternCSystem; Opts.AddPath(A->getValue(), Group, false, true); } // Add the path prefixes which are implicitly treated as being system headers. for (const auto *A : Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) Opts.AddSystemHeaderPrefix( A->getValue(), A->getOption().matches(OPT_system_header_prefix)); for (const auto *A : Args.filtered(OPT_ivfsoverlay)) Opts.AddVFSOverlayFile(A->getValue()); return Success; } void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, const llvm::Triple &T, std::vector<std::string> &Includes, LangStandard::Kind LangStd) { // Set some properties which depend solely on the input kind; it would be nice // to move these to the language standard, and have the driver resolve the // input kind + language standard. // // FIXME: Perhaps a better model would be for a single source file to have // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std) // simultaneously active? if (IK.getLanguage() == Language::Asm) { Opts.AsmPreprocessor = 1; } else if (IK.isObjectiveC()) { Opts.ObjC = 1; } if (LangStd == LangStandard::lang_unspecified) { // Based on the base language, pick one. switch (IK.getLanguage()) { case Language::Unknown: case Language::LLVM_IR: llvm_unreachable("Invalid input kind!"); case Language::OpenCL: LangStd = LangStandard::lang_opencl10; break; case Language::CUDA: LangStd = LangStandard::lang_cuda; break; case Language::Asm: case Language::C: #if defined(CLANG_DEFAULT_STD_C) LangStd = CLANG_DEFAULT_STD_C; #else // The PS4 uses C99 as the default C standard. if (T.isPS4()) LangStd = LangStandard::lang_gnu99; else LangStd = LangStandard::lang_gnu17; #endif break; case Language::ObjC: #if defined(CLANG_DEFAULT_STD_C) LangStd = CLANG_DEFAULT_STD_C; #else LangStd = LangStandard::lang_gnu11; #endif break; case Language::CXX: case Language::ObjCXX: #if defined(CLANG_DEFAULT_STD_CXX) LangStd = CLANG_DEFAULT_STD_CXX; #else LangStd = LangStandard::lang_gnucxx14; #endif break; case Language::RenderScript: LangStd = LangStandard::lang_c99; break; case Language::HIP: LangStd = LangStandard::lang_hip; break; } } const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); Opts.LangStd = LangStd; Opts.LineComment = Std.hasLineComments(); Opts.C99 = Std.isC99(); Opts.C11 = Std.isC11(); Opts.C17 = Std.isC17(); Opts.C2x = Std.isC2x(); Opts.CPlusPlus = Std.isCPlusPlus(); Opts.CPlusPlus11 = Std.isCPlusPlus11(); Opts.CPlusPlus14 = Std.isCPlusPlus14(); Opts.CPlusPlus17 = Std.isCPlusPlus17(); Opts.CPlusPlus20 = Std.isCPlusPlus20(); Opts.CPlusPlus2b = Std.isCPlusPlus2b(); Opts.GNUMode = Std.isGNUMode(); Opts.GNUCVersion = 0; Opts.HexFloats = Std.hasHexFloats(); Opts.ImplicitInt = Std.hasImplicitInt(); Opts.CPlusPlusModules = Opts.CPlusPlus20; // Set OpenCL Version. Opts.OpenCL = Std.isOpenCL(); if (LangStd == LangStandard::lang_opencl10) Opts.OpenCLVersion = 100; else if (LangStd == LangStandard::lang_opencl11) Opts.OpenCLVersion = 110; else if (LangStd == LangStandard::lang_opencl12) Opts.OpenCLVersion = 120; else if (LangStd == LangStandard::lang_opencl20) Opts.OpenCLVersion = 200; else if (LangStd == LangStandard::lang_opencl30) Opts.OpenCLVersion = 300; else if (LangStd == LangStandard::lang_openclcpp) Opts.OpenCLCPlusPlusVersion = 100; // OpenCL has some additional defaults. if (Opts.OpenCL) { Opts.AltiVec = 0; Opts.ZVector = 0; Opts.setDefaultFPContractMode(LangOptions::FPM_On); Opts.OpenCLCPlusPlus = Opts.CPlusPlus; Opts.OpenCLPipe = Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200; Opts.OpenCLGenericAddressSpace = Opts.OpenCLCPlusPlus || Opts.OpenCLVersion == 200; // Include default header file for OpenCL. if (Opts.IncludeDefaultHeader) { if (Opts.DeclareOpenCLBuiltins) { // Only include base header file for builtin types and constants. Includes.push_back("opencl-c-base.h"); } else { Includes.push_back("opencl-c.h"); } } } Opts.HIP = IK.getLanguage() == Language::HIP; Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP; if (Opts.HIP) { // HIP toolchain does not support 'Fast' FPOpFusion in backends since it // fuses multiplication/addition instructions without contract flag from // device library functions in LLVM bitcode, which causes accuracy loss in // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446. // For device library functions in bitcode to work, 'Strict' or 'Standard' // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas' // FP contract option is used to allow fuse across statements in frontend // whereas respecting contract flag in backend. Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); } else if (Opts.CUDA) { // Allow fuse across statements disregarding pragmas. Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); } Opts.RenderScript = IK.getLanguage() == Language::RenderScript; // OpenCL and C++ both have bool, true, false keywords. Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; // OpenCL has half keyword Opts.Half = Opts.OpenCL; } /// Check if input file kind and language standard are compatible. static bool IsInputCompatibleWithStandard(InputKind IK, const LangStandard &S) { switch (IK.getLanguage()) { case Language::Unknown: case Language::LLVM_IR: llvm_unreachable("should not parse language flags for this input"); case Language::C: case Language::ObjC: case Language::RenderScript: return S.getLanguage() == Language::C; case Language::OpenCL: return S.getLanguage() == Language::OpenCL; case Language::CXX: case Language::ObjCXX: return S.getLanguage() == Language::CXX; case Language::CUDA: // FIXME: What -std= values should be permitted for CUDA compilations? return S.getLanguage() == Language::CUDA || S.getLanguage() == Language::CXX; case Language::HIP: return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP; case Language::Asm: // Accept (and ignore) all -std= values. // FIXME: The -std= value is not ignored; it affects the tokenization // and preprocessing rules if we're preprocessing this asm input. return true; } llvm_unreachable("unexpected input language"); } /// Get language name for given input kind. static const StringRef GetInputKindName(InputKind IK) { switch (IK.getLanguage()) { case Language::C: return "C"; case Language::ObjC: return "Objective-C"; case Language::CXX: return "C++"; case Language::ObjCXX: return "Objective-C++"; case Language::OpenCL: return "OpenCL"; case Language::CUDA: return "CUDA"; case Language::RenderScript: return "RenderScript"; case Language::HIP: return "HIP"; case Language::Asm: return "Asm"; case Language::LLVM_IR: return "LLVM IR"; case Language::Unknown: break; } llvm_unreachable("unknown input language"); } void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts, SmallVectorImpl<const char *> &Args, StringAllocator SA, const llvm::Triple &T) { OptSpecifier StdOpt; switch (Opts.LangStd) { case LangStandard::lang_opencl10: case LangStandard::lang_opencl11: case LangStandard::lang_opencl12: case LangStandard::lang_opencl20: case LangStandard::lang_opencl30: case LangStandard::lang_openclcpp: StdOpt = OPT_cl_std_EQ; break; default: StdOpt = OPT_std_EQ; break; } auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd); GenerateArg(Args, StdOpt, LangStandard.getName(), SA); if (Opts.IncludeDefaultHeader) GenerateArg(Args, OPT_finclude_default_header, SA); if (Opts.DeclareOpenCLBuiltins) GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA); const LangOptions *LangOpts = &Opts; #define LANG_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef LANG_OPTION_WITH_MARSHALLING // The '-fcf-protection=' option is generated by CodeGenOpts generator. if (Opts.ObjC) { GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA); if (Opts.GC == LangOptions::GCOnly) GenerateArg(Args, OPT_fobjc_gc_only, SA); else if (Opts.GC == LangOptions::HybridGC) GenerateArg(Args, OPT_fobjc_gc, SA); else if (Opts.ObjCAutoRefCount == 1) GenerateArg(Args, OPT_fobjc_arc, SA); if (Opts.ObjCWeakRuntime) GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA); if (Opts.ObjCWeak) GenerateArg(Args, OPT_fobjc_weak, SA); if (Opts.ObjCSubscriptingLegacyRuntime) GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA); } if (Opts.GNUCVersion != 0) { unsigned Major = Opts.GNUCVersion / 100 / 100; unsigned Minor = (Opts.GNUCVersion / 100) % 100; unsigned Patch = Opts.GNUCVersion % 100; GenerateArg(Args, OPT_fgnuc_version_EQ, Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA); } if (Opts.IgnoreXCOFFVisibility) GenerateArg(Args, OPT_mignore_xcoff_visibility, SA); if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) { GenerateArg(Args, OPT_ftrapv, SA); GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA); } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) { GenerateArg(Args, OPT_fwrapv, SA); } if (Opts.MSCompatibilityVersion != 0) { unsigned Major = Opts.MSCompatibilityVersion / 10000000; unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100; unsigned Subminor = Opts.MSCompatibilityVersion % 100000; GenerateArg(Args, OPT_fms_compatibility_version, Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA); } if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) { if (!Opts.Trigraphs) GenerateArg(Args, OPT_fno_trigraphs, SA); } else { if (Opts.Trigraphs) GenerateArg(Args, OPT_ftrigraphs, SA); } if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200)) GenerateArg(Args, OPT_fblocks, SA); if (Opts.ConvergentFunctions && !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice)) GenerateArg(Args, OPT_fconvergent_functions, SA); if (Opts.NoBuiltin && !Opts.Freestanding) GenerateArg(Args, OPT_fno_builtin, SA); if (!Opts.NoBuiltin) for (const auto &Func : Opts.NoBuiltinFuncs) GenerateArg(Args, OPT_fno_builtin_, Func, SA); if (Opts.LongDoubleSize == 128) GenerateArg(Args, OPT_mlong_double_128, SA); else if (Opts.LongDoubleSize == 64) GenerateArg(Args, OPT_mlong_double_64, SA); // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='. // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or // '-fopenmp-targets='. if (Opts.OpenMP && !Opts.OpenMPSimd) { GenerateArg(Args, OPT_fopenmp, SA); if (Opts.OpenMP != 50) GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA); if (!Opts.OpenMPUseTLS) GenerateArg(Args, OPT_fnoopenmp_use_tls, SA); if (Opts.OpenMPIsDevice) GenerateArg(Args, OPT_fopenmp_is_device, SA); if (Opts.OpenMPIRBuilder) GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA); } if (Opts.OpenMPSimd) { GenerateArg(Args, OPT_fopenmp_simd, SA); if (Opts.OpenMP != 50) GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA); } if (Opts.OpenMPCUDANumSMs != 0) GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ, Twine(Opts.OpenMPCUDANumSMs), SA); if (Opts.OpenMPCUDABlocksPerSM != 0) GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ, Twine(Opts.OpenMPCUDABlocksPerSM), SA); if (Opts.OpenMPCUDAReductionBufNum != 1024) GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, Twine(Opts.OpenMPCUDAReductionBufNum), SA); if (!Opts.OMPTargetTriples.empty()) { std::string Targets; llvm::raw_string_ostream OS(Targets); llvm::interleave( Opts.OMPTargetTriples, OS, [&OS](const llvm::Triple &T) { OS << T.str(); }, ","); GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA); } if (!Opts.OMPHostIRFile.empty()) GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA); if (Opts.OpenMPCUDAMode) GenerateArg(Args, OPT_fopenmp_cuda_mode, SA); if (Opts.OpenMPCUDATargetParallel) GenerateArg(Args, OPT_fopenmp_cuda_parallel_target_regions, SA); if (Opts.OpenMPCUDAForceFullRuntime) GenerateArg(Args, OPT_fopenmp_cuda_force_full_runtime, SA); // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are // generated from CodeGenOptions. if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast) GenerateArg(Args, OPT_ffp_contract, "fast", SA); else if (Opts.DefaultFPContractMode == LangOptions::FPM_On) GenerateArg(Args, OPT_ffp_contract, "on", SA); else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off) GenerateArg(Args, OPT_ffp_contract, "off", SA); else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas) GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA); for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize)) GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA); // Conflating '-fsanitize-system-blacklist' and '-fsanitize-blacklist'. for (const std::string &F : Opts.NoSanitizeFiles) GenerateArg(Args, OPT_fsanitize_blacklist, F, SA); if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8) GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA); else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4) GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA); else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6) GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA); else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7) GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA); else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9) GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA); else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11) GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA); if (Opts.getSignReturnAddressScope() == LangOptions::SignReturnAddressScopeKind::All) GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA); else if (Opts.getSignReturnAddressScope() == LangOptions::SignReturnAddressScopeKind::NonLeaf) GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA); if (Opts.getSignReturnAddressKey() == LangOptions::SignReturnAddressKeyKind::BKey) GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA); } bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, const llvm::Triple &T, std::vector<std::string> &Includes, DiagnosticsEngine &Diags) { unsigned NumErrorsBefore = Diags.getNumErrors(); // FIXME: Cleanup per-file based stuff. LangStandard::Kind LangStd = LangStandard::lang_unspecified; if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { LangStd = LangStandard::getLangKind(A->getValue()); if (LangStd == LangStandard::lang_unspecified) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); // Report supported standards with short description. for (unsigned KindValue = 0; KindValue != LangStandard::lang_unspecified; ++KindValue) { const LangStandard &Std = LangStandard::getLangStandardForKind( static_cast<LangStandard::Kind>(KindValue)); if (IsInputCompatibleWithStandard(IK, Std)) { auto Diag = Diags.Report(diag::note_drv_use_standard); Diag << Std.getName() << Std.getDescription(); unsigned NumAliases = 0; #define LANGSTANDARD(id, name, lang, desc, features) #define LANGSTANDARD_ALIAS(id, alias) \ if (KindValue == LangStandard::lang_##id) ++NumAliases; #define LANGSTANDARD_ALIAS_DEPR(id, alias) #include "clang/Basic/LangStandards.def" Diag << NumAliases; #define LANGSTANDARD(id, name, lang, desc, features) #define LANGSTANDARD_ALIAS(id, alias) \ if (KindValue == LangStandard::lang_##id) Diag << alias; #define LANGSTANDARD_ALIAS_DEPR(id, alias) #include "clang/Basic/LangStandards.def" } } } else { // Valid standard, check to make sure language and standard are // compatible. const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); if (!IsInputCompatibleWithStandard(IK, Std)) { Diags.Report(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args) << GetInputKindName(IK); } } } // -cl-std only applies for OpenCL language standards. // Override the -std option in this case. if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { LangStandard::Kind OpenCLLangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) .Cases("cl", "CL", LangStandard::lang_opencl10) .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10) .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11) .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12) .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20) .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30) .Cases("clc++", "CLC++", LangStandard::lang_openclcpp) .Default(LangStandard::lang_unspecified); if (OpenCLLangStd == LangStandard::lang_unspecified) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); } else LangStd = OpenCLLangStd; } // These need to be parsed now. They are used to set OpenCL defaults. Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header); Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins); CompilerInvocation::setLangDefaults(Opts, IK, T, Includes, LangStd); // The key paths of codegen options defined in Options.td start with // "LangOpts->". Let's provide the expected variable name and type. LangOptions *LangOpts = &Opts; bool Success = true; #define LANG_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef LANG_OPTION_WITH_MARSHALLING if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { StringRef Name = A->getValue(); if (Name == "full" || Name == "branch") { Opts.CFProtectionBranch = 1; } } if (Opts.ObjC) { if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { StringRef value = arg->getValue(); if (Opts.ObjCRuntime.tryParse(value)) Diags.Report(diag::err_drv_unknown_objc_runtime) << value; } if (Args.hasArg(OPT_fobjc_gc_only)) Opts.setGC(LangOptions::GCOnly); else if (Args.hasArg(OPT_fobjc_gc)) Opts.setGC(LangOptions::HybridGC); else if (Args.hasArg(OPT_fobjc_arc)) { Opts.ObjCAutoRefCount = 1; if (!Opts.ObjCRuntime.allowsARC()) Diags.Report(diag::err_arc_unsupported_on_runtime); } // ObjCWeakRuntime tracks whether the runtime supports __weak, not // whether the feature is actually enabled. This is predominantly // determined by -fobjc-runtime, but we allow it to be overridden // from the command line for testing purposes. if (Args.hasArg(OPT_fobjc_runtime_has_weak)) Opts.ObjCWeakRuntime = 1; else Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); // ObjCWeak determines whether __weak is actually enabled. // Note that we allow -fno-objc-weak to disable this even in ARC mode. if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { if (!weakArg->getOption().matches(OPT_fobjc_weak)) { assert(!Opts.ObjCWeak); } else if (Opts.getGC() != LangOptions::NonGC) { Diags.Report(diag::err_objc_weak_with_gc); } else if (!Opts.ObjCWeakRuntime) { Diags.Report(diag::err_objc_weak_unsupported); } else { Opts.ObjCWeak = 1; } } else if (Opts.ObjCAutoRefCount) { Opts.ObjCWeak = Opts.ObjCWeakRuntime; } if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) Opts.ObjCSubscriptingLegacyRuntime = (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); } if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) { // Check that the version has 1 to 3 components and the minor and patch // versions fit in two decimal digits. VersionTuple GNUCVer; bool Invalid = GNUCVer.tryParse(A->getValue()); unsigned Major = GNUCVer.getMajor(); unsigned Minor = GNUCVer.getMinor().getValueOr(0); unsigned Patch = GNUCVer.getSubminor().getValueOr(0); if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); } Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch; } // In AIX OS, the -mignore-xcoff-visibility is enable by default if there is // no -fvisibility=* option. // This is the reason why '-fvisibility' needs to be always generated: // its absence implies '-mignore-xcoff-visibility'. // // Suppose the original cc1 command line does contain '-fvisibility default': // '-mignore-xcoff-visibility' should not be implied. // * If '-fvisibility' is not generated (as most options with default values // don't), its absence would imply '-mignore-xcoff-visibility'. This changes // the command line semantics. // * If '-fvisibility' is generated regardless of its presence and value, // '-mignore-xcoff-visibility' won't be implied and the command line // semantics are kept intact. // // When the original cc1 command line does **not** contain '-fvisibility', // '-mignore-xcoff-visibility' is implied. The generated command line will // contain both '-fvisibility default' and '-mignore-xcoff-visibility' and // subsequent calls to `CreateFromArgs`/`generateCC1CommandLine` will always // produce the same arguments. if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) || !Args.hasArg(OPT_fvisibility))) Opts.IgnoreXCOFFVisibility = 1; if (Args.hasArg(OPT_ftrapv)) { Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); // Set the handler, if one is specified. Opts.OverflowHandler = std::string(Args.getLastArgValue(OPT_ftrapv_handler)); } else if (Args.hasArg(OPT_fwrapv)) Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); Opts.MSCompatibilityVersion = 0; if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { VersionTuple VT; if (VT.tryParse(A->getValue())) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + VT.getMinor().getValueOr(0) * 100000 + VT.getSubminor().getValueOr(0); } // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs // is specified, or -std is set to a conforming mode. // Trigraphs are disabled by default in c++1z onwards. // For z/OS, trigraphs are enabled by default (without regard to the above). Opts.Trigraphs = (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS(); Opts.Trigraphs = Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL && Opts.OpenCLVersion == 200); Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice || Args.hasArg(OPT_fconvergent_functions); Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; if (!Opts.NoBuiltin) getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs); Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128) ? 128 : Args.hasArg(OPT_mlong_double_64) ? 64 : 0; if (Opts.FastRelaxedMath) Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); llvm::sort(Opts.ModuleFeatures); // -mrtd option if (Arg *A = Args.getLastArg(OPT_mrtd)) { if (Opts.getDefaultCallingConv() != LangOptions::DCC_None) Diags.Report(diag::err_drv_argument_not_allowed_with) << A->getSpelling() << "-fdefault-calling-conv"; else { if (T.getArch() != llvm::Triple::x86) Diags.Report(diag::err_drv_argument_not_allowed_with) << A->getSpelling() << T.getTriple(); else Opts.setDefaultCallingConv(LangOptions::DCC_StdCall); } } // Check if -fopenmp is specified and set default version to 5.0. Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0; // Check if -fopenmp-simd is specified. bool IsSimdSpecified = Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd, /*Default=*/false); Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified; Opts.OpenMPUseTLS = Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); Opts.OpenMPIsDevice = Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device); Opts.OpenMPIRBuilder = Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder); bool IsTargetSpecified = Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ); Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice; if (Opts.OpenMP || Opts.OpenMPSimd) { if (int Version = getLastArgIntValue( Args, OPT_fopenmp_version_EQ, (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags)) Opts.OpenMP = Version; // Provide diagnostic when a given target is not expected to be an OpenMP // device or host. if (!Opts.OpenMPIsDevice) { switch (T.getArch()) { default: break; // Add unsupported host targets here: case llvm::Triple::nvptx: case llvm::Triple::nvptx64: Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str(); break; } } } // Set the flag to prevent the implementation from emitting device exception // handling code for those requiring so. if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) || Opts.OpenCLCPlusPlus) { Opts.Exceptions = 0; Opts.CXXExceptions = 0; } if (Opts.OpenMPIsDevice && T.isNVPTX()) { Opts.OpenMPCUDANumSMs = getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ, Opts.OpenMPCUDANumSMs, Diags); Opts.OpenMPCUDABlocksPerSM = getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ, Opts.OpenMPCUDABlocksPerSM, Diags); Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue( Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ, Opts.OpenMPCUDAReductionBufNum, Diags); } // Get the OpenMP target triples if any. if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) { enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit }; auto getArchPtrSize = [](const llvm::Triple &T) { if (T.isArch16Bit()) return Arch16Bit; if (T.isArch32Bit()) return Arch32Bit; assert(T.isArch64Bit() && "Expected 64-bit architecture"); return Arch64Bit; }; for (unsigned i = 0; i < A->getNumValues(); ++i) { llvm::Triple TT(A->getValue(i)); if (TT.getArch() == llvm::Triple::UnknownArch || !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() || TT.getArch() == llvm::Triple::nvptx || TT.getArch() == llvm::Triple::nvptx64 || TT.getArch() == llvm::Triple::amdgcn || TT.getArch() == llvm::Triple::x86 || TT.getArch() == llvm::Triple::x86_64)) Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i); else if (getArchPtrSize(T) != getArchPtrSize(TT)) Diags.Report(diag::err_drv_incompatible_omp_arch) << A->getValue(i) << T.str(); else Opts.OMPTargetTriples.push_back(TT); } } // Get OpenMP host file path if any and report if a non existent file is // found if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) { Opts.OMPHostIRFile = A->getValue(); if (!llvm::sys::fs::exists(Opts.OMPHostIRFile)) Diags.Report(diag::err_drv_omp_host_ir_file_not_found) << Opts.OMPHostIRFile; } // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && Args.hasArg(options::OPT_fopenmp_cuda_mode); // Set CUDA support for parallel execution of target regions for OpenMP target // NVPTX/AMDGCN if specified in options. Opts.OpenMPCUDATargetParallel = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && Args.hasArg(options::OPT_fopenmp_cuda_parallel_target_regions); // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options Opts.OpenMPCUDAForceFullRuntime = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) && Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime); // FIXME: Eliminate this dependency. unsigned Opt = getOptimizationLevel(Args, IK, Diags), OptSize = getOptimizationLevelSize(Args); Opts.Optimize = Opt != 0; Opts.OptimizeSize = OptSize != 0; // This is the __NO_INLINE__ define, which just depends on things like the // optimization level and -fno-inline, not actually whether the backend has // inlining enabled. Opts.NoInlineDefine = !Opts.Optimize; if (Arg *InlineArg = Args.getLastArg( options::OPT_finline_functions, options::OPT_finline_hint_functions, options::OPT_fno_inline_functions, options::OPT_fno_inline)) if (InlineArg->getOption().matches(options::OPT_fno_inline)) Opts.NoInlineDefine = true; if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { StringRef Val = A->getValue(); if (Val == "fast") Opts.setDefaultFPContractMode(LangOptions::FPM_Fast); else if (Val == "on") Opts.setDefaultFPContractMode(LangOptions::FPM_On); else if (Val == "off") Opts.setDefaultFPContractMode(LangOptions::FPM_Off); else if (Val == "fast-honor-pragmas") Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas); else Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; } // Parse -fsanitize= arguments. parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), Diags, Opts.Sanitize); Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); std::vector<std::string> systemBlacklists = Args.getAllArgValues(OPT_fsanitize_system_blacklist); Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(), systemBlacklists.begin(), systemBlacklists.end()); if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) { Opts.setClangABICompat(LangOptions::ClangABI::Latest); StringRef Ver = A->getValue(); std::pair<StringRef, StringRef> VerParts = Ver.split('.'); unsigned Major, Minor = 0; // Check the version number is valid: either 3.x (0 <= x <= 9) or // y or y.0 (4 <= y <= current version). if (!VerParts.first.startswith("0") && !VerParts.first.getAsInteger(10, Major) && 3 <= Major && Major <= CLANG_VERSION_MAJOR && (Major == 3 ? VerParts.second.size() == 1 && !VerParts.second.getAsInteger(10, Minor) : VerParts.first.size() == Ver.size() || VerParts.second == "0")) { // Got a valid version number. if (Major == 3 && Minor <= 8) Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8); else if (Major <= 4) Opts.setClangABICompat(LangOptions::ClangABI::Ver4); else if (Major <= 6) Opts.setClangABICompat(LangOptions::ClangABI::Ver6); else if (Major <= 7) Opts.setClangABICompat(LangOptions::ClangABI::Ver7); else if (Major <= 9) Opts.setClangABICompat(LangOptions::ClangABI::Ver9); else if (Major <= 11) Opts.setClangABICompat(LangOptions::ClangABI::Ver11); } else if (Ver != "latest") { Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); } } if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) { StringRef SignScope = A->getValue(); if (SignScope.equals_lower("none")) Opts.setSignReturnAddressScope( LangOptions::SignReturnAddressScopeKind::None); else if (SignScope.equals_lower("all")) Opts.setSignReturnAddressScope( LangOptions::SignReturnAddressScopeKind::All); else if (SignScope.equals_lower("non-leaf")) Opts.setSignReturnAddressScope( LangOptions::SignReturnAddressScopeKind::NonLeaf); else Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << SignScope; if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) { StringRef SignKey = A->getValue(); if (!SignScope.empty() && !SignKey.empty()) { if (SignKey.equals_lower("a_key")) Opts.setSignReturnAddressKey( LangOptions::SignReturnAddressKeyKind::AKey); else if (SignKey.equals_lower("b_key")) Opts.setSignReturnAddressKey( LangOptions::SignReturnAddressKeyKind::BKey); else Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << SignKey; } } } return Success && Diags.getNumErrors() == NumErrorsBefore; } static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) { switch (Action) { case frontend::ASTDeclList: case frontend::ASTDump: case frontend::ASTPrint: case frontend::ASTView: case frontend::EmitAssembly: case frontend::EmitBC: case frontend::EmitHTML: case frontend::EmitLLVM: case frontend::EmitLLVMOnly: case frontend::EmitCodeGenOnly: case frontend::EmitObj: case frontend::FixIt: case frontend::GenerateModule: case frontend::GenerateModuleInterface: case frontend::GenerateHeaderModule: case frontend::GeneratePCH: case frontend::GenerateInterfaceStubs: case frontend::ParseSyntaxOnly: case frontend::ModuleFileInfo: case frontend::VerifyPCH: case frontend::PluginAction: case frontend::RewriteObjC: case frontend::RewriteTest: case frontend::RunAnalysis: case frontend::TemplightDump: case frontend::MigrateSource: return false; case frontend::DumpCompilerOptions: case frontend::DumpRawTokens: case frontend::DumpTokens: case frontend::InitOnly: case frontend::PrintPreamble: case frontend::PrintPreprocessedInput: case frontend::RewriteMacros: case frontend::RunPreprocessorOnly: case frontend::PrintDependencyDirectivesSourceMinimizerOutput: return true; } llvm_unreachable("invalid frontend action"); } static void GeneratePreprocessorArgs(PreprocessorOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA, const LangOptions &LangOpts, const FrontendOptions &FrontendOpts, const CodeGenOptions &CodeGenOpts) { PreprocessorOptions *PreprocessorOpts = &Opts; #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef PREPROCESSOR_OPTION_WITH_MARSHALLING if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate) GenerateArg(Args, OPT_pch_through_hdrstop_use, SA); for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn) GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA); for (const auto &MP : Opts.MacroPrefixMap) GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA); if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false)) GenerateArg(Args, OPT_preamble_bytes_EQ, Twine(Opts.PrecompiledPreambleBytes.first) + "," + (Opts.PrecompiledPreambleBytes.second ? "1" : "0"), SA); for (const auto &M : Opts.Macros) { // Don't generate __CET__ macro definitions. They are implied by the // -fcf-protection option that is generated elsewhere. if (M.first == "__CET__=1" && !M.second && !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch) continue; if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn && !CodeGenOpts.CFProtectionBranch) continue; if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch) continue; GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA); } for (const auto &I : Opts.Includes) { // Don't generate OpenCL includes. They are implied by other flags that are // generated elsewhere. if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader && ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") || I == "opencl-c.h")) continue; GenerateArg(Args, OPT_include, I, SA); } for (const auto &CI : Opts.ChainedIncludes) GenerateArg(Args, OPT_chain_include, CI, SA); for (const auto &RF : Opts.RemappedFiles) GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA); // Don't handle LexEditorPlaceholders. It is implied by the action that is // generated elsewhere. } static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action, const FrontendOptions &FrontendOpts) { PreprocessorOptions *PreprocessorOpts = &Opts; bool Success = true; #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef PREPROCESSOR_OPTION_WITH_MARSHALLING Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) || Args.hasArg(OPT_pch_through_hdrstop_use); for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) { auto Split = StringRef(A).split('='); Opts.MacroPrefixMap.insert( {std::string(Split.first), std::string(Split.second)}); } if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { StringRef Value(A->getValue()); size_t Comma = Value.find(','); unsigned Bytes = 0; unsigned EndOfLine = 0; if (Comma == StringRef::npos || Value.substr(0, Comma).getAsInteger(10, Bytes) || Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) Diags.Report(diag::err_drv_preamble_format); else { Opts.PrecompiledPreambleBytes.first = Bytes; Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); } } // Add the __CET__ macro if a CFProtection option is set. if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) { StringRef Name = A->getValue(); if (Name == "branch") Opts.addMacroDef("__CET__=1"); else if (Name == "return") Opts.addMacroDef("__CET__=2"); else if (Name == "full") Opts.addMacroDef("__CET__=3"); } // Add macros from the command line. for (const auto *A : Args.filtered(OPT_D, OPT_U)) { if (A->getOption().matches(OPT_D)) Opts.addMacroDef(A->getValue()); else Opts.addMacroUndef(A->getValue()); } // Add the ordered list of -includes. for (const auto *A : Args.filtered(OPT_include)) Opts.Includes.emplace_back(A->getValue()); for (const auto *A : Args.filtered(OPT_chain_include)) Opts.ChainedIncludes.emplace_back(A->getValue()); for (const auto *A : Args.filtered(OPT_remap_file)) { std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); if (Split.second.empty()) { Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); continue; } Opts.addRemappedFile(Split.first, Split.second); } // Always avoid lexing editor placeholders when we're just running the // preprocessor as we never want to emit the // "editor placeholder in source file" error in PP only mode. if (isStrictlyPreprocessorAction(Action)) Opts.LexEditorPlaceholders = false; return Success; } static void GeneratePreprocessorOutputArgs( const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) { const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts; #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP; if (Generate_dM) GenerateArg(Args, OPT_dM, SA); if (!Generate_dM && Opts.ShowMacros) GenerateArg(Args, OPT_dD, SA); } static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags, frontend::ActionKind Action) { PreprocessorOutputOptions &PreprocessorOutputOpts = Opts; unsigned NumErrorsBefore = Diags.getNumErrors(); bool Success = true; #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM); Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); return Success && Diags.getNumErrors() == NumErrorsBefore; } static void GenerateTargetArgs(const TargetOptions &Opts, SmallVectorImpl<const char *> &Args, CompilerInvocation::StringAllocator SA) { const TargetOptions *TargetOpts = &Opts; #define TARGET_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ GENERATE_OPTION_WITH_MARSHALLING( \ Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef TARGET_OPTION_WITH_MARSHALLING if (!Opts.SDKVersion.empty()) GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(), SA); } static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args, DiagnosticsEngine &Diags) { TargetOptions *TargetOpts = &Opts; unsigned NumErrorsBefore = Diags.getNumErrors(); bool Success = true; #define TARGET_OPTION_WITH_MARSHALLING( \ PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \ DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \ MERGER, EXTRACTOR, TABLE_INDEX) \ PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \ SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \ IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \ MERGER, TABLE_INDEX) #include "clang/Driver/Options.inc" #undef TARGET_OPTION_WITH_MARSHALLING if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) { llvm::VersionTuple Version; if (Version.tryParse(A->getValue())) Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << A->getValue(); else Opts.SDKVersion = Version; } return Success && Diags.getNumErrors() == NumErrorsBefore; } bool CompilerInvocation::CreateFromArgsImpl( CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0) { bool Success = true; // Parse the arguments. const OptTable &Opts = getDriverOptTable(); const unsigned IncludedFlagsBitmask = options::CC1Option; unsigned MissingArgIndex, MissingArgCount; InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex, MissingArgCount, IncludedFlagsBitmask); LangOptions &LangOpts = *Res.getLangOpts(); // Check for missing argument error. if (MissingArgCount) { Diags.Report(diag::err_drv_missing_argument) << Args.getArgString(MissingArgIndex) << MissingArgCount; Success = false; } // Issue errors on unknown arguments. for (const auto *A : Args.filtered(OPT_UNKNOWN)) { auto ArgString = A->getAsString(Args); std::string Nearest; if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) Diags.Report(diag::err_drv_unknown_argument) << ArgString; else Diags.Report(diag::err_drv_unknown_argument_with_suggestion) << ArgString << Nearest; Success = false; } Success &= ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags); Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags); Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags); Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags, /*DefaultDiagColor=*/false); Success &= ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile); // FIXME: We shouldn't have to pass the DashX option around here InputKind DashX = Res.getFrontendOpts().DashX; Success &= ParseTargetArgs(Res.getTargetOpts(), Args, Diags); llvm::Triple T(Res.getTargetOpts().Triple); ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags, Res.getFileSystemOpts().WorkingDir); if (DashX.getFormat() == InputKind::Precompiled || DashX.getLanguage() == Language::LLVM_IR) { // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the // PassManager in BackendUtil.cpp. They need to be initializd no matter // what the input type is. if (Args.hasArg(OPT_fobjc_arc)) LangOpts.ObjCAutoRefCount = 1; // PIClevel and PIELevel are needed during code generation and this should be // set regardless of the input type. LangOpts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); LangOpts.PIE = Args.hasArg(OPT_pic_is_pie); parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), Diags, LangOpts.Sanitize); } else { // Other LangOpts are only initialized when the input is not AST or LLVM IR. // FIXME: Should we really be calling this for an Language::Asm input? Success &= ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes, Diags); if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) LangOpts.ObjCExceptions = 1; } if (LangOpts.CUDA) { // During CUDA device-side compilation, the aux triple is the // triple used for host compilation. if (LangOpts.CUDAIsDevice) Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; } // Set the triple of the host for OpenMP device compile. if (LangOpts.OpenMPIsDevice) Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple; Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T, Res.getFrontendOpts().OutputFile, LangOpts); // FIXME: Override value name discarding when asan or msan is used because the // backend passes depend on the name of the alloca in order to print out // names. Res.getCodeGenOpts().DiscardValueNames &= !LangOpts.Sanitize.has(SanitizerKind::Address) && !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) && !LangOpts.Sanitize.has(SanitizerKind::Memory) && !LangOpts.Sanitize.has(SanitizerKind::KernelMemory); ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags, Res.getFrontendOpts().ProgramAction, Res.getFrontendOpts()); ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags, Res.getFrontendOpts().ProgramAction); ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags, Res.getFrontendOpts().ProgramAction, Res.getPreprocessorOutputOpts().ShowLineMarkers); if (!Res.getDependencyOutputOpts().OutputFile.empty() && Res.getDependencyOutputOpts().Targets.empty()) { Diags.Report(diag::err_fe_dependency_file_requires_MT); Success = false; } // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses. if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses && !Res.getLangOpts()->Sanitize.empty()) { Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false; Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored); } // Store the command-line for using in the CodeView backend. Res.getCodeGenOpts().Argv0 = Argv0; Res.getCodeGenOpts().CommandLineArgs = CommandLineArgs; Success &= FixupInvocation(Res, Diags, Args, DashX); return Success; } bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0) { CompilerInvocation DummyInvocation; return RoundTrip( [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0) { return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0); }, [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args, StringAllocator SA) { Invocation.generateCC1CommandLine(Args, SA); }, Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0); } std::string CompilerInvocation::getModuleHash() const { // Note: For QoI reasons, the things we use as a hash here should all be // dumped via the -module-info flag. using llvm::hash_code; using llvm::hash_value; using llvm::hash_combine; using llvm::hash_combine_range; // Start the signature with the compiler version. // FIXME: We'd rather use something more cryptographically sound than // CityHash, but this will do for now. hash_code code = hash_value(getClangFullRepositoryVersion()); // Also include the serialization version, in case LLVM_APPEND_VC_REV is off // and getClangFullRepositoryVersion() doesn't include git revision. code = hash_combine(code, serialization::VERSION_MAJOR, serialization::VERSION_MINOR); // Extend the signature with the language options #define LANGOPT(Name, Bits, Default, Description) \ code = hash_combine(code, LangOpts->Name); #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name())); #define BENIGN_LANGOPT(Name, Bits, Default, Description) #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) #include "clang/Basic/LangOptions.def" for (StringRef Feature : LangOpts->ModuleFeatures) code = hash_combine(code, Feature); code = hash_combine(code, LangOpts->ObjCRuntime); const auto &BCN = LangOpts->CommentOpts.BlockCommandNames; code = hash_combine(code, hash_combine_range(BCN.begin(), BCN.end())); // Extend the signature with the target options. code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU, TargetOpts->TuneCPU, TargetOpts->ABI); for (const auto &FeatureAsWritten : TargetOpts->FeaturesAsWritten) code = hash_combine(code, FeatureAsWritten); // Extend the signature with preprocessor options. const PreprocessorOptions &ppOpts = getPreprocessorOpts(); const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord); for (const auto &I : getPreprocessorOpts().Macros) { // If we're supposed to ignore this macro for the purposes of modules, // don't put it into the hash. if (!hsOpts.ModulesIgnoreMacros.empty()) { // Check whether we're ignoring this macro. StringRef MacroDef = I.first; if (hsOpts.ModulesIgnoreMacros.count( llvm::CachedHashString(MacroDef.split('=').first))) continue; } code = hash_combine(code, I.first, I.second); } // Extend the signature with the sysroot and other header search options. code = hash_combine(code, hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo, hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes, hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx, hsOpts.ModulesValidateDiagnosticOptions); code = hash_combine(code, hsOpts.ResourceDir); if (hsOpts.ModulesStrictContextHash) { hash_code SHPC = hash_combine_range(hsOpts.SystemHeaderPrefixes.begin(), hsOpts.SystemHeaderPrefixes.end()); hash_code UEC = hash_combine_range(hsOpts.UserEntries.begin(), hsOpts.UserEntries.end()); code = hash_combine(code, hsOpts.SystemHeaderPrefixes.size(), SHPC, hsOpts.UserEntries.size(), UEC); const DiagnosticOptions &diagOpts = getDiagnosticOpts(); #define DIAGOPT(Name, Bits, Default) \ code = hash_combine(code, diagOpts.Name); #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ code = hash_combine(code, diagOpts.get##Name()); #include "clang/Basic/DiagnosticOptions.def" #undef DIAGOPT #undef ENUM_DIAGOPT } // Extend the signature with the user build path. code = hash_combine(code, hsOpts.ModuleUserBuildPath); // Extend the signature with the module file extensions. const FrontendOptions &frontendOpts = getFrontendOpts(); for (const auto &ext : frontendOpts.ModuleFileExtensions) { code = ext->hashExtension(code); } // When compiling with -gmodules, also hash -fdebug-prefix-map as it // affects the debug info in the PCM. if (getCodeGenOpts().DebugTypeExtRefs) for (const auto &KeyValue : getCodeGenOpts().DebugPrefixMap) code = hash_combine(code, KeyValue.first, KeyValue.second); // Extend the signature with the enabled sanitizers, if at least one is // enabled. Sanitizers which cannot affect AST generation aren't hashed. SanitizerSet SanHash = LangOpts->Sanitize; SanHash.clear(getPPTransparentSanitizers()); if (!SanHash.empty()) code = hash_combine(code, SanHash.Mask); return llvm::APInt(64, code).toString(36, /*Signed=*/false); } void CompilerInvocation::generateCC1CommandLine( SmallVectorImpl<const char *> &Args, StringAllocator SA) const { llvm::Triple T(TargetOpts->Triple); GenerateFileSystemArgs(FileSystemOpts, Args, SA); GenerateMigratorArgs(MigratorOpts, Args, SA); GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA); GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false); GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile); GenerateTargetArgs(*TargetOpts, Args, SA); GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA); InputKind DashX = FrontendOpts.DashX; if (DashX.getFormat() == InputKind::Precompiled || DashX.getLanguage() == Language::LLVM_IR) { if (LangOpts->ObjCAutoRefCount) GenerateArg(Args, OPT_fobjc_arc, SA); if (LangOpts->PICLevel != 0) GenerateArg(Args, OPT_pic_level, Twine(LangOpts->PICLevel), SA); if (LangOpts->PIE) GenerateArg(Args, OPT_pic_is_pie, SA); for (StringRef Sanitizer : serializeSanitizerKinds(LangOpts->Sanitize)) GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA); } else { // FIXME: Move this whole condition into GenerateLangArgs. (And do the same // for ParseLangArgs). GenerateLangArgs(*LangOpts, Args, SA, T); } GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile, &*LangOpts); GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts, CodeGenOpts); GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA, FrontendOpts.ProgramAction); GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA); } IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags) { return createVFSFromCompilerInvocation(CI, Diags, llvm::vfs::getRealFileSystem()); } IntrusiveRefCntPtr<llvm::vfs::FileSystem> clang::createVFSFromCompilerInvocation( const CompilerInvocation &CI, DiagnosticsEngine &Diags, IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) { if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) return BaseFS; IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS; // earlier vfs files are on the bottom for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = Result->getBufferForFile(File); if (!Buffer) { Diags.Report(diag::err_missing_vfs_overlay_file) << File; continue; } IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML( std::move(Buffer.get()), /*DiagHandler*/ nullptr, File, /*DiagContext*/ nullptr, Result); if (!FS) { Diags.Report(diag::err_invalid_vfs_overlay) << File; continue; } Result = FS; } return Result; }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: driveLow.asm AUTHOR: Adam de Boor, Apr 22, 1990 ROUTINES: Name Description ---- ----------- INT DrivePointAtEntry Point at the proper disk status entry for the indicated drive. INT DriveCallDriver Call the DOS driver pointed to by ds:si REVISION HISTORY: Name Date Description ---- ---- ----------- Adam 4/22/90 Initial revision DESCRIPTION: Low-level functions for the Drive module $Id: driveLow.asm,v 1.1 97/04/05 01:11:27 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DrivePointAtEntry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Given a zero-based drive number, return the address of the DriveStatusEntry for the drive. CALLED BY: DriveGetStatus, DriveGetDefaultMedia PASS: al = zero-based drive number RETURN: ds:bx = DriveStatusEntry DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 4/22/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DrivePointAtEntryFar proc far call DrivePointAtEntry ret DrivePointAtEntryFar endp DrivePointAtEntry proc near uses ax .enter EC< cmp al, MSDOS_MAX_DRIVES > EC< ERROR_AE BAD_DRIVE_SPECIFIED > CheckHack <size DriveStatusEntry eq 22> xchg bx, ax clr bh shl bx mov ax, bx ; save al * 2 shl bx add ax, bx ; ax <- al * 6 shl bx shl bx ; bx = al * 16 add bx, ax ; bx <- al * 22 LoadVarSeg ds add bx, offset driveStatusTable .leave ret DrivePointAtEntry endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DriveCallDriver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Issue a call to a DOS device driver CALLED BY: DriveMediaRemovable?, InitDriveMap PASS: ds:si = DeviceHeader of driver to call on stack: RequestHeader structure for request to issue, plus any extra data required by the call. RETURN: carry set if driver declares an error DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 4/23/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DriveCallDriver proc far request:RequestHeader uses ax, es, bx .enter call LockDOS ; ; First call the "strategy" routine, passing it the request header ; in es:bx ; segmov es, ss, bx lea bx, request mov ax, ds:[si].DH_strat push cs call makeCall ; ; Now call the "interrupt" routine to process the request. Who thought ; up this interface, anyway? ; mov ax, ds:[si].DH_intr push cs call makeCall ; ; See if the thing protesteth too much. ; test request.RH_status, mask DDS_ERROR jz ok stc ok: call UnlockDOS .leave ret makeCall: push ds ; Set segment for call push ax ; and offset retf ; Call the driver. It will return ; to "our" caller for us... DriveCallDriver endp
; A147965: a(n) is the difference between n and the n-th gap between primes. ; 1,1,2,1,4,3,6,5,4,9,6,9,12,11,10,11,16,13,16,19,16,19,18,17,22,25,24,27,26,17,28,27,32,25,34,31,32,35,34,35,40,33,42,41,44,35,36,45,48,47,46,51,44,49,50,51,56,53,56,59 mov $1,$0 add $1,1 seq $1,40 ; The prime numbers. div $1,2 mul $1,2 sub $1,1 seq $1,64722 ; a(1) = 0; for n >= 2, a(n) = n - (largest prime <= n). sub $0,$1 add $0,1
#include "sha3_256.hpp" #include <cassert> // This example attempts to show how to use 2-to-1 SHA3-256 hash function ! int main(int argc, char** argv) { // $ python3 // >>> a = [0xff] * 32 // // first input digest constexpr sycl::uchar digest_0[32] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; // >>> b = [0x0f] * 32 // // second input digest constexpr sycl::uchar digest_1[32] = { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }; // >>> c = a + b // >>> import hashlib // >>> list(hashlib.sha3_256(bytes(c)).digest()) // // final output digest after merging two input digests constexpr sycl::uchar digest_2[32] = { 121, 136, 237, 222, 17, 197, 60, 82, 161, 87, 52, 66, 251, 235, 8, 125, 1, 95, 88, 134, 1, 235, 132, 182, 114, 55, 207, 202, 17, 104, 74, 95 }; sycl::default_selector s{}; sycl::device d{ s }; sycl::context c{ d }; sycl::queue q{ c, d }; // so that input digests can be transferred from host to device ( by runtime ) sycl::uchar* in = static_cast<sycl::uchar*>( sycl::malloc_shared(sizeof(digest_0) + sizeof(digest_1), q)); // so that output digest can be transferred from device to host ( by runtime ) sycl::uchar* out = static_cast<sycl::uchar*>(sycl::malloc_shared(sizeof(digest_2), q)); // copy both input digests to device memory q.memcpy(in + 0, digest_0, sizeof(digest_0)).wait(); q.memcpy(in + sizeof(digest_0), digest_1, sizeof(digest_1)).wait(); // compute 2-to-1 hash q.single_task<class kernelExampleSHA3_256>( [=]() { sha3_256::hash(in, out); }); q.wait(); // finally assert ! for (size_t i = 0; i < sizeof(digest_2); i++) { assert(*(out + i) == digest_2[i]); } // deallocate resources ! sycl::free(in, q); sycl::free(out, q); return EXIT_SUCCESS; }
; A077975: Expansion of 1/(1+x+x^2-2*x^3). ; Submitted by Jamie Morken(s4) ; 1,-1,0,3,-5,2,9,-21,16,23,-81,90,37,-289,432,-69,-941,1874,-1071,-2685,7504,-6961,-5913,27882,-35891,-3817,95472,-163437,60331,294050,-681255,507867,761488,-2631865,2886111,1268730,-9418571,13922063,-1966032,-30793173,60603331,-33742222,-88447455,243396339,-222433328,-197857921,907083927,-1154092662,-148707107,3116967623,-5276445840,1862064003,9648317083,-22063272766,16139083689,25220823243,-85486452464,92543796599,43384302351,-306901003878,448604294725,-54934686145,-1007471616336,1959614891931 mov $1,1 lpb $0 sub $0,1 mul $2,2 sub $3,$1 add $1,$3 add $2,$3 add $1,$2 sub $2,$1 add $1,$2 add $3,$2 lpe mov $0,$1
; long lrint(float x) SECTION code_fp_math48 PUBLIC cm48_sdcciy_lrint EXTERN cm48_sdcciy_lrint_fastcall cm48_sdcciy_lrint: pop af pop hl pop de push de push hl push af jp cm48_sdcciy_lrint_fastcall
; A220033: Number of 3 X n arrays of the minimum value of corresponding elements and their horizontal or diagonal neighbors in a random, but sorted with lexicographically nondecreasing rows and nonincreasing columns, 0..1 3 X n array. ; 4,6,10,19,30,42,55,69,84,100,117,135,154,174,195,217,240,264,289,315,342,370,399,429,460,492,525,559,594,630,667,705,744,784,825,867,910,954,999,1045,1092,1140,1189,1239,1290,1342,1395,1449,1504,1560,1617,1675 mov $2,2 lpb $0 add $2,5 add $3,2 add $4,$0 sub $0,1 lpe mov $0,$3 trn $0,$4 add $0,1 mov $1,$4 add $1,$0 trn $1,4 sub $2,6 trn $2,5 add $3,4 add $3,$2 add $1,$3
#include <gtest/gtest.h> #include "lib/lib.h" TEST(add, add) { int a = 2; int b = 3; EXPECT_EQ(lib::add(a, b), 5); }
Name: ys_mram.asm Type: file Size: 75216 Last-Modified: '2016-05-13T04:51:46Z' SHA-1: 186125CCE51366D7DB5A8155BFF9A556A6EBCD4B Description: null
/******************************************************************************* * Copyright 2020 FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "test_generator2.h" class TestPtnGenerator : public TestGenerator { public: void setInitialRegValue() { /* Here modify arrays of inputGenReg, inputPredReg, inputZReg */ setInputZregAllRandomHex(); #if 0 for (int j = 0; j < 32; j++) { for (int i = 0; i < 16; i++) { inputZReg[j].us_dt[i] = (j << 16) + i; } } for (int i = 0; i < 16; i++) { inputZReg[31].us_dt[i] = 0x11111111 * i; } #endif } void setCheckRegFlagAll() { /* Here modify arrays of checkGenRegMode, checkPredRegMode, checkZRegMode */ } void genJitTestCode() { /* Here write JIT code with x86_64 mnemonic function to be tested. */ vshuff32x4(Ymm(0), Ymm(30), Ymm(31), 0); vshuff32x4(Ymm(1), Ymm(30), Ymm(31), 1); vshuff32x4(Ymm(2), Ymm(30), Ymm(31), 2); vshuff32x4(Ymm(3), Ymm(30), Ymm(31), 4); vshuff32x4(Ymm(4), Ymm(30), Ymm(31), 8); vshuff32x4(Ymm(5), Ymm(30), Ymm(31), 16); vshuff32x4(Ymm(6), Ymm(30), Ymm(31), 32); vshuff32x4(Ymm(7), Ymm(30), Ymm(31), 64); vshuff32x4(Ymm(8), Ymm(30), Ymm(31), 128); vshuff32x4(Ymm(9), Ymm(9), Ymm(31), 8); vshuff32x4(Ymm(10), Ymm(30), Ymm(10), 16); vshuff32x4(Ymm(11), Ymm(30), Ymm(30), 16); vshuff32x4(Ymm(12), Ymm(12), Ymm(12), 16); } }; int main(int argc, char *argv[]) { /* Initializing arrays of inputData, inputGenReg, inputPredReg, inputZReg, * checkGenRegMode, checkPredRegMode,checkZRegMode */ TestPtnGenerator gen; /* Set bool output_jit_on_, bool exec_jit_on_ = 0; */ gen.parseArgs(argc, argv); /* Generate JIT code and get function pointer */ void (*f)(); if (gen.isOutputJitOn()) { f = (void (*)())gen.gen(); } /* Dump generated JIT code to a binary file */ gen.dumpJitCode(); /* 1:Execute JIT code, 2:dump all register values, 3:dump register values to * be checked */ if (gen.isExecJitOn()) { /* Before executing JIT code, dump inputData, inputGenReg, inputPredReg, * inputZReg. */ gen.dumpInputReg(); f(); /* Execute JIT code */ gen.dumpOutputReg(); /* Dump all register values */ gen.dumpCheckReg(); /* Dump register values to be checked */ } return 0; }
#include <srt-sync/Decode.hpp> #include <cmath> #include <cstdlib> #include <iostream> namespace srt_sync { Decode::DecodeSink::DecodeSink(Decode &decoder) : decoder(decoder) { auto buffer = static_cast<unsigned char*>(av_malloc(MAX_FRAME_SIZE)); if (!buffer) return; io_context = avio_alloc_context(buffer, MAX_FRAME_SIZE, 0, this, &read_callback, nullptr, nullptr); if (!io_context) return; fmt_context = avformat_alloc_context(); if(!fmt_context) return; fmt_context->pb = io_context; packet = av_packet_alloc(); } int Decode::DecodeSink::read_callback(void *data, uint8_t *buf, int buf_size) { auto self = static_cast<DecodeSink*>(data); if (!self->decoder.from || !self->decoder.from->connected()) return -1; auto frame = self->decoder.from->pull(); if (!frame) return AVERROR(EAGAIN); auto to_copy = std::min(buf_size, static_cast<int>((*frame).size)); memcpy(buf, (*frame).data.data(), to_copy); return to_copy; } int Decode::DecodeSink::raise_ready() { std::unique_lock<std::mutex> lock(decoder.get_lock()); if (!decoder.initialized) return 0; packet->data = NULL; packet->size = 0; if (!decoder.from->ready()) return 0; if(av_read_frame(fmt_context, packet) < 0) return 0; int ret = 0; if (packet->stream_index == decoder.video_index) ret = avcodec_send_packet(decoder.video_decode_context, packet); else if (packet->stream_index == decoder.audio_index) ret = avcodec_send_packet(decoder.audio_decode_context, packet); av_packet_unref(packet); if (ret < 0) return -1; return 0; } std::optional<AVFrameWrapper> Decode::DecodeSource::pull() { std::unique_lock<std::mutex> lock(decoder.get_lock()); if (!decoder.initialized) return std::nullopt; AVFrameWrapper wrapper; int ret = avcodec_receive_frame(decoder.video_decode_context, wrapper.video_frame); if (ret < 0) return std::nullopt; ret = avcodec_receive_frame(decoder.audio_decode_context, wrapper.audio_frame); if (ret < 0) return std::nullopt; lock.unlock(); decoder.sink.raise_ready(); return wrapper; } std::optional<int> Decode::open_codec_context(AVCodecContext **decode_context, enum AVMediaType type) { int ret = av_find_best_stream(sink.fmt_context, type, -1, -1, NULL, 0); if (ret < 0) { std::cout << "Failed to find best stream" << std::endl; return std::nullopt; } int stream_idx = ret; AVStream *stream = sink.fmt_context->streams[stream_idx]; AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id); if (!dec) { std::cout << "Failed finding decoder for codec_id " << stream->codecpar->codec_id << std::endl; return std::nullopt; } *decode_context = avcodec_alloc_context3(dec); if (!decode_context) { std::cout << "Failed to allocate decoder_context" << std::endl; return std::nullopt; } if (avcodec_parameters_to_context(*decode_context, stream->codecpar) < 0) { std::cout << "Failed to copy codec parameters" << std::endl; return std::nullopt; } if (avcodec_open2(*decode_context, dec, NULL) < 0) { std::cout << "Failed to open codec context" << std::endl; return std::nullopt; } return stream_idx; } void Decode::probe_input() { std::unique_lock<std::mutex> lock(ffmpeg_lock); std::cout << "probe_input()" << std::endl; int ret = av_probe_input_buffer2(sink.io_context, &sink.fmt, NULL, NULL, 0, 0); std::cout << "av_probe_input_buffer2(): " << ret << std::endl; std::cout << sink.fmt->name << std::endl; ret = avformat_open_input(&sink.fmt_context, NULL, sink.fmt, NULL); std::cout << "avformat_open_input(): " << ret << std::endl; ret = avformat_find_stream_info(sink.fmt_context, NULL); std::cout << "avformat_find_stream_info(): " << ret << std::endl; auto index_ret = open_codec_context(&video_decode_context, AVMEDIA_TYPE_VIDEO); if (!index_ret) { std::cout << "open_codex_context() failed for video!" << std::endl; return; } video_index = *index_ret; index_ret = open_codec_context(&audio_decode_context, AVMEDIA_TYPE_AUDIO); if (!index_ret) { std::cout << "open_codex_context() failed for audio!" << std::endl; return; } audio_index = *index_ret; av_dump_format(sink.fmt_context, 0, NULL, 0); initialized = true; lock.unlock(); sink.raise_ready(); } } // namespace srt_sync
.headersize (G_BOOT_ENTRYPOINT - G_BOOT_ADDR) .org G_BOOT_ENTRYPOINT BOOT: addiu sp, sp, -0x20 sw s0, 0x18(sp) sw s1, 0x1C(sp) // copy boot code into it's own address space la s0, G_SWAP_ENTRYPOINT la a0, G_BOOT_ENTRYPOINT addu a1, s0, r0 li s1, G0_DMADATA_SIZE jal bcopy addu a2, s1, r0 // flush the cache addu a0, s0, r0 jal osWritebackDCache addu a1, s1, r0 addu a0, s0, r0 jal osInvalICache addu a1, s1, r0 j BOOT_3 nop .headersize (G_SWAP_ENTRYPOINT - G_BOOT_ADDR) BOOT_3: //jal osGetCount //nop lui v1, 0x8000 lb v0, (0x031C+0x1C)(v1) andi at, v0, 0x01 addiu v0, v0, 1 bnez at, @BOOT_G1 sb v0, (0x031C+0x1C)(v1) @BOOT_G0: lw s0, 0x18(sp) lw s1, 0x1C(sp) //original boot li t0, 0x80006830 li t1, 0x4910 @@L0: addi t1, t1, -0x08 sw r0, 0x0000(t0) sw r0, 0x0004(t0) bnez t1, @@L0 addi t0, t0, 0x08 li t2, 0x80000498 li sp, 0x80007220 jr t2 nop @BOOT_G1: @@Loop: lw t3, PI_STATUS_REG andi at, t3, 0x03 bnez at, @@Loop nop la t4, (0xB0000000 + G_G1_MAKEROM) lw t0, 0x0008(t4) li t1, 0x1FFFFFFF // lui at, hi(PI_DRAM_ADDR_REG) and t2, t0, t1 sw t2, lo(PI_DRAM_ADDR_REG)(at) lui at, hi(PI_CART_ADDR_REG) lw t6, G_G1_CART li t7, 0xB0001000 addu t4, t6, t7 and t5, t4, t1 sw t5, lo(PI_CART_ADDR_REG)(at) lui at, hi(PI_WR_LEN_REG) li t3, 0xFFFFF sw t3, lo(PI_WR_LEN_REG)(at) nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop @@Loop2: lw t3, PI_STATUS_REG andi at, t3, 0x03 bnez at, @@Loop2 nop lw s0, 0x18(sp) lw s1, 0x1C(sp) jr t0 nop
#ifndef GAMESPELL_OS_UNICODE_HH #define GAMESPELL_OS_UNICODE_HH #include <string> #include <string_view> namespace gs { namespace os { extern std::wstring mbToWc(std::string_view s); extern std::string wcToMb(std::wstring_view ws); } // namespace os } // namespace gs #endif // GAMESPELL_OS_UNICODE_HH
; A274682: Numbers n such that 8*n-1 is a triangular number. ; Submitted by Simon Strandgaard ; 2,7,29,44,88,113,179,214,302,347,457,512,644,709,863,938,1114,1199,1397,1492,1712,1817,2059,2174,2438,2563,2849,2984,3292,3437,3767,3922,4274,4439,4813,4988,5384,5569,5987,6182,6622,6827,7289,7504,7988,8213,8719,8954,9482,9727,10277,10532,11104,11369,11963,12238,12854,13139,13777,14072,14732,15037,15719,16034,16738,17063,17789,18124,18872,19217,19987,20342,21134,21499,22313,22688,23524,23909,24767,25162,26042,26447,27349,27764,28688,29113,30059,30494,31462,31907,32897,33352,34364,34829,35863 mov $1,$0 gcd $0,2 pow $0,2 add $0,2 mul $1,8 add $0,$1 bin $0,2 mul $0,8 div $0,64 add $0,1
; A321295: a(n) = n * sigma_n(n). ; 1,10,84,1092,15630,284700,5764808,134744072,3486961557,100097666500,3138428376732,107019534520152,3937376385699302,155577590681061500,6568408813691796120,295152408847700721680,14063084452067724991026,708238048886859220660710,37589973457545958193355620,2097154000001929338886339560,122694327397835096314419994272,7511415092873316773201064686620,480250763996501976790165756943064,32009660552444602391661383907366192 add $0,1 mov $2,$0 lpb $0 mov $3,$2 mov $5,$0 cmp $5,0 add $0,$5 dif $3,$0 mov $4,$3 cmp $3,$2 cmp $3,0 mul $3,$0 sub $0,1 pow $3,$2 add $1,$3 lpe add $1,1 mul $4,$1 mov $0,$4
; uint in_LookupKey(uchar c) SECTION code_clib PUBLIC in_LookupKey PUBLIC _in_LookupKey EXTERN in_keytranstbl ; Given the ascii code of a character, returns the scan row and mask ; corresponding to the key that needs to be pressed to generate the ; character. ; ; The scan row returned will have bit 7 set and bit 6 set to ; indicate if CAPS, SYM SHIFTS also have to be pressed to generate the ; ascii code, respectively. ; enter: L = ascii character code ; exit : L = scan row ; H = mask ; else: L = scan row, H = mask ; bit 7 of L set if SHIFT needs to be pressed ; bit 6 of L set if CTRL needs to be pressed ; uses : AF,BC,HL ; The 16-bit value returned is a scan code understood by ; in_KeyPressed. .in_LookupKey ._in_LookupKey ld a,l ld hl,in_keytranstbl ld bc,64 * 3 cpir jr nz,notfound ld a,+(64 * 3) - 1 sub c ;A = position in table ld c,a ld hl,0 cp 64 * 2 jr c,not_function_table sub 64 * 2 ld c,a ld a,l or @01000000 ld l,a jr continue notfound: ld hl,0 scf ret not_function_table: cp 64 jr c,continue sub 64 ld c,a ld a,l or @10000000 ld l,a continue: ; l = flags ; c = character ; find the row divide by 5 ld a,c rrca rrca rrca and 7 ;row number ld h,a ld a,c and 7 ; l = row number, a = character in row ; find the mask ld b,@00000001 ld e,a find_mask: ld a,e and a jr z,found_mask ld a,b rlca ld b,a dec e jr find_mask found_mask: ; l = modifiers ; h = row number ; b = mask ld a,l or h ld l,a ld h,b and a ret
; A219020: Sum of the cubes of the first n even-indexed Fibonacci numbers divided by the sum of the first n terms. ; 1,7,45,297,2002,13630,93177,638001,4371235,29956465,205313076,1407206412,9645056785,66107994667,453110391657,3105663400665,21286529888422,145900036590826,1000013702089545,6854195814790005,46979356835860351 mov $1,2 mov $2,1 lpb $0 sub $0,1 add $2,$1 add $1,$2 lpe mov $0,$1 add $0,1 mul $0,$1 mov $1,$0 sub $1,6 div $1,4 add $1,1
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //General-purpose I/Os namespace GpiodModer{ ///<GPIO port mode register using Addr = Register::Address<0x48000c00,0x00000000,0x00000000,std::uint32_t>; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> moder15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> moder14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::ReadWriteAccess,unsigned> moder13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,unsigned> moder12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> moder11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> moder10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,unsigned> moder9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> moder8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> moder7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> moder6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> moder5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> moder4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> moder3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> moder2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> moder1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> moder0{}; } namespace GpiodOtyper{ ///<GPIO port output type register using Addr = Register::Address<0x48000c04,0xffff0000,0x00000000,std::uint32_t>; ///Port x configuration bit 15 constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> ot15{}; ///Port x configuration bit 14 constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> ot14{}; ///Port x configuration bit 13 constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> ot13{}; ///Port x configuration bit 12 constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> ot12{}; ///Port x configuration bit 11 constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> ot11{}; ///Port x configuration bit 10 constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> ot10{}; ///Port x configuration bit 9 constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> ot9{}; ///Port x configuration bit 8 constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> ot8{}; ///Port x configuration bit 7 constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> ot7{}; ///Port x configuration bit 6 constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> ot6{}; ///Port x configuration bit 5 constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ot5{}; ///Port x configuration bit 4 constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ot4{}; ///Port x configuration bit 3 constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ot3{}; ///Port x configuration bit 2 constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ot2{}; ///Port x configuration bit 1 constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ot1{}; ///Port x configuration bit 0 constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ot0{}; } namespace GpiodOspeedr{ ///<GPIO port output speed register using Addr = Register::Address<0x48000c08,0x00000000,0x00000000,std::uint32_t>; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> ospeedr15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> ospeedr14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::ReadWriteAccess,unsigned> ospeedr13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,unsigned> ospeedr12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> ospeedr11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> ospeedr10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,unsigned> ospeedr9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> ospeedr8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> ospeedr7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> ospeedr6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> ospeedr5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> ospeedr4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> ospeedr3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> ospeedr2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> ospeedr1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> ospeedr0{}; } namespace GpiodPupdr{ ///<GPIO port pull-up/pull-down register using Addr = Register::Address<0x48000c0c,0x00000000,0x00000000,std::uint32_t>; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> pupdr15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> pupdr14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::ReadWriteAccess,unsigned> pupdr13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,unsigned> pupdr12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> pupdr11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> pupdr10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,unsigned> pupdr9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pupdr8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> pupdr7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> pupdr6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> pupdr5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> pupdr4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> pupdr3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> pupdr2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> pupdr1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> pupdr0{}; } namespace GpiodIdr{ ///<GPIO port input data register using Addr = Register::Address<0x48000c10,0xffff0000,0x00000000,std::uint32_t>; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> idr15{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> idr14{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> idr13{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> idr12{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> idr11{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> idr10{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> idr9{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> idr8{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> idr7{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> idr6{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> idr5{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> idr4{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> idr3{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> idr2{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> idr1{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> idr0{}; } namespace GpiodOdr{ ///<GPIO port output data register using Addr = Register::Address<0x48000c14,0xffff0000,0x00000000,std::uint32_t>; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> odr15{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> odr14{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> odr13{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> odr12{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> odr11{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> odr10{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> odr9{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> odr8{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> odr7{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> odr6{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> odr5{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> odr4{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> odr3{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> odr2{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> odr1{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> odr0{}; } namespace GpiodBsrr{ ///<GPIO port bit set/reset register using Addr = Register::Address<0x48000c18,0x00000000,0x00000000,std::uint32_t>; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> br15{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> br14{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> br13{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> br12{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> br11{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> br10{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> br9{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> br8{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> br7{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> br6{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> br5{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> br4{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> br3{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> br2{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> br1{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> br0{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> bs15{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> bs14{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> bs13{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> bs12{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> bs11{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> bs10{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> bs9{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> bs8{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> bs7{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> bs6{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> bs5{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> bs4{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> bs3{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> bs2{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> bs1{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> bs0{}; } namespace GpiodLckr{ ///<GPIO port configuration lock register using Addr = Register::Address<0x48000c1c,0xfffe0000,0x00000000,std::uint32_t>; ///Port x lock bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> lckk{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> lck15{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> lck14{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> lck13{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> lck12{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> lck11{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> lck10{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> lck9{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> lck8{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> lck7{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> lck6{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> lck5{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> lck4{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> lck3{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> lck2{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> lck1{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> lck0{}; } namespace GpiodAfrl{ ///<GPIO alternate function low register using Addr = Register::Address<0x48000c20,0x00000000,0x00000000,std::uint32_t>; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> afrl7{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> afrl6{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::ReadWriteAccess,unsigned> afrl5{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> afrl4{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::ReadWriteAccess,unsigned> afrl3{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> afrl2{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> afrl1{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> afrl0{}; } namespace GpiodAfrh{ ///<GPIO alternate function high register using Addr = Register::Address<0x48000c24,0x00000000,0x00000000,std::uint32_t>; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> afrh15{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> afrh14{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::ReadWriteAccess,unsigned> afrh13{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> afrh12{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::ReadWriteAccess,unsigned> afrh11{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> afrh10{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> afrh9{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> afrh8{}; } namespace GpiodBrr{ ///<Port bit reset register using Addr = Register::Address<0x48000c28,0xffff0000,0x00000000,std::uint32_t>; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> br0{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> br1{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> br2{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> br3{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> br4{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> br5{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> br6{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> br7{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> br8{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> br9{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> br10{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> br11{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> br12{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> br13{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> br14{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> br15{}; } }
;; $Header: /cvsroot/uuu/dimension/cell/memory/noblame/noblame.asm,v 1.2 2002/01/23 01:53:50 jmony Exp $ ;; ;; Little simplified memory manager. It doesn't accept memory deallocations, ;; and uses a simple unique pointer for memory allocations. Now if things ;; fails while using this memory manager, it is because something else is ;; broken. ;; ;; by EKS, on a desperate day. ;; $Revision: 1.2 $ ;; [bits 32] %define EXTENDED_RAM 4 ; number of MB of RAM on your system %define CONVENTIONAL_RAM 640 ; number of KB of Conventional ram extern __CORE_HEADER__ section .c_init global _start: _start: _c_init_start: push esi mov esi, __CORE_HEADER__ add esi, dword [esi + hdr_core.core_size] cmp esi, 0x00100000 jb short .in_conventional .in_extended: mov [extended_low_limit], esi sub esi, 0x00100000 sub [mem.free_ram], esi mov esi, 0x00000500 .in_conventional: ; esi = end of core address mov [conventional_low_limit], esi sub [mem.free_ram], esi pop esi section .text _text_start: globalfunc mem.realloc ;--------------------- ; resizes a block of memory ; ; parameters: ; ----------- ; EAX = base address of block to resize ; ECX = new size ; ; returned values: ; ---------------- ; EAX = size of block requested (ecx from call) ; ECX = actuall size of memory allocated ; EDI = new memory location ; registers and errors as usual push esi push ecx push eax call mem.alloc jc .error pop esi push ecx push edi shr ecx, 2 rep movsd pop edi pop ecx pop eax pop esi clc retn .error: pop edi pop eax pop esi mov eax, __ERROR_INSUFFICIENT_MEMORY__ stc retn globalfunc mem.alloc ;------------------------------- ;> ;; param: ecx = mem requested ;; returns: edi = block allocated ;; cf = 1 if error occured, eax = error code ;< push ecx add ecx, byte 63 and cl, 0xFF-63 mov edi, dword [extended_mem_top] sub edi, ecx cmp edi, dword [extended_low_limit] jae short .validated pop eax mov eax, __ERROR_INSUFFICIENT_MEMORY__ stc retn .validated: mov dword [extended_mem_top], edi sub dword [mem.free_ram], ecx add dword [mem.used_ram], ecx pop eax clc retn globalfunc mem.alloc_20bit_address ;--------------------------------- ;> ;; params: ecx = mem requested ;; returns: edi = block allocated ;; cf = 1 if error occured, eax = error code ;< push edi add ecx, byte 63 and cl, 0xFF-63 mov edi, dword [conventional_mem_top] sub edi, ecx cmp edi, dword [conventional_low_limit] jae short .successful pop edi mov eax, __ERROR_INSUFFICIENT_MEMORY__ stc retn .successful: mov dword [conventional_mem_top], edi add dword [mem.used_ram], ecx add esp, byte 4 clc retn globalfunc mem.dealloc ;--------------------------------- ;> ;; params: eax = pointer to memblock to free ;; returns: cf = 1 if failed, eax = error code ;< clc retn section .data _data_start: globalfunc mem.used_ram dd 0 globalfunc mem.used_swap dd 0 globalfunc mem.free_ram dd ((EXTENDED_RAM * 0x00100000) - 0x00100000) + (CONVENTIONAL_RAM * 1024) globalfunc mem.free_swap dd 0 conventional_low_limit: dd 0 conventional_mem_top: dd CONVENTIONAL_RAM * 1024 extended_low_limit: dd 0x00100000 extended_mem_top: dd EXTENDED_RAM * 0x00100000
; A122625: n_{n^2}. ; Submitted by Jamie Morken(s2) ; 1,2,3,4,5,6,7,8,9,100,122,146,172,200,230,262,296,332,370,800,883,970,1061,1156,1255,1358,1465,1576,1691,2700,2884,3074,3270,3472,3680,3894,4114,4340,4572,6400,6725,7058,7399,7748,8105,8470,8843,9224,9613,12500 add $0,1 mov $2,$0 div $2,10 mul $2,$0 mul $2,$0 mod $0,10 add $0,$2
#include <map> #include <set> #include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <gflags/gflags.h> #include <glog/logging.h> #include <boost/algorithm/string.hpp> #include "sales_data.h" /*** * 输出流文件结束标志 Ctrl + D */ using namespace std; bool compareIsbn(const Sales_data &lhs, const Sales_data & rhs) { return lhs.isbn() < rhs.isbn(); } int map_test() { map<string, int> word_count; string word; string word_origin; while(cin >> word){ word_origin = word; // 全部转换为小写 transform(word.begin(), word.end(), word.begin(), (int (*)(int))tolower); ++word_count[word]; } // 使用基于范围的 for 语句遍历 map for(const auto & w : word_count){ cout << w.first << " occurs " << w.second << (w.second > 1 ? " times" : "time") << endl; } map<string, size_t> word_cot; map<string, string> authors = { {"Joyce", "James"}, {"Austen", "Jane"}, {"Dickens", "Charles"} }; vector<int> ivec; for (vector<int>::size_type i = 0; i <= 10; ++i){ ivec.push_back(i); ivec.push_back(i); } set<int> iset(ivec.begin(), ivec.end()); multiset<int> imset(ivec.begin(), ivec.end()); auto iter_begin = iset.begin(); iter_begin++; iset.erase(iter_begin, iset.end()); cout << "ivec: " << ivec.size() << endl; cout << "iset: " << iset.size() << endl; cout << "imset: " << imset.size() << endl; /// typedef bool (*isbn_type) (const Sales_data &lhs, const Sales_data & rhs); // multiset<Sales_data, decltype(compareIsbn) *> bookStore(compareIsbn); multiset<Sales_data, isbn_type> bookStore(compareIsbn); return 0; } map<string, string> build_map(ifstream &map_file) { map<string, string> trans_map; string key, value; while(map_file >> key && getline(map_file, value)){ // cout << key << endl; if( value.size() > 1) // 检查是否有转换规则 trans_map[key] = value.substr(1); else throw runtime_error("no rule(s) for " + key); } return trans_map; } const string transform(string &s, map<string, string> &t_map ) { auto map_it = t_map.find(s); if ( map_it != t_map.cend() ) return map_it->second; else return s; } void word_tansform(ifstream &map_file, ifstream &input) { auto trans_map = build_map(map_file); string text; // 以行为单位处理文件中 while(getline(input, text)){ istringstream stream(text); string word; bool first_word = true; // 处理每一行语句 while(stream >> word){ if(first_word) first_word = false; else cout << " "; cout << transform(word, trans_map); } cout << endl; } } namespace klm{ void GlobalInit(int* pargc, char*** pargv) { // Google flags. ::google::ParseCommandLineFlags(pargc, pargv, true); // Google logging. ::google::InitGoogleLogging(*(pargv)[0]); // Provide a backtrace on segfault. ::google::InstallFailureSignalHandler(); } } // end of namespace klm DEFINE_string(gpus, "", " separated by ','. -gpu all to run all gpus"); DEFINE_int32(iterations, 0, "int number foro test"); int main(int argc, char *argv[]) { // :google::InitGoogleLogging(argv[0]); klm::GlobalInit(&argc, &argv); // 打印输出到 stderr (当使用 logging 时). FLAGS_alsologtostderr = 1; LOG(INFO) << "glog is running"; ifstream map_file("/home/klm/work/gitwork/work_note/dev_tools/cpp/code/cpp_primer_5nd/map_instance/map.txt"); ifstream input_file("/home/klm/work/gitwork/work_note/dev_tools/cpp/code/cpp_primer_5nd/map_instance/test.txt"); word_tansform(map_file, input_file); LOG(INFO) << "word_tansform done "; vector<string> gpus; // string flags_gpus(FLAGS_gpus); if(0 == strcmp(FLAGS_gpus.c_str(), "all")) LOG(INFO) << "Using GPUS: 0, 1, 2, 3, 4, 5, 6, 7, 8"; else { boost::split(gpus, FLAGS_gpus, boost::is_any_of(",")); for(auto &gpu: gpus) cout << gpu << endl; } LOG(INFO) << FLAGS_iterations; return 0; }
; int feof_fastcall(FILE *stream) INCLUDE "config_private.inc" SECTION code_clib SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _feof_fastcall EXTERN asm_feof _feof_fastcall: push hl ex (sp),ix call asm_feof pop ix ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _feof_fastcall EXTERN _feof_unlocked_fastcall defc _feof_fastcall = _feof_unlocked_fastcall ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
format binary as 'gba' include 'flash.inc' include '../lib/constants.inc' include '../lib/macros.inc' macro m_exit test { mov r12, test b eval } header: include '../lib/header.asm' main: m_test_init ; Reset test register mov r12, 0 mov r11, MEM_SRAM b flash_common flash: ; Fake flash save type dw 'FLAS' dw 'H_V ' dw 'FLAS' dw 'H512' dw '_V ' include 'flash.asm' eval: m_vsync m_test_eval r12 idle: b idle include '../lib/text.asm'
section .data maxlen: equ 1024 prompt: db "Enter your name (max 1024 characters): ", 0 result: db "Nice to meet you, ", 0 section .bss buffer: resb maxlen section .text global _start _start: mov rax, prompt call print mov rax, 0 mov rdi, 0 mov rsi, buffer mov rdx, maxlen syscall mov rax, result call print mov rax, buffer call print jmp exit strlen: mov rbx, rax strlen_loop: cmp byte[rbx], 0 je strlen_stop inc rbx jmp strlen_loop strlen_stop: sub rbx, rax ret print: push rax push rbx push rdi push rsi push rdx call strlen mov rsi, rax mov rdx, rbx mov rax, 1 mov rdi, 1 syscall pop rdx pop rsi pop rdi pop rbx pop rax ret exit: mov rax, 60 mov rdi, 0 syscall
; A257175: The smallest m such that the m-th triangular number is greater than or equal to half the n-th triangular number. ; 0,1,2,2,3,4,5,5,6,7,7,8,9,10,10,11,12,12,13,14,14,15,16,17,17,18,19,19,20,21,22,22,23,24,24,25,26,27,27,28,29,29,30,31,31,32,33,34,34,35,36,36,37,38,39,39,40,41,41,42,43,43,44,45,46,46,47,48,48,49,50,51,51,52,53,53,54,55,56,56,57,58,58,59,60,60,61,62,63,63,64,65,65,66,67,68,68,69,70,70 lpb $0 add $2,$0 sub $0,1 lpe lpb $2 add $0,1 sub $2,$0 trn $2,$0 lpe
; A029001: Expansion of 1/((1-x)(1-x^2)(1-x^3)(1-x^7)). ; 1,1,2,3,4,5,7,9,11,14,17,20,24,28,33,38,44,50,57,64,72,81,90,100,111,122,134,147,161,175,191,207,224,242,261,281,302,324,347,371,396,422,450,478,508,539,571,604,639 mov $1,17 lpb $0,1 mov $2,$0 sub $0,1 cal $2,25768 ; Expansion of 1/((1-x)*(1-x^3)*(1-x^7)). sub $0,1 add $1,$2 lpe sub $1,16
; A040250: Continued fraction for sqrt(267). ; Submitted by Christian Krause ; 16,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1,15,1,2,32,2,1 seq $0,10222 ; Continued fraction for sqrt(178). seq $0,96022 ; Numbers that are congruent to {15, 27, 39, 51} mod 60. div $0,12 sub $0,1
; A098296: Member r=11 of the family of Chebyshev sequences S_r(n) defined in A092184. ; Submitted by Christian Krause ; 0,1,11,100,891,7921,70400,625681,5560731,49420900,439227371,3903625441,34693401600,308336988961,2740339499051,24354718502500,216452127023451,1923714424708561,17096977695353600,151949084833473841,1350444785805910971,12002053987419724900,106668041100971613131,948010315921324793281,8425424802190951526400,74880812903797238944321,665501891331984198972491,5914636209084060551808100,52566223990424560767300411,467181379704736986353895601,4152066193352208316417760000,36901414360465137861405944401 mov $3,1 lpb $0 sub $0,1 mul $1,7 add $3,$1 add $2,$3 mov $1,$2 add $3,2 lpe mov $0,$1
; A113636: In the sequence of positive integers add 1 to each nonprime number. ; 2,2,3,5,5,7,7,9,10,11,11,13,13,15,16,17,17,19,19,21,22,23,23,25,26,27,28,29,29,31,31,33,34,35,36,37,37,39,40,41,41,43,43,45,46,47,47,49,50,51,52,53,53,55,56,57,58,59,59,61,61,63,64,65,66,67,67,69,70,71,71,73 mov $1,$0 cal $0,105661 ; a(n)=1 if n is a prime, 2 if n is an even semiprime, otherwise 0. sub $0,1 lpb $0 mov $0,$2 add $1,1 lpe add $1,1
; A274830: Numbers n such that 7*n+1 is a triangular number (A000217). ; 0,2,5,11,17,27,36,50,62,80,95,117,135,161,182,212,236,270,297,335,365,407,440,486,522,572,611,665,707,765,810,872,920,986,1037,1107,1161,1235,1292,1370,1430,1512,1575,1661,1727,1817,1886,1980,2052,2150,2225,2327,2405,2511,2592,2702,2786,2900,2987,3105,3195,3317,3410,3536,3632,3762,3861,3995,4097,4235,4340,4482,4590,4736,4847,4997,5111,5265,5382,5540,5660,5822,5945,6111,6237,6407,6536,6710,6842,7020,7155,7337,7475,7661,7802,7992,8136,8330,8477,8675,8825,9027,9180,9386,9542,9752,9911,10125,10287,10505,10670,10892,11060,11286,11457,11687,11861,12095,12272,12510,12690,12932,13115,13361,13547,13797,13986,14240,14432,14690,14885,15147,15345,15611,15812,16082,16286,16560,16767,17045,17255,17537,17750,18036,18252,18542,18761,19055,19277,19575,19800,20102,20330,20636,20867,21177,21411,21725,21962,22280,22520,22842,23085,23411,23657,23987,24236,24570,24822,25160,25415,25757,26015,26361,26622,26972,27236,27590,27857,28215,28485,28847,29120,29486,29762,30132,30411,30785,31067,31445,31730,32112,32400,32786,33077,33467,33761,34155,34452,34850,35150,35552,35855,36261,36567,36977,37286,37700,38012,38430,38745,39167,39485,39911,40232,40662,40986,41420,41747,42185,42515,42957,43290,43736,44072,44522,44861,45315,45657,46115,46460,46922,47270,47736,48087,48557,48911,49385,49742,50220,50580,51062,51425,51911,52277,52767,53136,53630,54002,54500 mov $2,$0 lpb $2,1 mov $3,$2 add $3,$0 lpb $3,1 add $1,$2 trn $3,$2 lpe trn $0,2 sub $2,1 lpe
; Add ALTTP items to SM ; ; Extra message box code lifted from MessageBoxV4 by Kejardon, JAM !IBranchItem = #$887C !ISetItem = #$8899 !ILoadSpecialGraphics = #$8764 !ISetGoto = #$8A24 !ISetPreInstructionCode = #$86C1 !IDrawCustom1 = #$E04F !IDrawCustom2 = #$E067 !IGoto = #$8724 !IKill = #$86BC !IPlayTrackNow = #$8BDD !IJSR = #$8A2E !ISetCounter8 = #$874E !IGotoDecrement = #$873F !IGotoIfDoorSet = #$8A72 !ISleep = #$86B4 !IVisibleItem = #i_visible_item !IChozoItem = #i_chozo_item !IHiddenItem = #i_hidden_item !ILoadCustomGraphics = #i_load_custom_graphics !IPickup = #i_pickup !IStartDrawLoop = #i_start_draw_loop !IStartHiddenDrawLoop = #i_start_hidden_draw_loop !ITEM_PLM_BUF = $7ffb00 !SM_MULTIWORLD_PICKUP = $7ffafe !Big = #$825A !Small = #$8289 !EmptySmall = #$8436 !Shot = #$83C5 !Dash = #$83CC !Jump = #$8756 !ItemCancel = #$875D !ItemSelect = #$8764 !AimDown = #$876B !AimUp = #$8773 !EmptyBig = #EmptyBig !PlaceholderBig = #PlaceholderBig !DungeonItemBig = #DungeonItemBig !DungeonKeyItemBig = #DungeonKeyItemBig !KeycardBig = #KeycardBig ; org $01E9BC ; db $d1 ; org $cf8432 ; dw $efe0 ; org $cf8432+$5 ; db $D2 ;org $cf86de ; dw $efe4 ; Morph to progressive sword org $C22D7C ; Patch to Crateria surface palette for Z3 items e.g. PoH, Pearl incbin "data/Crateria_palette.bin" org $C23798 ; Crocomire's room changes colors $2E, $2F, $3E, and $3F for reasons unknown. incbin "data/Crocomire_palette.bin" org $c98000 ; New item graphics base $898000 incbin "data/newitems.bin" org $c4efe0 ; First free space in PLM block base $84efe0 plm_items: dw i_visible_item_setup, v_item ;efe0 dw i_visible_item_setup, c_item ;efe4 dw i_hidden_item_setup, h_item ;efe8 v_item: dw !IVisibleItem c_item: dw !IChozoItem h_item: dw !IHiddenItem ; Graphics pointers for items (by item index) item_graphics: ; SM (B0-FF) dw $8800 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Grapple beam dw $8900 : db $01, $01, $00, $00, $03, $03, $00, $00 ; X-ray scope dw $8300 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Varia suit dw $8200 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Spring ball dw $8700 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Morph ball dw $8500 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Screw attack dw $8100 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Gravity suit dw $8400 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Hi-Jump dw $8600 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Space jump dw $8000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Bombs dw $8A00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Speed booster dw $8B00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Charge dw $8C00 : db $00, $03, $00, $00, $00, $03, $00, $00 ; Ice Beam dw $8D00 : db $00, $02, $00, $00, $00, $02, $00, $00 ; Wave beam dw $8F00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Spazer dw $8E00 : db $00, $01, $00, $00, $00, $01, $00, $00 ; Plasma beam ; C0 dw $0008 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Energy Tank dw $9000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; Reserve tank dw $000A : db $00, $00, $00, $00, $00, $00, $00, $00 ; Missile dw $000C : db $00, $00, $00, $00, $00, $00, $00, $00 ; Super Missile dw $000E : db $00, $00, $00, $00, $00, $00, $00, $00 ; Power Bomb dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; C5 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; C6 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; C7 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; C8 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; C9 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; CA - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; CB - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; CC - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; CD - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; CE - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; CF - Unused dw $EE00 : db $03, $00, $00, $00, $03, $00, $00, $00 ; D0 - Crateria L1 Key dw $EF00 : db $02, $00, $00, $00, $02, $00, $00, $00 ; D1 - Crateria L2 Key dw $F000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; D2 - Crateria Boss Key dw $EE00 : db $03, $00, $00, $00, $03, $00, $00, $00 ; D3 - Brinstar L1 Key dw $EF00 : db $02, $00, $00, $00, $02, $00, $00, $00 ; D4 - Brinstar L2 Key dw $F000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; D5 - Brinstar Boss Key dw $EE00 : db $03, $00, $00, $00, $03, $00, $00, $00 ; D6 - Norfair L1 Key dw $EF00 : db $02, $00, $00, $00, $02, $00, $00, $00 ; D7 - Norfair L2 Key dw $F000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; D8 - Norfair Boss Key dw $EE00 : db $03, $00, $00, $00, $03, $00, $00, $00 ; D9 - Maridia L1 Key dw $EF00 : db $02, $00, $00, $00, $02, $00, $00, $00 ; DA - Maridia L2 Key dw $F000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; DB - Maridia Boss Key dw $EE00 : db $03, $00, $00, $00, $03, $00, $00, $00 ; DC - Wrecked Ship L1 Key dw $F000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; DD - Wrecked Ship Boss Key dw $EE00 : db $03, $00, $00, $00, $03, $00, $00, $00 ; DE - Lower Norfair L1 Key dw $F000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; DF - Lower Norfair Boss Key dw $F500 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E0 - L1 Key Plaque dw $F600 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E1 - L2 Key Plaque dw $F700 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E2 - Boss Key Plaque dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E3 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E4 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E5 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E6 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E7 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E8 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; E9 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; EA - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; EB - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; EC - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; ED - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; EE - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; EF - Unused ; ALTTP (00-AF) dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 00 Dummy - L1SwordAndShield dw $CA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 01 Master Sword dw $CB00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 02 Tempered Sword dw $CC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 03 Gold Sword dw $CF00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 04 Blue Shield dw $D000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 05 Red Shield dw $D100 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 06 Mirror Shield dw $AF00 : db $02, $00, $00, $00, $02, $00, $00, $00 ; 07 Fire Rod dw $B000 : db $00, $03, $00, $00, $00, $03, $00, $00 ; 08 Ice Rod dw $B500 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 09 Hammer dw $9100 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 0A Hookshot dw $9200 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 0B Bow dw $DF00 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 0C Blue Boomerang dw $9700 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 0D Powder dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 0E Bee (bottle contents) dw $B100 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 0F Bombos dw $B200 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 10 Ether dw $B300 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 11 Quake dw $B400 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 12 Lamp dw $B600 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 13 Shovel dw $B700 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 14 Flute dw $C100 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 15 Somaria dw $BA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 16 Empty Bottle dw $D200 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 17 Heart Piece dw $C200 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 18 Cane of Byrna dw $C300 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 19 Cape dw $C400 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 1A Mirror dw $C500 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 1B Gloves dw $C600 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 1C Titan's Mitts dw $B900 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 1D Book dw $C800 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 1E Flippers dw $C900 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 1F Moon Pearl dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 20 Dummy dw $B800 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 21 Bug-Catching Net dw $CD00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 22 Blue Tunic dw $CE00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 23 Red Tunic dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 24 Dummy - Key dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 25 Dummy - Compass dw $D300 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 26 Heart Container (no animation) dw $9400 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 27 One bomb dw $D700 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 28 3 Bombs dw $9600 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 29 Mushroom dw $E000 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 2A Red Boomerang dw $BB00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 2B Red Potion Bottle dw $BC00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 2C Green Potion Bottle dw $BD00 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 2D Blue Potion Bottle dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 2E Dummy - Red potion (contents) dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 2F Dummy - Green potion (contents) dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 30 Dummy - Blue potion (contents) dw $D800 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 31 10 Bombs dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 32 Dummy - Big key dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 33 Dummy - Map dw $D900 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 34 1 Rupee dw $DA00 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 35 5 Rupees dw $DB00 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 36 20 Rupees dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 37 Dummy - Pendant of Courage dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 38 Dummy - Pendant of Wisdom dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 39 Dummy - Pendant of Power dw $9200 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 3A Bow and Arrows dw $DE00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 3B Silver Arrows dw $BE00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 3C Bee Bottle dw $C000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 3D Fairy Bottle dw $D300 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 3E Heart Container - Boss dw $D300 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 3F Heart Container - Sanc dw $DD00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 40 100 Rupees dw $DC00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 41 50 Rupees dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 42 Dummy - Small heart dw $D400 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 43 Single Arrow dw $D600 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 44 10 Arrows dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 45 Dummy - Small magic dw $9300 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 46 300 Rupees dw $DB00 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 47 20 Rupees dw $BF00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 48 Good Bee Bottle dw $E700 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 49 Fighter Sword dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 4A Dummy - Activated flute dw $C700 : db $02, $02, $02, $02, $02, $02, $02, $02 ; 4B Boots dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 4C Dummy - 50 Bomb upgrade dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 4D Dummy - 70 Arrow upgrade dw $E100 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 4E Half Magic dw $E200 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 4F Quarter Magic dw $CA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 50 Master Sword dw $E300 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 51 5 Bomb Upgrade dw $E400 : db $03, $03, $03, $03, $03, $03, $03, $03 ; 52 10 Bomb Upgrade dw $E500 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 53 5 Arrow Upgrade dw $E600 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 54 10 Arrow Upgrade dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 55 Dummy - Programmable 1 dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 56 Dummy - Programmable 2 dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 57 Dummy - Programmable 3 dw $DE00 : db $01, $01, $01, $01, $01, $01, $01, $01 ; 58 Silver Arrows dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 59 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5A - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5B - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5C - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5D - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5E - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5F - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 60 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 61 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 62 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 63 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 64 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 65 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 66 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 67 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 68 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 69 - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 6A - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 6B - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 6C - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 6D - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 6E - Unused dw $0000 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 6F - Unused dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 70 - Unused dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 71 - Unused dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 72 - Ganons Tower Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 73 - Turtle Rock Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 74 - Thieves' Town Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 75 - Tower of Hera Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 76 - Ice Palace Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 77 - Skull Woods Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 78 - Misery Mire Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 79 - Palace Of Darkness Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 7A - Swamp Palace Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 7B - Unused dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 7C - Desert Palace Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 7D - Eastern Palace Map dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 7E - Unused dw $ED00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 7F - Hyrule Castle Map dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 80 - Unused dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 81 - Unused dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 82 - Ganons Tower Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 83 - Turtle Rock Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 84 - Thieves' Town Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 85 - Tower of Hera Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 86 - Ice Palace Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 87 - Skull Woods Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 88 - Misery Mire Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 89 - Palace of Darkness Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 8A - Swamp Palace Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 8B - Unused dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 8C - Desert Palace Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 8D - Eastern Palace Compass dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 8E - Unused dw $EC00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 8F - Unused dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 90 - Unused dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 91 - Unused dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 92 - Ganons Tower Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 93 - Turtle Rock Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 94 - Thieves' Town Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 95 - Tower of Hera Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 96 - Ice Palace Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 97 - Skull Woods Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 98 - Misery Mire Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 99 - Palace of Darkness Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 9A - Swamp Palace Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 9B - Unused dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 9C - Desert Palace Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 9D - Eastern Palace Big Key dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 9E - Unused dw $EA00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 9F - Unused dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A0 - Hyrule Castle Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A1 - Unused dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A2 - Unused dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A3 - Desert Palace Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A4 - Castle Tower Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A5 - Swamp Palace Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A6 - Palace of Darkness Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A7 - Misery Mire Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A8 - Skull Woods Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; A9 - Ice Palace Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; AA - Tower of Hera Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; AB - Thieves' Town Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; AC - Turtle Rock Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; AD - Ganons Tower Small Key dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; AE - Unused dw $EB00 : db $00, $00, $00, $00, $00, $00, $00, $00 ; AF - Unused ;dw $D300 : db $02, $02, $02, $02, $02, $02, $02, $02 ; Heart Container ;dw $D500 : db $00, $00, $00, $00, $00, $00, $00, $00 ; 5 Arrows sm_item_table: ; pickup, qty, msg, type, ext2, ext3, loop, hloop dw $891A, $4000, $0000, $0004, $0000, $0000, $0000, $0000 ; Grapple dw $8941, $8000, $0000, $0004, $0000, $0000, $0000, $0000 ; X-ray scope dw $88F3, $0001, $0007, $0004, $0000, $0000, $0000, $0000 ; Varia suit dw $88F3, $0002, $0008, $0004, $0000, $0000, $0000, $0000 ; Spring ball dw $88F3, $0004, $0009, $0004, $0000, $0000, $0000, $0000 ; Morph ball dw $88F3, $0008, $000A, $0004, $0000, $0000, $0000, $0000 ; Screw attack dw $88F3, $0020, $001A, $0004, $0000, $0000, $0000, $0000 ; Gravity suit dw $88F3, $0100, $000B, $0004, $0000, $0000, $0000, $0000 ; Hi-jump dw $88F3, $0200, $000C, $0004, $0000, $0000, $0000, $0000 ; Space jump dw $88F3, $1000, $0013, $0004, $0000, $0000, $0000, $0000 ; Bombs dw $88F3, $2000, $000D, $0004, $0000, $0000, $0000, $0000 ; Speed booster dw $88B0, $1000, $000E, $0005, $0000, $0000, $0000, $0000 ; Charge beam dw $88B0, $0002, $000F, $0005, $0000, $0000, $0000, $0000 ; Ice beam dw $88B0, $0001, $0010, $0005, $0000, $0000, $0000, $0000 ; Wave beam dw $88B0, $0004, $0011, $0005, $0000, $0000, $0000, $0000 ; Spazer dw $88B0, $0008, $0012, $0005, $0000, $0000, $0000, $0000 ; Plasma dw $8968, $0064, $0000, $0000, $0000, $0000, $E0A5, #p_etank_hloop ; E-Tank dw $8986, $0064, $0000, $0006, $0000, $0000, $0000, $0000 ; Reserve tank dw $89A9, $0005, $0000, $0001, $0000, $0000, $E0CA, #p_missile_hloop ; Missiles dw $89D2, $0005, $0000, $0002, $0000, $0000, $E0EF, #p_super_hloop ; Super Missiles dw $89FB, $0005, $0000, $0003, $0000, $0000, $E114, #p_pb_hloop ; Power Bombs progressive_items: db $5e, $59, $04, $49, $01, $02, $03, $00 ; Progressive sword db $5f, $5A, $03, $04, $05, $06, $00, $00 ; Progressive shield db $60, $5B, $02, $22, $23, $00, $00, $00 ; Progressive armor db $61, $54, $02, $1b, $1c, $00, $00, $00 ; Progressive glove db $ff i_visible_item: lda #$0006 jsr i_load_rando_item rts i_chozo_item: lda #$0008 jsr i_load_rando_item rts i_hidden_item: lda #$000A jsr i_load_rando_item rts p_etank_hloop: dw $0004, $a2df dw $0004, $a2e5 dw !IGotoDecrement, p_etank_hloop dw !IJSR, $e020 dw !IGoto, p_hidden_item_loop2 p_missile_hloop: dw $0004, $A2EB dw $0004, $A2F1 dw !IGotoDecrement, p_missile_hloop dw !IJSR, $e020 dw !IGoto, p_hidden_item_loop2 p_super_hloop: dw $0004, $A2F7 dw $0004, $A2FD dw !IGotoDecrement, p_super_hloop dw !IJSR, $e020 dw !IGoto, p_hidden_item_loop2 p_pb_hloop: dw $0004, $A303 dw $0004, $A309 dw !IGotoDecrement, p_pb_hloop dw !IJSR, $e020 dw !IGoto, p_hidden_item_loop2 p_visible_item: dw !ILoadCustomGraphics dw !IBranchItem, .end dw !ISetGoto, .trigger dw !ISetPreInstructionCode, $df89 dw !IStartDrawLoop .loop dw !IDrawCustom1 dw !IDrawCustom2 dw !IGoto, .loop .trigger dw !ISetItem dw SOUNDFX : db !Click dw !IPickup .end dw !IGoto, $dfa9 p_chozo_item: dw !ILoadCustomGraphics dw !IBranchItem, .end dw !IJSR, $dfaf dw !IJSR, $dfc7 dw !ISetGoto, .trigger dw !ISetPreInstructionCode, $df89 dw !ISetCounter8 : db $16 dw !IStartDrawLoop .loop dw !IDrawCustom1 dw !IDrawCustom2 dw !IGoto, .loop .trigger dw !ISetItem dw SOUNDFX : db !Click dw !IPickup .end dw $0001, $a2b5 dw !IKill p_hidden_item: dw !ILoadCustomGraphics .loop2 dw !IJSR, $e007 dw !IBranchItem, .end dw !ISetGoto, .trigger dw !ISetPreInstructionCode, $df89 dw !ISetCounter8 : db $16 dw !IStartHiddenDrawLoop .loop dw !IDrawCustom1 dw !IDrawCustom2 dw !IGotoDecrement, .loop dw !IJSR, $e020 dw !IGoto, .loop2 .trigger dw !ISetItem dw SOUNDFX : db !Click dw !IPickup .end dw !IJSR, $e032 dw !IGoto, .loop2 i_start_draw_loop: phy : phx lda !ITEM_PLM_BUF, x ; Load item id cmp #$0015 bcc .smItem bra .custom_item .smItem asl #4 clc : adc #$000C tax lda sm_item_table, x ; Load next loop point if available beq .custom_item plx : ply tay rts .custom_item plx ply rts i_start_hidden_draw_loop: phy : phx lda !ITEM_PLM_BUF, x ; Load item id cmp #$0015 bcc .smItem bra .custom_item .smItem asl #4 clc : adc #$000E tax lda sm_item_table, x ; Load next loop point if available beq .custom_item plx : ply tay rts .custom_item plx ply rts i_load_custom_graphics: phy : phx lda !ITEM_PLM_BUF, x ; Load item id %a8() sta $4202 lda #$0A sta $4203 nop : nop : %ai16() lda $4216 ; Multiply it by 0x0A clc adc #item_graphics tay ; Add it to the graphics table and transfer into Y lda $0000, y cmp #$8000 bcc .no_custom jsr $8764 ; Jump to original PLM graphics loading routine plx ply rts .no_custom tay lda $0000, y sta.l $7edf0c, x plx ply rts i_visible_item_setup: phy : phx jsr load_item_id %a8() sta $4202 lda #$0A sta $4203 nop : nop : %ai16() lda $4216 ; Multiply it by 0x0A tax lda item_graphics, x cmp #$8000 bcc .no_custom plx : ply jmp $ee64 .no_custom plx : ply tyx sta.l $7edf0c, x jmp $ee64 i_hidden_item_setup: phy : phx jsr load_item_id %a8() sta $4202 lda #$0A sta $4203 nop : nop : %ai16() lda $4216 ; Multiply it by 0x0A tax lda item_graphics, x cmp #$8000 bcc .no_custom plx : ply jmp $ee8e .no_custom plx : ply tyx sta.l $7edf0c, x jmp $ee8e i_load_rando_item: cmp #$0006 : bne + ldy #p_visible_item bra .end + cmp #$0008 : bne + ldy #p_chozo_item bra .end + ldy #p_hidden_item .end rts ; Pick up item i_pickup: phx : phy : php : phx lda #$0000 sta !SM_MULTIWORLD_PICKUP lda.l config_multiworld beq .own_item lda $1dc7, x ; Load PLM room argument asl #3 : tax lda.l rando_item_table, x ; Load item type beq .own_item .multiworld_item ; This is someone elses item, send message phx lda.l rando_item_table+$4, x ; Load item owner into Y tay lda.l rando_item_table+$2, x ; Load original item id into X tax pla ; Multiworld item table id in A phx : phy jsl mw_write_message ; Send message ply : plx jsl sm_mw_display_item_sent ; Display custom message box plx bra .end .own_item plx lda !ITEM_PLM_BUF, x ; Load adjusted item id (progression etc) cmp #$0040 bcc .smItem sec sbc #$0040 sta !ITEM_PLM_BUF, x ; Readjust item id so it fits the ALTTP table again jsl alttp_item_pickup bra .end .smItem jsr receive_sm_item bra .end .end plp : ply : plx rts ; Get item ID from randomizer table (and adjust item id to local tables as needed for graphics display) load_item_id: phx : phy lda.l config_multiworld bne .multiworld_item lda $1dc7, y ; Load PLM room argument pha xba : and #$00ff ; Get top 8 bits of room argument as item id tax : pla and #$00ff sta $1dc7, y ; Clear out item ID from room argument (so we don't mess with SRAM item indexes) txa bra .checkItem .multiworld_item lda $1dc7, y ; Load PLM room argument asl #3 : tax lda.l rando_item_table+$2, x ; Load item id from table .checkItem jsr check_upgrade_item cmp #$00b0 ; b0+ = SM Item bcc .alttpItem sec sbc #$00b0 ; Subtract $b0 since we have SM items starting at index 00 bra + .alttpItem clc adc #$0040 ; Offset alttp items by #$40 to point to the correct table entries + ply tyx sta !ITEM_PLM_BUF, x ; Store adjusted item id (used for custom graphics and things) plx rts check_upgrade_item: phx %a8() sta $c5 ldx #$0000 - lda progressive_items, x cmp #$ff beq .notFound cmp $c5 beq .found txa : clc : adc #$08 : tax bne - .found lda progressive_items+$1, x ; Load SRAM index offset phx : tax lda !SRAM_ALTTP_ITEM_BUF, x plx cmp progressive_items+$2, x ; Check against max allowed value beq + inc + stx $c5 : clc : adc $c5 : tax ; Add upgraded item value to x lda progressive_items+$2, x ; Get new item id bra + .notFound lda $c5 + %ai16() and #$00ff plx rts check_upgrade_item_long: phb : phk : plb jsr check_upgrade_item plb rtl receive_sm_item_long: jsr receive_sm_item rtl ; Item index to receive in A receive_sm_item: cmp #$0015 bcs .customItem asl : asl : asl : asl phx clc adc #sm_item_table ; A contains pointer to pickup routine from item table tax tay iny : iny ; Y points to data to be used in item pickup routine jsr ($0000,x) plx rts .customItem cmp #$0020 bcs .keycard bra .end .keycard and #$000f sta $c7 ; Store keycard index clc : adc #$0080 ; Turn this into an event id jsl $8081fa ; Set event (receive keycard) lda !SM_MULTIWORLD_PICKUP bne .multiPickup lda #$0062 jsl $858080 ; Display message 62 - keycard bra .end .multiPickup phx : phy jsr SETFX lda #$0037 jsl $809049 ply : plx lda #$005d jsl $858080 ; Display multiworld message lda #$0000 sta !SM_MULTIWORLD_PICKUP .end rts warnpc $850000 org $c498e3 base $8498e3 CLIPCHECK: LDA $05D7 CMP #$0002 BEQ $0E LDA #$0000 JSL $808FF7 LDA $07F5 JSL $808FC1 LDA #$0000 STA $05D7 RTL CLIPSET: LDA #$0001 STA $05D7 JSL $82BE17 LDA #$0000 RTS SOUNDFX: JSR SETFX AND #$00FF JSL $809049 RTS SPECIALFX: JSR SETFX JSL $8090CB RTS MISCFX: JSR SETFX JSL $80914D RTS SETFX: LDA #$0002 STA $05D7 LDA $0000,y INY RTS sm_mw_call_receive: phx : phy jsr SETFX lda #$0037 jsl $809049 ply : plx jsr ($0000,x) rtl warnpc $849953 org $f30000 ;!SM_INVENTORY_SWAP = $a0638c ;!SM_INVENTORY_SWAP_2 = $a0638e !SM_INVENTORY_SWAP = !SRAM_ALTTP_ITEM_BUF+$8c !SM_INVENTORY_SWAP_2 = !SRAM_ALTTP_ITEM_BUF+$8e alttp_progressive_item: phx lda $0000,y ; Load SRAM offset of progressive item iny : iny ; Y points to value of first progressive item sty $89 tax lda !SRAM_ALTTP_ITEM_BUF,x ; Load current item value and #$00ff asl a ; Shift left for table lookup clc : adc $89 tax ldy $0000,x ; Set Y to next instruction by lookup table plx rtl alttp_item_pickup: phx phy php lda.l config_multiworld beq + lda !SM_MULTIWORLD_PICKUP bne .multiworldItemId + lda !ITEM_PLM_BUF,x ; Load previously saved item index sta $c7 ; Store current item index bra .checkItemSwap .multiworldItemId lda $c1 ; This item was gotten from another player in MW jsl check_upgrade_item_long ; Progress item if needed .checkItemSwap jsl check_item_swap ; Set correct item swap flag if needed asl : asl : asl ; Value * 8 to get a table index tax lda.l alttp_item_table,x ; Get ALTTP SRAM index tay ; Store Index in Y lda.l alttp_item_table+4,x ; Get item type sta.l $89 ; Store item type in temp variable and #$00ff cmp #$0000 beq .normal_item_jmp cmp #$0001 beq .increment_item_jmp cmp #$0002 beq .bottle_item_jmp cmp #$0003 beq .piece_of_heart_jmp cmp #$0004 beq .rupees_jmp cmp #$0005 beq .boots_jmp cmp #$0006 beq .flippers_jmp cmp #$0007 beq .silvers_jmp cmp #$0010 beq .dungeon_jmp cmp #$0011 beq .dungeon_key_jmp jmp .end .normal_item_jmp jmp .normal_item .increment_item_jmp jmp .increment_item .bottle_item_jmp jmp .bottle_item .piece_of_heart_jmp jmp .piece_of_heart .rupees_jmp jmp .rupees .boots_jmp jmp .boots .flippers_jmp jmp .flippers .silvers_jmp jmp .silvers .dungeon_jmp jmp .dungeon .dungeon_key_jmp jmp .dungeon_key .normal_item lda.l alttp_item_table+2,x ; Get Item value phx tyx %a8() cmp.l !SRAM_ALTTP_ITEM_BUF,x ; Prevent downgrades bcc .normal_item_end beq .check_progressive sta.l !SRAM_ALTTP_ITEM_BUF,x ; Save value to ALTTP SRAM .normal_item_end %a16() plx jmp .end .check_progressive pha lda $8a and #$01 cmp #$01 beq + pla sta.l !SRAM_ALTTP_ITEM_BUF,x bra .normal_item_end + pla ; Progressive item that we already have, force upgrade inc a sta.l !SRAM_ALTTP_ITEM_BUF,x %a16() and #$00ff sta $89 plx lda.l alttp_item_table,x sta $87 ; find the new index to the alttp_item_table so we can show the correct text box ldx #$0000 - lda.l alttp_item_table,x cmp.l $87 bne + lda.l alttp_item_table+2,x cmp.l $89 bne + jmp .end + txa clc adc #$0008 tax bra - .increment_item lda.l alttp_item_table+2,x phx tyx %a8() clc adc.l !SRAM_ALTTP_ITEM_BUF,x sta.l !SRAM_ALTTP_ITEM_BUF,x %a16() plx jmp .end .bottle_item phx tyx lda #$0000 %a8() lda.b #$01 sta.l !SRAM_ALTTP_ITEM_BUF,x ; Set we have bottles flag ldx #$0000 - lda.l !SRAM_ALTTP_ITEM_BUF+$5c,x beq .found_bottle_index inx cpx #$0004 bne - %a16() plx jmp .end ; Bail out if we have all bottles already .found_bottle_index txy plx lda.l alttp_item_table+2,x ; Get bottle value phx tyx sta.l !SRAM_ALTTP_ITEM_BUF+$5c,x ; $a0635b,x ; Store bottle value to the correct bottle index %a16() plx jmp .end .piece_of_heart %a8() phx tyx lda.l !SRAM_ALTTP_ITEM_BUF,x ; Load amount of heart pieces inc a ; Increment cmp.b #$04 ; Oh we got 4, then give a real heartpiece bne .no_heartpiece lda #$00 sta.l !SRAM_ALTTP_ITEM_BUF,x ; Reset heartpieces lda.l !SRAM_ALTTP_ITEM_BUF+$6c ; $a0636C clc adc #$08 sta.l !SRAM_ALTTP_ITEM_BUF+$6c ; $a0636C ; Give a heartpiece lda.l !SRAM_ALTTP_ITEM_BUF+$6c sta.l !SRAM_ALTTP_ITEM_BUF+$6d ; Refill Link's Health bra .piece_end .no_heartpiece sta.l !SRAM_ALTTP_ITEM_BUF,x ; Store heartpieces .piece_end lda !SRAM_ALTTP_STATS_BUF+$28 ; Increment global heart piece counter in stats buffer inc a ; Logic copied from z3/randomizer/inventory.asm heartpiece routine and #$1f tax lda !SRAM_ALTTP_STATS_BUF+$28 and #$e0 sta !SRAM_ALTTP_STATS_BUF+$28 txa ora !SRAM_ALTTP_STATS_BUF+$28 sta !SRAM_ALTTP_STATS_BUF+$28 %a16() plx jmp .end .rupees lda.l alttp_item_table+2,x ; 16-bit add phx tyx clc adc.l !SRAM_ALTTP_ITEM_BUF+$2,x sta.l !SRAM_ALTTP_ITEM_BUF,x sta.l !SRAM_ALTTP_ITEM_BUF+$2,x plx jmp .end .boots lda.l alttp_item_table+2,x ; Get Item value phx tyx %a8() sta.l !SRAM_ALTTP_ITEM_BUF,x ; Save value to ALTTP SRAM lda.l !SRAM_ALTTP_ITEM_BUF+$79 ; $a06379 ora #$04 sta.l !SRAM_ALTTP_ITEM_BUF+$79 ;$a06379 ; Set dash bit %a16() plx jmp .end .flippers lda.l alttp_item_table+2,x ; Get Item value phx tyx %a8() sta.l !SRAM_ALTTP_ITEM_BUF,x ; Save value to ALTTP SRAM lda.l !SRAM_ALTTP_ITEM_BUF+$79 ; $a06379 ora #$02 sta.l !SRAM_ALTTP_ITEM_BUF+$79 ;$a06379 ; Set swim bit %a16() plx jmp .end .silvers %a8() lda.l !SRAM_ALTTP_ITEM_BUF+$40 ;$a06340 ; Load bow value beq .nobow clc adc #$02 sta.l !SRAM_ALTTP_ITEM_BUF+$40 ; Store silver arrows and bow %a16() jmp .end .dungeon %a16() lda.l alttp_item_table+2, x ; Get dungeon item bitmask phx : tyx ora.l !SRAM_ALTTP_ITEM_BUF, x sta.l !SRAM_ALTTP_ITEM_BUF, x plx lda $c7 and #$000f sta $c7 ; Clear out extra bits from item index to use as dungeon id jmp .end .dungeon_key %a8() lda.l alttp_item_table+2, x ; Get dungeon item value phx : tyx clc adc !SRAM_ALTTP_ITEM_BUF, x sta !SRAM_ALTTP_ITEM_BUF, x cpx #$007C : bne + : sta !SRAM_ALTTP_ITEM_BUF+$1, x ; Store Hyrule keys to sewer keys + lda !SRAM_ALTTP_SMALLKEY_BUF-$7C, x ; Subtract base offset 0x7C to get index into dungeon small key stats buffer inc a sta !SRAM_ALTTP_SMALLKEY_BUF-$7C, x cpx #$007C : bne + : sta !SRAM_ALTTP_SMALLKEY_BUF-$7C+$1, x ; Store Sewer keys to Hyrule Castle keys + plx %a16() lda $c7 and #$000f sta $c7 ; Clear out extra bits from item index to use as dungeon id jmp .end .nobow %a8() lda.b #$01 sta.l !SRAM_ALTTP_ITEM_BUF+$76 ;$a06376 ; Give upgrade only silver arrows %a16() jmp .end .end ;lda #$0168 ;jsl $82e118 ; Music fix (no need with nofanfare?) lda.l config_multiworld beq + lda.l !SM_MULTIWORLD_PICKUP bne .multiworldMessage + lda.l alttp_item_table+6,x ; Load message pointer and #$00ff jsl $858080 ; Display message bra + .multiworldMessage lda #$005d jsl $858080 ; Display multiworld message lda #$0000 sta !SM_MULTIWORLD_PICKUP + jsl zelda_fix_checksum ; Fix SRAM checksum plp ply plx rtl check_item_swap: pha phy php %ai8() tay CPY.b #$0C : BNE + ; Blue Boomerang LDA !SM_INVENTORY_SWAP : ORA #$80 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$2A : BNE + ; Red Boomerang LDA !SM_INVENTORY_SWAP : ORA #$40 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$29 : BNE + ; Mushroom LDA !SM_INVENTORY_SWAP : ORA #$20 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$0D : BNE + ; Magic Powder LDA !SM_INVENTORY_SWAP : ORA #$10 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$13 : BNE + ; Shovel LDA !SM_INVENTORY_SWAP : ORA #$04 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$14 : BNE + ; Flute (Inactive) LDA !SM_INVENTORY_SWAP : ORA #$02 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$4A : BNE + ; Flute (Active) LDA !SM_INVENTORY_SWAP : ORA #$01 : STA !SM_INVENTORY_SWAP BRL .done + CPY.b #$0B : BNE + ; Bow LDA !SM_INVENTORY_SWAP_2 : ORA #$80 : STA !SM_INVENTORY_SWAP_2 BRL .done + CPY.b #$3A : BNE + ; Bow & Arrows LDA !SM_INVENTORY_SWAP_2 : ORA #$80 : STA !SM_INVENTORY_SWAP_2 BRL .done + CPY.b #$3B : BNE + ; Bow & Silver Arrows LDA !SM_INVENTORY_SWAP_2 : ORA #$40 : STA !SM_INVENTORY_SWAP_2 BRL .done + CPY.b #$43 : BNE + ; Single arrow LDA !SM_INVENTORY_SWAP_2 : ORA #$80 : STA !SM_INVENTORY_SWAP_2 ; activate wood arrows in quick-swap BRL .done + CPY.b #$58 : BNE + ; Upgrade-Only Silver Arrows LDA !SM_INVENTORY_SWAP_2 : ORA #$40 : STA !SM_INVENTORY_SWAP_2 + CPY.b #$49 : BNE + ; Fighter's Sword JSR .stampSword BRL .done + CPY.b #$01 : BNE + ; Master Sword JSR .stampSword BRL .done + CPY.b #$50 : BNE + ; Master Sword JSR .stampSword BRL .done + CPY.b #$02 : BNE + ; Tempered Sword JSR .stampSword BRL .done + CPY.b #$03 : BNE + ; Golden Sword JSR .stampSword BRL .done + CPY.b #$4B : BNE + ; Pegasus Boots JSR .stampBoots BRL .done + CPY.b #$1A : BNE + ; Magic Mirror JSR .stampMirror BRL .done + .done plp ply pla rtl !SWORD_TIME = "$a06458" !BOOTS_TIME = "$a0645C" !FLUTE_TIME = "$a06460" !MIRROR_TIME = "$a06464" .stampSword REP #$20 ; set 16-bit accumulator JSL get_total_frame_time LDA.l !SWORD_TIME : BNE + LDA.l !SWORD_TIME+2 : BNE + LDA.l !SRAM_TIMER1 : STA.l !SWORD_TIME LDA.l !SRAM_TIMER2 : STA.l !SWORD_TIME+2 + SEP #$20 ; set 8-bit accumulator RTS .stampBoots REP #$20 ; set 16-bit accumulator JSL get_total_frame_time LDA.l !BOOTS_TIME : BNE + LDA.l !BOOTS_TIME+2 : BNE + LDA.l !SRAM_TIMER1 : STA.l !BOOTS_TIME LDA.l !SRAM_TIMER2 : STA.l !BOOTS_TIME+2 + SEP #$20 ; set 8-bit accumulator RTS .stampFlute REP #$20 ; set 16-bit accumulator JSL get_total_frame_time LDA.l !FLUTE_TIME : BNE + LDA.l !FLUTE_TIME+2 : BNE + LDA.l !SRAM_TIMER1 : STA.l !FLUTE_TIME LDA.l !SRAM_TIMER2 : STA.l !FLUTE_TIME+2 + SEP #$20 ; set 8-bit accumulator RTS .stampMirror REP #$20 ; set 16-bit accumulator JSL get_total_frame_time LDA.l !MIRROR_TIME : BNE + LDA.l !MIRROR_TIME+2 : BNE + LDA.l !SRAM_TIMER1 : STA.l !MIRROR_TIME LDA.l !SRAM_TIMER2 : STA.l !MIRROR_TIME+2 + SEP #$20 ; set 8-bit accumulator RTS alttp_item_table: namespace "alttp_item_" ; Offset = ALTTP SRAM Offset ; Value = Value to write/add to offset ; Type = Type of item (Item / Amount / ...) ; Message = Id of message box to show ; Offset Value Type Message dw $0000, $0000, $0000, $0000 ; 00 Dummy - L1SwordAndShield dw $0059, $0002, $0100, $0040 ; 01 Master Sword dw $0059, $0003, $0100, $0041 ; 02 Tempered Sword dw $0059, $0004, $0000, $0042 ; 02 Gold Sword dw $005A, $0001, $0100, $0045 ; 04 Shield dw $005A, $0002, $0100, $0046 ; 05 Red Shield dw $005A, $0003, $0000, $0047 ; 06 Mirror Shield dw $0045, $0001, $0000, $0025 ; 07 Firerod dw $0046, $0001, $0000, $0026 ; 08 Icerod dw $004B, $0001, $0000, $002B ; 09 Hammer dw $0042, $0001, $0000, $0021 ; 0A Hookshot dw $0040, $0002, $0000, $001d ; 0B Bow dw $0041, $0001, $0000, $001f ; 0C Blue Boomerang dw $0044, $0002, $0000, $0024 ; 0D Powder dw $0000, $0000, $0000, $0000 ; 0E Dummy - Bee (bottle content) dw $0047, $0001, $0000, $0027 ; 0F Bombos dw $0048, $0001, $0000, $0028 ; 10 Ether dw $0049, $0001, $0000, $0029 ; 11 Quake dw $004A, $0001, $0000, $002A ; 12 Lamp dw $004C, $0001, $0000, $002C ; 13 Shovel dw $004C, $0002, $0000, $002D ; 14 Flute dw $0050, $0001, $0000, $0037 ; 15 Somaria dw $004F, $0002, $0002, $0030 ; 16 Bottle dw $006B, $0001, $0003, $0048 ; 17 Piece of Heart dw $0051, $0001, $0000, $0038 ; 18 Byrna dw $0052, $0001, $0000, $0039 ; 19 Cape dw $0053, $0002, $0000, $003A ; 1A Mirror dw $0054, $0001, $0100, $003B ; 1B Glove dw $0054, $0002, $0000, $003C ; 1C Mitt dw $004E, $0001, $0000, $002F ; 1D Book dw $0056, $0001, $0006, $003E ; 1E Flippers dw $0057, $0001, $0000, $003F ; 1F Pearl dw $0000, $0000, $0000, $0000 ; 20 Dummy dw $004D, $0001, $0000, $002E ; 21 Net dw $005B, $0001, $0100, $0043 ; 22 Blue Tunic dw $005B, $0002, $0000, $0044 ; 23 Red Tunic dw $0000, $0000, $0000, $0000 ; 24 Dummy - key dw $0000, $0000, $0000, $0000 ; 25 Dummy - compass dw $006C, $0008, $0001, $0049 ; 26 Heart Container - no anim dw $0075, $0001, $0001, $0022 ; 27 Bomb 1 dw $0075, $0003, $0001, $004D ; 28 3 Bombs dw $0044, $0001, $0000, $0023 ; 29 Mushroom dw $0041, $0002, $0000, $0020 ; 2A Red Boomerang dw $004F, $0003, $0002, $0031 ; 2B Red Potion dw $004F, $0004, $0002, $0032 ; 2C Green Potion dw $004F, $0005, $0002, $0033 ; 2D Blue Potion dw $0000, $0000, $0000, $0000 ; 2E Dummy - red dw $0000, $0000, $0000, $0000 ; 2F Dummy - green dw $0000, $0000, $0000, $0000 ; 30 Dummy - blue dw $0075, $000A, $0001, $004E ; 31 10 Bombs dw $0000, $0000, $0000, $0000 ; 32 Dummy - big key dw $0000, $0000, $0000, $0000 ; 33 Dummy - map dw $0060, $0001, $0004, $004F ; 34 1 Rupee dw $0060, $0005, $0004, $0050 ; 35 5 Rupees dw $0060, $0014, $0004, $0051 ; 36 20 Rupees dw $0000, $0000, $0000, $0000 ; 37 Dummy - Pendant of Courage dw $0000, $0000, $0000, $0000 ; 38 Dummy - Pendant of Wisdom dw $0000, $0000, $0000, $0000 ; 39 Dummy - Pendant of Power dw $0040, $0002, $0000, $001d ; 3A Bow and arrows dw $0040, $0003, $0007, $001e ; 3B Bow and silver Arrows dw $004F, $0007, $0002, $0034 ; 3C Bee dw $004F, $0006, $0002, $0036 ; 3D Fairy dw $006C, $0008, $0001, $0049 ; 3E Heart Container - Boss dw $006C, $0008, $0001, $0049 ; 3F Heart Container - Sanc dw $0060, $0064, $0004, $0053 ; 40 100 Rupees dw $0060, $0032, $0004, $0052 ; 41 50 Rupees dw $0000, $0000, $0000, $0000 ; 42 Dummy - small heart dw $0076, $0001, $0001, $004A ; 43 1 Arrow dw $0076, $000A, $0001, $004C ; 44 10 Arrows dw $0000, $0000, $0000, $0000 ; 45 Dummy - small magic dw $0060, $012C, $0004, $0054 ; 46 300 Rupees dw $0060, $0014, $0004, $0051 ; 47 20 Rupees dw $004F, $0008, $0002, $0035 ; 48 Good Bee dw $0059, $0001, $0100, $005B ; 49 Fighter Sword dw $0000, $0000, $0000, $0000 ; 4A Dummy - activated flute dw $0055, $0001, $0005, $003D ; 4B Boots dw $0000, $0000, $0000, $0000 ; 4C Dummy - 50+bombs dw $0000, $0000, $0000, $0000 ; 4D Dummy - 70+arrows dw $007B, $0001, $0000, $0055 ; 4E Half Magic dw $007B, $0002, $0000, $0056 ; 4F Quarter Magic dw $0059, $0002, $0100, $0040 ; 50 Master Sword dw $0070, $0005, $0001, $0057 ; 51 +5 Bombs dw $0070, $000A, $0001, $0058 ; 52 +10 Bombs dw $0071, $0005, $0001, $0059 ; 53 +5 Arrows dw $0071, $000A, $0001, $005A ; 54 +10 Arrows dw $0000, $0000, $0000, $0000 ; 55 Dummy - Programmable 1 dw $0000, $0000, $0000, $0000 ; 56 Dummy - Programmable 2 dw $0000, $0000, $0000, $0000 ; 57 Dummy - Programmable 3 dw $0040, $0003, $0007, $001e ; 58 Silver Arrows dw $0000, $0000, $0000, $0000 ; 59 Unused dw $0000, $0000, $0000, $0000 ; 5A Unused dw $0000, $0000, $0000, $0000 ; 5B Unused dw $0000, $0000, $0000, $0000 ; 5C Unused dw $0000, $0000, $0000, $0000 ; 5D Unused dw $0000, $0000, $0000, $0000 ; 5E Unused dw $0000, $0000, $0000, $0000 ; 5F Unused dw $0000, $0000, $0000, $0000 ; 60 Unused dw $0000, $0000, $0000, $0000 ; 61 Unused dw $0000, $0000, $0000, $0000 ; 62 Unused dw $0000, $0000, $0000, $0000 ; 63 Unused dw $0000, $0000, $0000, $0000 ; 64 Unused dw $0000, $0000, $0000, $0000 ; 65 Unused dw $0000, $0000, $0000, $0000 ; 66 Unused dw $0000, $0000, $0000, $0000 ; 67 Unused dw $0000, $0000, $0000, $0000 ; 68 Unused dw $0000, $0000, $0000, $0000 ; 69 Unused dw $0000, $0000, $0000, $0000 ; 6A Unused dw $0000, $0000, $0000, $0000 ; 6B Unused dw $0000, $0000, $0000, $0000 ; 6C Unused dw $0000, $0000, $0000, $0000 ; 6D Unused dw $0000, $0000, $0000, $0000 ; 6E Unused dw $0000, $0000, $0000, $0000 ; 6F Unused dw $0068, $0001, $0010, $005e ; 70 - Unused dw $0068, $0002, $0010, $005e ; 71 - Unused dw $0068, $0004, $0010, $005e ; 72 - Ganons Tower Map dw $0068, $0008, $0010, $005e ; 73 - Turtle Rock Map dw $0068, $0010, $0010, $005e ; 74 - Thieves' Town Map dw $0068, $0020, $0010, $005e ; 75 - Tower of Hera Map dw $0068, $0040, $0010, $005e ; 76 - Ice Palace Map dw $0068, $0080, $0010, $005e ; 77 - Skull Woods Map dw $0068, $0100, $0010, $005e ; 78 - Misery Mire Map dw $0068, $0200, $0010, $005e ; 79 - Palace Of Darkness Map dw $0068, $0400, $0010, $005e ; 7A - Swamp Palace Map dw $0068, $0800, $0010, $005e ; 7B - Unused dw $0068, $1000, $0010, $005e ; 7C - Desert Palace Map dw $0068, $2000, $0010, $005e ; 7D - Eastern Palace Map dw $0068, $C000, $0010, $005e ; 7E - Unused dw $0068, $C000, $0010, $005e ; 7F - Hyrule Castle Map dw $0064, $0001, $0010, $005f ; 80 - Unused dw $0064, $0002, $0010, $005f ; 81 - Unused dw $0064, $0004, $0010, $005f ; 82 - Ganons Tower Compass dw $0064, $0008, $0010, $005f ; 83 - Turtle Rock Compass dw $0064, $0010, $0010, $005f ; 84 - Thieves' Town Compass dw $0064, $0020, $0010, $005f ; 85 - Tower of Hera Compass dw $0064, $0040, $0010, $005f ; 86 - Ice Palace Compass dw $0064, $0080, $0010, $005f ; 87 - Skull Woods Compass dw $0064, $0100, $0010, $005f ; 88 - Misery Mire Compass dw $0064, $0200, $0010, $005f ; 89 - Palace of Darkness Compass dw $0064, $0400, $0010, $005f ; 8A - Swamp Palace Compass dw $0064, $0800, $0010, $005f ; 8B - Unused dw $0064, $1000, $0010, $005f ; 8C - Desert Palace Compass dw $0064, $2000, $0010, $005f ; 8D - Eastern Palace Compass dw $0064, $C000, $0010, $005f ; 8E - Unused dw $0064, $C000, $0010, $005f ; 8F - Unused dw $0066, $0001, $0010, $0060 ; 90 - Unused dw $0066, $0002, $0010, $0060 ; 91 - Unused dw $0066, $0004, $0010, $0060 ; 92 - Ganons Tower Big Key dw $0066, $0008, $0010, $0060 ; 93 - Turtle Rock Big Key dw $0066, $0010, $0010, $0060 ; 94 - Thieves' Town Big Key dw $0066, $0020, $0010, $0060 ; 95 - Tower of Hera Big Key dw $0066, $0040, $0010, $0060 ; 96 - Ice Palace Big Key dw $0066, $0080, $0010, $0060 ; 97 - Skull Woods Big Key dw $0066, $0100, $0010, $0060 ; 98 - Misery Mire Big Key dw $0066, $0200, $0010, $0060 ; 99 - Palace of Darkness Big Key dw $0066, $0400, $0010, $0060 ; 9A - Swamp Palace Big Key dw $0066, $0800, $0010, $0060 ; 9B - Unused dw $0066, $1000, $0010, $0060 ; 9C - Desert Palace Big Key dw $0066, $2000, $0010, $0060 ; 9D - Eastern Palace Big Key dw $0066, $C000, $0010, $0060 ; 9E - Unused dw $0066, $C000, $0010, $0060 ; 9F - Unused dw $007C, $0001, $0011, $0061 ; A0 - Hyrule Castle Small Key dw $007C, $0001, $0011, $0061 ; A1 - Sewers Small Key dw $007E, $0001, $0011, $0061 ; A2 - Eastern Palace Small Key dw $007F, $0001, $0011, $0061 ; A3 - Desert Palace Small Key dw $0080, $0001, $0011, $0061 ; A4 - Castle Tower Small Key dw $0081, $0001, $0011, $0061 ; A5 - Swamp Palace Small Key dw $0082, $0001, $0011, $0061 ; A6 - Palace of Darkness Small Key dw $0083, $0001, $0011, $0061 ; A7 - Misery Mire Small Key dw $0084, $0001, $0011, $0061 ; A8 - Skull Woods Small Key dw $0085, $0001, $0011, $0061 ; A9 - Ice Palace Small Key dw $0086, $0001, $0011, $0061 ; AA - Tower of Hera Small Key dw $0087, $0001, $0011, $0061 ; AB - Thieves' Town Small Key dw $0088, $0001, $0011, $0061 ; AC - Turtle Rock Small Key dw $0089, $0001, $0011, $0061 ; AD - Ganons Tower Small Key dw $008A, $0001, $0011, $0061 ; AE - Unused dw $008B, $0001, $0011, $0061 ; AF - Unused ; dw $006C, $0008, $0001, $0049 ; Heart Container ; dw $0076, $0005, $0001, $004B ; 5 Arrows org $c59643 base $859643 dw !EmptySmall, !Small, bow dw !EmptySmall, !Small, silver_arrows dw !EmptySmall, !Small, blue_boomerang dw !EmptySmall, !Small, red_boomerang dw !EmptySmall, !Small, hookshot dw !EmptySmall, !Small, bomb_1 dw !EmptySmall, !Small, mushroom dw !EmptySmall, !Small, powder dw !EmptySmall, !Small, firerod dw !EmptySmall, !Small, icerod dw !EmptySmall, !Small, bombos dw !EmptySmall, !Small, ether dw !EmptySmall, !Small, quake dw !EmptySmall, !Small, lamp dw !EmptySmall, !Small, hammer dw !EmptySmall, !Small, shovel dw !EmptySmall, !Small, flute dw !EmptySmall, !Small, net dw !EmptySmall, !Small, book dw !EmptySmall, !Small, bottle_empty dw !EmptySmall, !Small, bottle_red dw !EmptySmall, !Small, bottle_green dw !EmptySmall, !Small, bottle_blue dw !EmptySmall, !Small, bottle_bee dw !EmptySmall, !Small, bottle_good_bee dw !EmptySmall, !Small, bottle_fairy dw !EmptySmall, !Small, somaria dw !EmptySmall, !Small, byrna dw !EmptySmall, !Small, cape dw !EmptySmall, !Small, mirror dw !EmptySmall, !Small, glove dw !EmptySmall, !Small, mitt dw !EmptySmall, !Small, boots dw !EmptySmall, !Small, flippers dw !EmptySmall, !Small, pearl dw !EmptySmall, !Small, sword_master dw !EmptySmall, !Small, sword_tempered dw !EmptySmall, !Small, sword_gold dw !EmptySmall, !Small, tunic_blue dw !EmptySmall, !Small, tunic_red dw !EmptySmall, !Small, shield dw !EmptySmall, !Small, shield_red dw !EmptySmall, !Small, shield_mirror dw !EmptySmall, !Small, heart_piece dw !EmptySmall, !Small, heart_container dw !EmptySmall, !Small, arrow_1 dw !EmptySmall, !Small, arrows_5 dw !EmptySmall, !Small, arrows_10 dw !EmptySmall, !Small, bombs_3 dw !EmptySmall, !Small, bombs_10 dw !EmptySmall, !Small, rupee_1 dw !EmptySmall, !Small, rupees_5 dw !EmptySmall, !Small, rupees_20 dw !EmptySmall, !Small, rupees_50 dw !EmptySmall, !Small, rupees_100 dw !EmptySmall, !Small, rupees_300 dw !EmptySmall, !Small, magic_half dw !EmptySmall, !Small, magic_quarter dw !EmptySmall, !Small, bomb_upgrade_5 dw !EmptySmall, !Small, bomb_upgrade_10 dw !EmptySmall, !Small, arrow_upgrade_5 dw !EmptySmall, !Small, arrow_upgrade_10 dw !EmptySmall, !Small, sword_fighter dw !PlaceholderBig, !Big, sm_item_sent dw !PlaceholderBig, !Big, sm_item_received dw !DungeonItemBig, !Big, map ; 5E dw !DungeonItemBig, !Big, compass ; 5F dw !DungeonItemBig, !Big, big_key ; 60 dw !DungeonKeyItemBig, !Big, small_key ; 61 dw !KeycardBig, !Big, keycard ; 62 dw !EmptySmall, !Small, btn_array table box.tbl,rtl ; 0 31 bow: dw "______ Bow _______" silver_arrows: dw "______ Silver Arrows _______" blue_boomerang: dw "______ Blue Boomerang _______" red_boomerang: dw "______ Red Boomerang _______" hookshot: dw "______ Hookshot _______" bomb_1: dw "______ 1 Bomb _______" mushroom: dw "______ Mushroom _______" powder: dw "______ Magic Powder _______" firerod: dw "______ Fire Rod _______" icerod: dw "______ Ice Rod _______" bombos: dw "______ Bombos _______" ether: dw "______ Ether _______" quake: dw "______ Quake _______" lamp: dw "______ Lamp _______" hammer: dw "______ Hammer _______" shovel: dw "______ Shovel _______" flute: dw "______ Flute _______" net: dw "______ Bug-catching Net _______" book: dw "______ Book of Mudora _______" bottle_empty: dw "______ Bottle _______" bottle_red: dw "______ Red Potion _______" bottle_green: dw "______ Green Potion _______" bottle_blue: dw "______ Blue Potion _______" bottle_bee: dw "______ Bee _______" bottle_good_bee: dw "______ Good Bee _______" bottle_fairy: dw "______ Fairy _______" somaria: dw "______ Cane of Somaria _______" byrna: dw "______ Cane of Byrna _______" cape: dw "______ Magic Cape _______" mirror: dw "______ Mirror _______" glove: dw "______ Power Glove _______" mitt: dw "______ Titan's Mitt _______" boots: dw "______ Pegasus Boots _______" flippers: dw "______ Zora's Flippers _______" pearl: dw "______ Moon Pearl _______" sword_master: dw "______ Master Sword _______" sword_tempered: dw "______ Tempered Sword _______" sword_gold: dw "______ Gold Sword _______" tunic_blue: dw "______ Blue Mail _______" tunic_red: dw "______ Red Mail _______" shield: dw "______ Small Shield _______" shield_red: dw "______ Red Shield _______" shield_mirror: dw "______ Mirror Shield _______" heart_piece: dw "______ Heart Piece _______" heart_container: dw "______ Heart Container _______" arrow_1: dw "______ 1 Arrow _______" arrows_5: dw "______ 5 Arrows _______" arrows_10: dw "______ 10 Arrows _______" bombs_3: dw "______ 3 Bombs _______" bombs_10: dw "______ 10 Bombs _______" rupee_1: dw "______ 1 Rupee _______" rupees_5: dw "______ 5 Rupees _______" rupees_20: dw "______ 20 Rupees _______" rupees_50: dw "______ 50 Rupees _______" rupees_100: dw "______ 100 Rupees _______" rupees_300: dw "______ 300 Rupees _______" magic_half: dw "______ Half Magic _______" magic_quarter: dw "______ Quarter Magic _______" bomb_upgrade_5: dw "______ 5 Bomb capacity _______" bomb_upgrade_10: dw "______ 10 Bomb capacity _______" arrow_upgrade_5: dw "______ 5 Arrow capacity _______" arrow_upgrade_10: dw "______ 10 Arrow capacity _______" sword_fighter: dw "______ Fighter's Sword _______" sm_item_sent: dw "___ You found ___" dw "___ ITEM NAME HERE ___" dw "___ for ___" dw "___ PLAYER ___" sm_item_received: dw "___ You received ___" dw "___ ITEM NAME HERE ___" dw "___ from ___" dw "___ PLAYER ___" map: dw "___ This is the map ___" dw "___ for ___" dw "___ ___" dw "___ DUNGEON ___" compass: dw "___ This is the compass ___" dw "___ for ___" dw "___ ___" dw "___ DUNGEON ___" big_key: dw "___ This is the big key ___" dw "___ for ___" dw "___ ___" dw "___ DUNGEON ___" small_key: dw "___ This is a small key ___" dw "___ for ___" dw "___ ___" dw "___ DUNGEON ___" keycard: dw "___ This is the ___" dw "___ KEYCARD ___" dw "___ for ___" dw "___ REGION ___" cleartable btn_array: DW $0000, $012A, $012A, $012C, $012C, $012C, $0000, $0000, $0000, $0000, $0000, $0000, $0120, $0000, $0000 DW $0000, $0000, $0000, $012A, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 DW $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000, $0000 table box_yellow.tbl,rtl item_names: dw "___ Grappling Beam ___" ; 00 (b0) (sm items) dw "___ X-Ray Scope ___" dw "___ Varia Suit ___" dw "___ Spring Ball ___" dw "___ Morphing Ball ___" dw "___ Screw Attack ___" dw "___ Gravity Suit ___" dw "___ Hi-Jump Boots ___" dw "___ Space Jump ___" dw "___ Bombs ___" dw "___ Speed Booster ___" dw "___ Charge Beam ___" dw "___ Ice Beam ___" dw "___ Wave Beam ___" dw "___ ~ S p A z E r ~ ___" dw "___ Plasma Beam ___" ; 0f dw "___ An Energy Tank ___" ; 10 dw "___ A Reserve Tank ___" dw "___ Missiles ___" dw "___ Super Missiles ___" dw "___ Power Bombs ___" dw "___ ___" ;15 dw "___ ___" ;16 dw "___ ___" ;17 dw "___ ___" ;18 dw "___ ___" ;19 dw "___ ___" ;1A dw "___ ___" ;1B dw "___ ___" ;1C dw "___ ___" ;1D dw "___ ___" ;1E dw "___ ___" ;1F dw "___ Crateria L 1 Keycard ___" ; 20 dw "___ Crateria L 2 Keycard ___" ; 21 dw "___ Crateria Boss Keycard ___" ; 22 dw "___ Brinstar L 1 Keycard ___" ; 23 dw "___ Brinstar L 2 Keycard ___" ; 24 dw "___ Brinstar Boss Keycard ___" ; 25 dw "___ Norfair L 1 Keycard ___" ; 26 dw "___ Norfair L 2 Keycard ___" ; 27 dw "___ Norfair Boss Keycard ___" ; 28 dw "___ Maridia L 1 Keycard ___" ; 28 dw "___ Maridia L 2 Keycard ___" ; 2A dw "___ Maridia Boss Keycard ___" ; 2B dw "___ Wrecked Ship L 1 Keycard ___" ; 2C dw "___ Wrecked Ship Boss Keycard___" ; 2D dw "___Lower Norfair L 1 Keycard ___" ; 2E dw "___Lower Norfair Boss Keycard___" ; 2F dw "___ ___" ; $30+ (alttp items) dw "___ Master Sword ___" dw "___ Tempered Sword ___" dw "___ Gold Sword ___" dw "___ Small Shield ___" dw "___ Red Shield ___" dw "___ Mirror Shield ___" dw "___ Fire Rod ___" dw "___ Ice Rod ___" dw "___ Hammer ___" dw "___ Hookshot ___" dw "___ Bow ___" dw "___ Blue Boomerang ___" dw "___ Magic Powder ___" dw "___ ___" dw "___ Bombos ___" dw "___ Ether ___" dw "___ Quake ___" dw "___ Lamp ___" dw "___ Shovel ___" dw "___ Flute ___" dw "___ Cane of Somaria ___" dw "___ Bottle ___" dw "___ Heart Piece ___" dw "___ Cane of Byrna ___" dw "___ Magic Cape ___" dw "___ Mirror ___" dw "___ Power Glove ___" dw "___ Titan's Mitt ___" dw "___ Book of Mudora ___" dw "___ Zora's Flippers ___" dw "___ Moon Pearl ___" dw "___ ___" dw "___ Bug-catching Net ___" dw "___ Blue Mail ___" dw "___ Red Mail ___" dw "___ ___" dw "___ ___" dw "___ Heart Container ___" dw "___ 1 Bomb ___" dw "___ 3 Bombs ___" dw "___ Mushroom ___" dw "___ Red Boomerang ___" dw "___ Red Potion ___" dw "___ Green Potion ___" dw "___ Blue Potion ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ 10 Bombs ___" dw "___ ___" dw "___ ___" dw "___ 1 Rupee ___" dw "___ 5 Rupees ___" dw "___ 20 Rupees ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ Bow ___" dw "___ Silver Arrows ___" dw "___ Bee ___" dw "___ Fairy ___" dw "___ Heart Container ___" dw "___ Heart Container ___" dw "___ 100 Rupees ___" dw "___ 50 Rupees ___" dw "___ ___" dw "___ 1 Arrow ___" dw "___ 10 Arrows ___" dw "___ ___" dw "___ 300 Rupees ___" dw "___ 20 Rupees ___" dw "___ Good Bee ___" dw "___ Fighter's Sword ___" dw "___ ___" dw "___ Pegasus Boots ___" dw "___ ___" dw "___ ___" dw "___ Half Magic ___" dw "___ Quarter Magic ___" dw "___ Master Sword ___" dw "___ 5 Bomb capacity ___" dw "___ 10 Bomb capacity ___" dw "___ 5 Arrow capacity ___" dw "___ 10 Arrow capacity ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ Silver arrows ___" ; 58 dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ Sword Upgrade ___" dw "___ Shield Uprade ___" dw "___ Armour Upgrade ___" ; 60 dw "___ Glove Upgrade ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" dw "___ ___" ; 6F dw "___ ___" ; 70 dw "___ ___" dw "___ Ganon's Tower Map ___" dw "___ Turtle Rock Map ___" dw "___ Thieves' Town Map ___" dw "___ Tower of Hera Map ___" dw "___ Ice Palace Map ___" dw "___ Skull Woods Map ___" dw "___ Misery Mire Map ___" dw "___ Palace of Darkness Map ___" dw "___ Swamp Palace Map ___" dw "___ ___" dw "___ Desert Palace Map ___" dw "___ Eastern Palace Map ___" dw "___ ___" dw "___ HYRULE CASTLE Map ___" ; 7F dw "___ ___" ; 80 dw "___ ___" dw "___ Ganon's Tower Compass ___" dw "___ Turtle Rock Compass ___" dw "___ Thieves' Town Compass ___" dw "___ Tower of Hera Compass ___" dw "___ Ice Palace Compass ___" dw "___ Skull Woods Compass ___" dw "___ Misery Mire Compass ___" dw "___Palace of Darkness Compass___" dw "___ Swamp Palace Compass ___" dw "___ ___" dw "___ Desert Palace Compass ___" dw "___ Eastern Palace Compass ___" dw "___ ___" dw "___ ___" ; 8F dw "___ ___" ; 90 dw "___ ___" dw "___ Ganon's Tower Big Key ___" dw "___ Turtle Rock Big Key ___" dw "___ Thieves' Town Big Key ___" dw "___ Tower of Hera Big Key ___" dw "___ Ice Palace Big Key ___" dw "___ Skull Woods Big Key ___" dw "___ Misery Mire Big Key ___" dw "___Palace of Darkness Big Key___" dw "___ Swamp Palace Big Key ___" dw "___ ___" dw "___ Desert Palace Big Key ___" dw "___ Eastern Palace Big Key ___" dw "___ ___" dw "___ ___" ; 9F dw "___ Hyrule Castle Key ___" ; A0 dw "___ Sewers Key ___" dw "___ Eastern Palace Key ___" dw "___ Desert Palace Key ___" dw "___ Castle Tower Key ___" dw "___ Swamp Palace Key ___" dw "___ Palace of Darkness Key ___" dw "___ Misery Mire Key ___" dw "___ Skull Woods Key ___" dw "___ Ice Palace Key ___" dw "___ Tower of Hera Key ___" dw "___ Thieves' Town Key ___" dw "___ Turtle Rock Key ___" dw "___ Ganon's Tower Key ___" dw "___ ___" dw "___ ___" ; AF dungeon_names: dw "___ UNUSED ___" ; 0 dw "___ UNUSED ___" ; 1 dw "___ Ganon's Tower ___" ; 2 dw "___ Turtle Rock ___" ; 3 dw "___ Thieves' Town ___" ; 4 dw "___ Tower of Hera ___" ; 5 dw "___ Ice Palace ___" ; 6 dw "___ Skull Woods ___" ; 7 dw "___ Misery Mire ___" ; 8 dw "___ Palace of Darkness ___" ; 9 dw "___ Swamp Palace ___" ; A dw "___ UNUSED ___" ; B dw "___ Desert Palace ___" ; C dw "___ Eastern Palace ___" ; D dw "___ UNUSED ___" ; E dw "___ Hyrule Castle ___" ; F dungeon_names_key: dw "___ Hyrule Castle ___" ; 0 dw "___ UNUSED ___" ; 1 dw "___ UNUSED ___" ; 2 dw "___ Desert Palace ___" ; 3 dw "___ Castle Tower ___" ; 4 dw "___ Swamp Palace ___" ; 5 dw "___ Palace of Darkness ___" ; 6 dw "___ Misery Mire ___" ; 7 dw "___ Skull Woods ___" ; 8 dw "___ Ice Palace ___" ; 9 dw "___ Tower of Hera ___" ; A dw "___ Thieves' Town ___" ; B dw "___ Turtle Rock ___" ; C dw "___ Ganon's Tower ___" ; D dw "___ UNUSED ___" ; E dw "___ UNUSED ___" ; F region_names: dw "___ Crateria ___" ; 0 dw "___ Crateria ___" ; 1 dw "___ Crateria ___" ; 2 dw "___ Brinstar ___" ; 3 dw "___ Brinstar ___" ; 4 dw "___ Brinstar ___" ; 5 dw "___ Norfair ___" ; 6 dw "___ Norfair ___" ; 7 dw "___ Norfair ___" ; 8 dw "___ Maridia ___" ; 9 dw "___ Maridia ___" ; A dw "___ Maridia ___" ; B dw "___ Wrecked Ship ___" ; C dw "___ Wrecked Ship ___" ; D dw "___ Lower Norfair ___" ; E dw "___ Lower Norfair ___" ; F keycard_names: dw "___ Level 1 Keycard ___" ; 0 dw "___ Level 2 Keycard ___" ; 1 dw "___ Boss Keycard ___" ; 2 dw "___ Level 1 Keycard ___" ; 3 dw "___ Level 2 Keycard ___" ; 4 dw "___ Boss Keycard ___" ; 5 dw "___ Level 1 Keycard ___" ; 6 dw "___ Level 2 Keycard ___" ; 7 dw "___ Boss Keycard ___" ; 8 dw "___ Level 1 Keycard ___" ; 9 dw "___ Level 2 Keycard ___" ; A dw "___ Boss Keycard ___" ; B dw "___ Level 1 Keycard ___" ; C dw "___ Boss Keycard ___" ; D dw "___ Level 1 Keycard ___" ; E dw "___ Boss Keycard ___" ; F cleartable EmptyBig: REP #$30 LDY #$0000 JMP $841D PlaceholderBig: REP #$30 JSR write_placeholders LDY #$0000 JMP $841D DungeonItemBig: REP #$30 JSR write_dungeon LDY #$0000 JMP $841D DungeonKeyItemBig: REP #$30 JSR write_dungeon_key LDY #$0000 JMP $841D KeycardBig: REP #$30 JSR write_keycard LDY #$0000 JMP $841D write_dungeon: phx : phy lda $1c1f cmp #$005e beq .adjust cmp #$005f beq .adjust cmp #$0060 beq .adjust bra .end .adjust lda $c7 ; Load dungeon id asl #6 : tay ldx #$0000 - lda dungeon_names, y sta.l $7e3300, x inx #2 : iny #2 cpx #$0040 bne - .end ply : plx lda #$0020 rts write_dungeon_key: phx : phy lda $1c1f cmp #$0061 beq .adjust bra .end .adjust lda $c7 ; Load dungeon id asl #6 : tay ldx #$0000 - lda dungeon_names_key, y sta.l $7e3300, x inx #2 : iny #2 cpx #$0040 bne - .end ply : plx lda #$0020 rts write_keycard: phx : phy lda $1c1f cmp #$0062 beq .adjust bra .end .adjust lda $c7 ; Load keycard index asl #6 : tay phy ldx #$0000 - lda keycard_names, y sta.l $7e3280, x inx #2 : iny #2 cpx #$0040 bne - ply ldx #$0000 - lda region_names, y sta.l $7e3300, x inx #2 : iny #2 cpx #$0040 bne - .end ply : plx lda #$0020 rts write_placeholders: phx : phy lda $1c1f cmp #$005c beq .adjust cmp #$005d beq .adjust bra .end .adjust lda $c1 ; Load item id cmp #$00b0 bcc .alttpItem sec sbc #$00b0 bra + .alttpItem clc adc #$0030 + asl #6 : tay ldx #$0000 - lda item_names, y ; Write item name to box sta.l $7e3280, x inx #2 : iny #2 cpx #$0040 bne - lda $c3 ; Load player 1 asl #4 : tax ldy #$0000 - lda.l rando_player_table, x and #$00ff phx asl : tax ; Put char table offset in X lda char_table-$40, x tyx sta.l $7e3314, x iny #2 plx inx cpy #$0018 bne - rep #$30 .end ply : plx lda #$0020 rts char_table: ; Each unsupported value translate to "?" $38FE to raise a visual indication ; <sp> ! " # $ % & ' ( ) * + , - . / dw $384E, $38FF, $38AA, $38AE, $38FE, $380A, $38FE, $38FC, $38FE, $38FE, $38FE, $38AF, $38FB, $38CF, $38FA, $38FE ; 0 1 2 3 4 5 6 7 8 9 : ; < = > ? dw $3889, $3880, $3881, $3882, $3883, $3884, $3885, $3886, $3887, $3888, $38AB, $38FE, $38FE, $38FE, $38FE, $38FE ; @ A B C D E F G H I J K L M N O dw $38FE, $38E0, $38E1, $38E2, $38E3, $38E4, $38E5, $38E6, $38E7, $38E8, $38E9, $38EA, $38EB, $38EC, $38ED, $38EE ; P Q R S T U V W X Y Z [ \ ] ^ _ dw $38EF, $38F0, $38F1, $38F2, $38F3, $38F4, $38F5, $38F6, $38F7, $38F8, $38F9, $38FE, $38FE, $38FE, $38FE, $38FE ; Lowercase Letters, which simply translate to uppercase ; ` A B C D E F G H I J K L M N O dw $38FE, $3890, $3891, $3892, $3893, $3894, $3895, $3896, $3897, $3898, $3899, $389A, $389B, $389C, $389D, $389E ; P Q R S T U V W X Y Z { | } ~ <DEL> dw $389F, $38A0, $38A1, $38A2, $38A3, $38A4, $38A5, $38A6, $38A7, $38A8, $38A9, $38FE, $38FE, $38FE, $38AC, $38FE org $c58749 base $858749 fix_1c1f: LDA $CE ; if $CE is set, it overrides the message box BEQ + STA $1C1F STZ $CE ; Clear $CE + LDA $1C1F CMP #$001D BPL + RTS + ADC #$027F RTS org $c58243 base $858243 JSR fix_1c1f org $c582E5 base $8582E5 JSR fix_1c1f org $c58413 base $858413 DW btn_array namespace off ; ; Patch item PLM's ; org $CF81CC ; dw $efe0 ;Power Bomb (Crateria surface) ; org $CF81E8 ; dw $efe0 ;Missile (outside Wrecked Ship bottom) ; org $CF81EE ; dw $efe8 ;Missile (outside Wrecked Ship top) ; org $CF81F4 ; dw $efe0 ;Missile (outside Wrecked Ship middle) ; org $CF8248 ; dw $efe0 ;Missile (Crateria moat) ; org $CF8264 ; dw $efe0 ;Energy Tank (Crateria gauntlet) ; org $CF83EE ; dw $efe0 ;Missile (Crateria bottom) ; org $CF8404 ; dw $efe4 ;Bomb ; org $CF8432 ; dw $efe0 ;Energy Tank (Crateria tunnel to Brinstar) ; org $CF8464 ; dw $efe0 ;Missile (Crateria gauntlet right) ; org $CF846A ; dw $efe0 ;Missile (Crateria gauntlet left) ; org $CF8478 ; dw $efe0 ;Super Missile (Crateria) ; org $CF8486 ; dw $efe0 ;Missile (Crateria middle) ; org $CF84AC ; dw $efe4 ;Power Bomb (green Brinstar bottom) ; org $CF84E4 ; dw $efe4 ;Super Missile (pink Brinstar) ; org $CF8518 ; dw $efe0 ;Missile (green Brinstar below super missile) ; org $CF851E ; dw $efe0 ;Super Missile (green Brinstar top) ; org $CF852C ; dw $efe4 ;Reserve Tank (Brinstar) ; org $CF8532 ; dw $efe8 ;Missile (green Brinstar behind missile) ; org $CF8538 ; dw $efe0 ;Missile (green Brinstar behind Reserve Tank) ; org $CF8608 ; dw $efe0 ;Missile (pink Brinstar top) ; org $CF860E ; dw $efe0 ;Missile (pink Brinstar bottom) ; org $CF8614 ; dw $efe4 ;Charge Beam ; org $CF865C ; dw $efe0 ;Power Bomb (pink Brinstar) ; org $CF8676 ; dw $efe0 ;Missile (green Brinstar pipe) ; org $CF86DE ; dw $efe0 ;Morphing Ball ; org $CF874C ; dw $efe0 ;Power Bomb (blue Brinstar) ; org $CF8798 ; dw $efe0 ;Missile (blue Brinstar middle) ; org $CF879E ; dw $efe8 ;Energy Tank (blue Brinstar) ; org $CF87C2 ; dw $efe0 ;Energy Tank (green Brinstar bottom) ; org $CF87D0 ; dw $efe0 ;Super Missile (green Brinstar bottom) ; org $CF87FA ; dw $efe0 ;Energy Tank (pink Brinstar bottom) ; org $CF8802 ; dw $efe4 ;Missile (blue Brinstar bottom) ; org $CF8824 ; dw $efe0 ;Energy Tank (pink Brinstar top) ; org $CF8836 ; dw $efe0 ;Missile (blue Brinstar top) ; org $CF883C ; dw $efe8 ;Missile (blue Brinstar behind missile) ; org $CF8876 ; dw $efe4 ;X-Ray Visor ; org $CF88CA ; dw $efe0 ;Power Bomb (red Brinstar sidehopper room) ; org $CF890E ; dw $efe4 ;Power Bomb (red Brinstar spike room) ; org $CF8914 ; dw $efe0 ;Missile (red Brinstar spike room) ; org $CF896E ; dw $efe4 ;Spazer ; org $CF899C ; dw $efe8 ;Energy Tank (Kraid) ; org $CF89EC ; dw $efe8 ;Missile (Kraid) ; org $CF8ACA ; dw $efe4 ;Varia Suit ; org $CF8AE4 ; dw $efe8 ;Missile (lava room) ; org $CF8B24 ; dw $efe4 ;Ice Beam ; org $CF8B46 ; dw $efe8 ;Missile (below Ice Beam) ; org $CF8BA4 ; dw $efe0 ;Energy Tank (Crocomire) ; org $CF8BAC ; dw $efe4 ;Hi-Jump Boots ; org $CF8BC0 ; dw $efe0 ;Missile (above Crocomire) ; org $CF8BE6 ; dw $efe0 ;Missile (Hi-Jump Boots) ; org $CF8BEC ; dw $efe0 ;Energy Tank (Hi-Jump Boots) ; org $CF8C04 ; dw $efe0 ;Power Bomb (Crocomire) ; org $CF8C14 ; dw $efe0 ;Missile (below Crocomire) ; org $CF8C2A ; dw $efe0 ;Missile (Grapple Beam) ; org $CF8C36 ; dw $efe4 ;Grapple Beam ; org $CF8C3E ; dw $efe4 ;Reserve Tank (Norfair) ; org $CF8C44 ; dw $efe8 ;Missile (Norfair Reserve Tank) ; org $CF8C52 ; dw $efe0 ;Missile (bubble Norfair green door) ; org $CF8C66 ; dw $efe0 ;Missile (bubble Norfair) ; org $CF8C74 ; dw $efe8 ;Missile (Speed Booster) ; org $CF8C82 ; dw $efe4 ;Speed Booster ; org $CF8CBC ; dw $efe0 ;Missile (Wave Beam) ; org $CF8CCA ; dw $efe4 ;Wave Beam ; org $CF8E6E ; dw $efe0 ;Missile (Gold Torizo) ; org $CF8E74 ; dw $efe8 ;Super Missile (Gold Torizo) ; org $CF8F30 ; dw $efe0 ;Missile (Mickey Mouse room) ; org $CF8FCA ; dw $efe0 ;Missile (lower Norfair above fire flea room) ; org $CF8FD2 ; dw $efe0 ;Power Bomb (lower Norfair above fire flea room) ; org $CF90C0 ; dw $efe0 ;Power Bomb (above Ridley) ; org $CF9100 ; dw $efe0 ;Missile (lower Norfair near Wave Beam) ; org $CF9108 ; dw $efe8 ;Energy Tank (Ridley) ; org $CF9110 ; dw $efe4 ;Screw Attack ; org $CF9184 ; dw $efe0 ;Energy Tank (lower Norfair fire flea room) ; org $CFC265 ; dw $efe0 ;Missile (Wrecked Ship middle) ; org $CFC2E9 ; dw $efe4 ;Reserve Tank (Wrecked Ship) ; org $CFC2EF ; dw $efe0 ;Missile (Gravity Suit) ; org $CFC319 ; dw $efe0 ;Missile (Wrecked Ship top) ; org $CFC337 ; dw $efe0 ;Energy Tank (Wrecked Ship) ; org $CFC357 ; dw $efe0 ;Super Missile (Wrecked Ship left) ; org $CFC365 ; dw $efe0 ;Super Missile (Wrecked Ship right) ; org $CFC36D ; dw $efe4 ;Gravity Suit ; org $CFC437 ; dw $efe0 ;Missile (green Maridia shinespark) ; org $CFC43D ; dw $efe0 ;Super Missile (green Maridia) ; org $CFC47D ; dw $efe0 ;Energy Tank (green Maridia) ; org $CFC483 ; dw $efe8 ;Missile (green Maridia tatori) ; org $CFC4AF ; dw $efe0 ;Super Missile (yellow Maridia) ; org $CFC4B5 ; dw $efe0 ;Missile (yellow Maridia super missile) ; org $CFC533 ; dw $efe0 ;Missile (yellow Maridia false wall) ; org $CFC559 ; dw $efe4 ;Plasma Beam ; org $CFC5DD ; dw $efe0 ;Missile (left Maridia sand pit room) ; org $CFC5E3 ; dw $efe4 ;Reserve Tank (Maridia) ; org $CFC5EB ; dw $efe0 ;Missile (right Maridia sand pit room) ; org $CFC5F1 ; dw $efe0 ;Power Bomb (right Maridia sand pit room) ; org $CFC603 ; dw $efe0 ;Missile (pink Maridia) ; org $CFC609 ; dw $efe0 ;Super Missile (pink Maridia) ; org $CFC6E5 ; dw $efe4 ;Spring Ball ; org $CFC74D ; dw $efe8 ;Missile (Draygon) ; org $CFC755 ; dw $efe0 ;Energy Tank (Botwoon) ; org $CFC7A7 ; dw $efe4 ;Space Jump
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="epfd, op, fd, event"/> <%docstring> Invokes the syscall epoll_ctl. See 'man 2 epoll_ctl' for more information. Arguments: epfd(int): epfd op(int): op fd(int): fd event(epoll_event): event </%docstring> ${syscall('SYS_epoll_ctl', epfd, op, fd, event)}
; A105852: sigma(n) mod 9. ; 1,3,4,7,6,3,8,6,4,0,3,1,5,6,6,4,0,3,2,6,5,0,6,6,4,6,4,2,3,0,5,0,3,0,3,1,2,6,2,0,6,6,8,3,6,0,3,7,3,3,0,8,0,3,0,3,8,0,6,6,8,6,5,1,3,0,5,0,6,0,0,6,2,6,7,5,6,6,8,6,4,0,3,8,0,6,3,0,0,0,4,6,2,0,3,0,8,0,3,1,3,0,5,3,3,0,0,1,2,0,8,5,6,6,0,3,2,0,0,0,7,6,6,8,3,6,2,3,5,0,6,3,7,6,6,0,3,0,5,3,3,0,6,7,0,6,3,5,6,3,8,3,0,0,3,5,5,6,0,0,3,3,2,6,0,0,6,3,3,0,8,2,3,0,5,3,6,0,0,6,2,3,5,0,3,6,0,3,5,0,3,4,5,6,3,3,0,0,2,6,2,0,6,0,0,6,6,2,6,0,5,0,0,0,3,6,4,6,8,0,0,6,8,0,7,0,3,2,5,0,6,0,0,6,0,6,5,0,6,6,8,3,4,2,0,0,1,3,3,0 cal $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n). mod $0,9 mov $1,$0
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_82_goodG2B.cpp Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-82_goodG2B.tmpl.cpp */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_82.h" #define HELLO_STRING L"hello" namespace CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_82 { void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_82_goodG2B::action(size_t data) { { wchar_t * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the wcscpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > wcslen(HELLO_STRING)) { myString = (wchar_t *)malloc(data*sizeof(wchar_t)); /* Copy a small string into myString */ wcscpy(myString, HELLO_STRING); printWLine(myString); free(myString); } else { printLine("Input is less than the length of the source string"); } } } } #endif /* OMITGOOD */
#include <thor-internal/arch/gic.hpp> #include <thor-internal/arch/timer.hpp> #include <thor-internal/dtb/dtb.hpp> #include <thor-internal/main.hpp> #include <thor-internal/initgraph.hpp> #include <thor-internal/cpu-data.hpp> #include <thor-internal/physical.hpp> #include <thor-internal/arch/cpu.hpp> #include <thor-internal/fiber.hpp> namespace thor { extern "C" uint8_t _binary_kernel_thor_arch_arm_trampoline_bin_start[]; extern "C" uint8_t _binary_kernel_thor_arch_arm_trampoline_bin_end[]; namespace { struct StatusBlock { StatusBlock *self; // Pointer to this struct in the higher half. int targetStage; int cpuId; uintptr_t ttbr0; uintptr_t ttbr1; uintptr_t stack; void (*main)(StatusBlock *); CpuData *cpuContext; }; struct Psci { Psci(DeviceTreeNode *node) { cpuOn_ = node->cpuOn(); usesHvc_ = node->method() == "hvc"; if (!usesHvc_) assert(node->method() == "smc"); } int turnOnCpu(uint8_t id, uintptr_t addr) { register int64_t regResult asm("x0"); register uint64_t regCmd asm("x0") = cpuOn_; register uint64_t regCpu asm("x1") = id; register uint64_t regAddr asm("x2") = addr; if (usesHvc_) { asm volatile ("hvc #0" : "=r"(regResult) : "r"(regCmd), "r"(regCpu), "r"(regAddr)); } else { asm volatile ("smc #0" : "=r"(regResult) : "r"(regCmd), "r"(regCpu), "r"(regAddr)); } return regResult; } private: uint32_t cpuOn_; bool usesHvc_; }; frg::manual_box<Psci> psci_; void secondaryMain(StatusBlock *statusBlock) { initializeIrqVectors(); auto cpuContext = statusBlock->cpuContext; setupCpuContext(cpuContext); initializeThisProcessor(); cpuContext->archCpuIndex = statusBlock->cpuId; initGicOnThisCpu(); initTimerOnThisCpu(); __atomic_store_n(&statusBlock->targetStage, 2, __ATOMIC_RELEASE); infoLogger() << "Hello world on CPU #" << getCpuData()->cpuIndex << frg::endlog; Scheduler::resume(cpuContext->wqFiber); localScheduler()->update(); localScheduler()->forceReschedule(); localScheduler()->commitReschedule(); while(1); } } extern frg::manual_box<GicDistributor> dist; bool bootSecondary(DeviceTreeNode *node) { infoLogger() << "thor: Starting CPU \"" << node->path() << "\"" << frg::endlog; uint8_t id = node->reg()[0].addr; // TODO: We assume CPU 0 is the boot CPU, but potentially it could be some other one if (id == 0) return false; using EnableMethod = DeviceTreeNode::EnableMethod; if (node->enableMethod() == EnableMethod::unknown) { infoLogger() << "thor: We don't know how to start this CPU" << frg::endlog; return false; } // Allocate a stack for the initialization code. constexpr size_t stackSize = 0x10000; void *stackPtr = kernelAlloc->allocate(stackSize); auto context = frg::construct<CpuData>(*kernelAlloc); // Participate in global TLB invalidation *before* paging is used by the target CPU. { auto irqLock = frg::guard(&irqMutex()); context->globalBinding.bind(); } auto codePhysPtr = physicalAllocator->allocate(kPageSize); auto codeVirtPtr = KernelVirtualMemory::global().allocate(kPageSize); KernelPageSpace::global().mapSingle4k(VirtualAddr(codeVirtPtr), codePhysPtr, page_access::write, CachingMode::uncached); // We use a ClientPageSpace here to create an identity mapping for the trampoline ClientPageSpace lowMapping; lowMapping.mapSingle4k(codePhysPtr, codePhysPtr, false, page_access::execute, CachingMode::null); auto imageSize = (uintptr_t)_binary_kernel_thor_arch_arm_trampoline_bin_end - (uintptr_t)_binary_kernel_thor_arch_arm_trampoline_bin_start; assert(imageSize <= kPageSize); memcpy(codeVirtPtr, _binary_kernel_thor_arch_arm_trampoline_bin_start, imageSize); // Setup a status block to communicate information to the AP. auto statusBlock = reinterpret_cast<StatusBlock *>(reinterpret_cast<char *>(codeVirtPtr) + (kPageSize - sizeof(StatusBlock))); statusBlock->self = statusBlock; statusBlock->targetStage = 0; statusBlock->ttbr0 = lowMapping.rootTable(); statusBlock->ttbr1 = KernelPageSpace::global().rootTable(); statusBlock->stack = (uintptr_t)stackPtr + stackSize; statusBlock->main = &secondaryMain; statusBlock->cpuContext = context; statusBlock->cpuId = id; bool dontWait = false; switch(node->enableMethod()) { case EnableMethod::spintable: { infoLogger() << "thor: This CPU uses a spin-table" << frg::endlog; auto ptr = node->cpuReleaseAddr(); infoLogger() << "thor: Release address is " << frg::hex_fmt{ptr} << frg::endlog; auto page = ptr & ~(kPageSize - 1); auto offset = ptr & (kPageSize - 1); auto virtPtr = KernelVirtualMemory::global().allocate(kPageSize); KernelPageSpace::global().mapSingle4k(VirtualAddr(virtPtr), page, page_access::write, CachingMode::uncached); auto space = arch::mem_space{virtPtr}; arch::scalar_store<uintptr_t>(space, offset, codePhysPtr); asm volatile ("sev" ::: "memory"); KernelPageSpace::global().unmapSingle4k(VirtualAddr(virtPtr)); KernelVirtualMemory::global().deallocate(virtPtr, kPageSize); break; } case EnableMethod::psci: { infoLogger() << "thor: This CPU uses PSCI" << frg::endlog; if (!psci_) { infoLogger() << "thor: PSCI was not detected" << frg::endlog; return false; } int res = psci_->turnOnCpu(id, codePhysPtr); if (res < 0) { constexpr const char *errors[] = { "Success", "Not supported", "Invalid parameters", "Denied", "Already on", "On pending", "Internal failure", "Not present", "Disabled", "Invalid address" }; infoLogger() << "thor: Booting AP failed with " << errors[-res] << frg::endlog; dontWait = true; } break; } default: panicLogger() << "thor: Illegal enable method" << frg::endlog; } // Wait for AP to leave the stub so we can free it and the mapping it used if (!dontWait) { while(__atomic_load_n(&statusBlock->targetStage, __ATOMIC_ACQUIRE) == 0) ; } KernelPageSpace::global().unmapSingle4k(VirtualAddr(codeVirtPtr)); KernelVirtualMemory::global().deallocate(codeVirtPtr, kPageSize); KernelFiber::asyncBlockCurrent(KernelPageSpace::global().shootdown(VirtualAddr(codeVirtPtr), kPageSize)); physicalAllocator->free(codePhysPtr, kPageSize); if (dontWait) { kernelAlloc->deallocate(stackPtr, stackSize); } return !dontWait; } static initgraph::Task initAPs{&globalInitEngine, "arm.init-aps", initgraph::Requires{getDeviceTreeParsedStage(), getTaskingAvailableStage()}, [] { getDeviceTreeRoot()->forEach([&](DeviceTreeNode *node) -> bool { if (node->isCompatible<1>({"arm,psci"})) { psci_.initialize(node); return true; } return false; }); getDeviceTreeRoot()->forEach([&](DeviceTreeNode *node) -> bool { if (node->isCompatible<3>({"arm,cortex-a72", "arm,cortex-a53", "arm,arm-v8"})) { bootSecondary(node); } return false; }); } }; }
; ------------------------------------------------------------------------------ ; BITMAP MODE (MODE #2) ; ------------------------------------------------------------------------------ PLOTVBASELO: .byte <($A000+(0*320)),<($A000+(1*320)),<($A000+(2*320)),<($A000+(3*320)) .byte <($A000+(4*320)),<($A000+(5*320)),<($A000+(6*320)),<($A000+(7*320)) .byte <($A000+(8*320)),<($A000+(9*320)),<($A000+(10*320)),<($A000+(11*320)) .byte <($A000+(12*320)),<($A000+(13*320)),<($A000+(14*320)),<($A000+(15*320)) .byte <($A000+(16*320)),<($A000+(17*320)),<($A000+(18*320)),<($A000+(19*320)) .byte <($A000+(20*320)),<($A000+(21*320)),<($A000+(22*320)),<($A000+(23*320)) .byte <($A000+(24*320)) PLOTVBASEHI: .byte >($A000+(0*320)),>($A000+(1*320)),>($A000+(2*320)),>($A000+(3*320)) .byte >($A000+(4*320)),>($A000+(5*320)),>($A000+(6*320)),>($A000+(7*320)) .byte >($A000+(8*320)),>($A000+(9*320)),>($A000+(10*320)),>($A000+(11*320)) .byte >($A000+(12*320)),>($A000+(13*320)),>($A000+(14*320)),>($A000+(15*320)) .byte >($A000+(16*320)),>($A000+(17*320)),>($A000+(18*320)),>($A000+(19*320)) .byte >($A000+(20*320)),>($A000+(21*320)),>($A000+(22*320)),>($A000+(23*320)) .byte >($A000+(24*320)) PLOT8LO: .byte <(0*8),<(1*8),<(2*8),<(3*8),<(4*8),<(5*8),<(6*8),<(7*8),<(8*8),<(9*8) .byte <(10*8),<(11*8),<(12*8),<(13*8),<(14*8),<(15*8),<(16*8),<(17*8),<(18*8),<(19*8) .byte <(20*8),<(21*8),<(22*8),<(23*8),<(24*8),<(25*8),<(26*8),<(27*8),<(28*8),<(29*8) .byte <(30*8),<(31*8),<(32*8),<(33*8),<(34*8),<(35*8),<(36*8),<(37*8),<(38*8),<(39*8) PLOT8HI: .byte >(0*8),>(1*8),>(2*8),>(3*8),>(4*8),>(5*8),>(6*8),>(7*8),>(8*8),>(9*8) .byte >(10*8),>(11*8),>(12*8),>(13*8),>(14*8),>(15*8),>(16*8),>(17*8),>(18*8),>(19*8) .byte >(20*8),>(21*8),>(22*8),>(23*8),>(24*8),>(25*8),>(26*8),>(27*8),>(28*8),>(29*8) .byte >(30*8),>(31*8),>(32*8),>(33*8),>(34*8),>(35*8),>(36*8),>(37*8),>(38*8),>(39*8) PLOTCVBASELO: .byte <($8400+(0*40)),<($8400+(1*40)),<($8400+(2*40)),<($8400+(3*40)) .byte <($8400+(4*40)),<($8400+(5*40)),<($8400+(6*40)),<($8400+(7*40)) .byte <($8400+(8*40)),<($8400+(9*40)),<($8400+(10*40)),<($8400+(11*40)) .byte <($8400+(12*40)),<($8400+(13*40)),<($8400+(14*40)),<($8400+(15*40)) .byte <($8400+(16*40)),<($8400+(17*40)),<($8400+(18*40)),<($8400+(19*40)) .byte <($8400+(20*40)),<($8400+(21*40)),<($8400+(22*40)),<($8400+(23*40)) .byte <($8400+(24*40)) PLOTCVBASEHI: .byte >($8400+(0*40)),>($8400+(1*40)),>($8400+(2*40)),>($8400+(3*40)) .byte >($8400+(4*40)),>($8400+(5*40)),>($8400+(6*40)),>($8400+(7*40)) .byte >($8400+(8*40)),>($8400+(9*40)),>($8400+(10*40)),>($8400+(11*40)) .byte >($8400+(12*40)),>($8400+(13*40)),>($8400+(14*40)),>($8400+(15*40)) .byte >($8400+(16*40)),>($8400+(17*40)),>($8400+(18*40)),>($8400+(19*40)) .byte >($8400+(20*40)),>($8400+(21*40)),>($8400+(22*40)),>($8400+(23*40)) .byte >($8400+(24*40)) PLOTC2VBASELO: .byte <($D800+(0*40)),<($D800+(1*40)),<($D800+(2*40)),<($D800+(3*40)) .byte <($D800+(4*40)),<($D800+(5*40)),<($D800+(6*40)),<($D800+(7*40)) .byte <($D800+(8*40)),<($D800+(9*40)),<($D800+(10*40)),<($D800+(11*40)) .byte <($D800+(12*40)),<($D800+(13*40)),<($D800+(14*40)),<($D800+(15*40)) .byte <($D800+(16*40)),<($D800+(17*40)),<($D800+(18*40)),<($D800+(19*40)) .byte <($D800+(20*40)),<($D800+(21*40)),<($D800+(22*40)),<($D800+(23*40)) .byte <($D800+(24*40)) PLOTC2VBASEHI: .byte >($D800+(0*40)),>($D800+(1*40)),>($D800+(2*40)),>($D800+(3*40)) .byte >($D800+(4*40)),>($D800+(5*40)),>($D800+(6*40)),>($D800+(7*40)) .byte >($D800+(8*40)),>($D800+(9*40)),>($D800+(10*40)),>($D800+(11*40)) .byte >($D800+(12*40)),>($D800+(13*40)),>($D800+(14*40)),>($D800+(15*40)) .byte >($D800+(16*40)),>($D800+(17*40)),>($D800+(18*40)),>($D800+(19*40)) .byte >($D800+(20*40)),>($D800+(21*40)),>($D800+(22*40)),>($D800+(23*40)) .byte >($D800+(24*40)) ; ------------------------------------------------------------------------------ ; MULTICOLOR MODE (MODE #3) ; ------------------------------------------------------------------------------ PLOT4LO: .byte <(0*4),<(1*4),<(2*4),<(3*4),<(4*4),<(5*4),<(6*4),<(7*4),<(8*4),<(9*4) .byte <(10*4),<(11*4),<(12*4),<(13*4),<(14*4),<(15*4),<(16*4),<(17*4),<(18*4),<(19*4) .byte <(20*4),<(21*4),<(22*4),<(23*4),<(24*4),<(25*4),<(26*4),<(27*4),<(28*4),<(29*4) .byte <(30*4),<(31*4),<(32*4),<(33*4),<(34*4),<(35*4),<(36*4),<(37*4),<(38*4),<(39*4) .byte <(40*4),<(41*4),<(42*4),<(43*4),<(44*4),<(45*4),<(46*4),<(47*4),<(48*4),<(49*4) .byte <(50*4),<(51*4),<(52*4),<(53*4),<(54*4),<(55*4),<(56*4),<(57*4),<(58*4),<(59*4) .byte <(60*4),<(61*4),<(62*4),<(63*4),<(64*4),<(65*4),<(66*4),<(67*4),<(68*4),<(69*4) .byte <(70*4),<(71*4),<(72*4),<(73*4),<(74*4),<(75*4),<(76*4),<(77*4),<(78*4),<(79*4) PLOT4HI: .byte >(0*4),>(1*4),>(2*4),>(3*4),>(4*4),>(5*4),>(6*4),>(7*4),>(8*4),>(9*4) .byte >(10*4),>(11*4),>(12*4),>(13*4),>(14*4),>(15*4),>(16*4),>(17*4),>(18*4),>(19*4) .byte >(20*4),>(21*4),>(22*4),>(23*4),>(24*4),>(25*4),>(26*4),>(27*4),>(28*4),>(29*4) .byte >(30*4),>(31*4),>(32*4),>(33*4),>(34*4),>(35*4),>(36*4),>(37*4),>(38*4),>(39*4) .byte >(40*4),>(41*4),>(42*4),>(43*4),>(44*4),>(45*4),>(46*4),>(47*4),>(48*4),>(49*4) .byte >(50*4),>(51*4),>(52*4),>(53*4),>(54*4),>(55*4),>(56*4),>(57*4),>(58*4),>(59*4) .byte >(60*4),>(61*4),>(62*4),>(63*4),>(64*4),>(65*4),>(66*4),>(67*4),>(68*4),>(69*4) .byte >(70*4),>(71*4),>(72*4),>(73*4),>(74*4),>(75*4),>(76*4),>(77*4),>(78*4),>(79*4)
# 本文档存储器以字节编址 # 本文档存储器以字节编址 # 本文档存储器以字节编址 # 初始PC = 0x00000000 .data .word 0,6,0,16,0x80000000,0x80000100,0x100,5,0 #编译成机器码时,编译器会在前面多加个0,所以后面lw指令地址会多加4 _start: addi $t0,$0,3 #t0=3 0 addi $t1,$t0,2 #t1=5 4 addi $t2,$0,1 #t2=1 8 addi $t3,$0,0 #t3=0 12 add $s0,$t1,$t0 #s0=t1+t0=8 测试add指令 16 add $s0,$s0,$s0 #s0=s0+s0=16 20 lw $s1,12($0) # 24 beq $s1,$s0,_next1 #正确跳到_next 28 j _fail _next1: lw $t0, 16($0) #t0 = 0x80000000 36 lw $t1, 20($0) #t1 = 0x80000100 40 add $s0,$t1,$t0 #s0 = 0x00000100 = 256 44 lw $s1, 24($0) # 48 beq $s1,$s0,_next2 #正确跳到_success 52 j _fail _next2: add $0, $0, $t2 #$0应该一直为0 60 beq $0,$t3,_success # 64 _fail: sw $t3,8($0) #失败通过看存储器地址0x08里值,若为0则测试不通过,最初地址0x08里值为0 64 j _fail 68 _success: sw $t2,8($0) #全部测试通过,存储器地址0x08里值为1 72 j _success 76 #判断测试通过的条件是最后存储器地址0x08里值为1,说明全部通过测试
; A248429: Number of length n+2 0..4 arrays with every three consecutive terms having the sum of some two elements equal to twice the third. ; 29,45,69,101,165,261,389,645,1029,1541,2565,4101,6149,10245,16389,24581,40965,65541,98309,163845,262149,393221,655365,1048581,1572869,2621445,4194309,6291461,10485765,16777221,25165829,41943045,67108869,100663301,167772165,268435461,402653189,671088645,1073741829,1610612741,2684354565,4294967301,6442450949,10737418245,17179869189,25769803781,42949672965,68719476741,103079215109,171798691845,274877906949,412316860421,687194767365,1099511627781,1649267441669,2748779069445,4398046511109 lpb $0 sub $0,1 add $2,2 mov $1,$2 trn $1,$0 add $2,$1 lpe mul $1,8 add $1,29 mov $0,$1
#pragma once #include "LDAModel.hpp" #include "../Utils/LBFGS.h" #include "../Utils/text.hpp" #include "DMR.h" /* Implementation of DMR using Gibbs sampling by bab2min * Mimno, D., & McCallum, A. (2012). Topic models conditioned on arbitrary features with dirichlet-multinomial regression. arXiv preprint arXiv:1206.3278. */ namespace tomoto { template<TermWeight _tw> struct ModelStateDMR : public ModelStateLDA<_tw> { Eigen::Matrix<Float, -1, 1> tmpK; }; template<TermWeight _tw, typename _RandGen, size_t _Flags = flags::partitioned_multisampling, typename _Interface = IDMRModel, typename _Derived = void, typename _DocType = DocumentDMR<_tw>, typename _ModelState = ModelStateDMR<_tw>> class DMRModel : public LDAModel<_tw, _RandGen, _Flags, _Interface, typename std::conditional<std::is_same<_Derived, void>::value, DMRModel<_tw, _RandGen, _Flags>, _Derived>::type, _DocType, _ModelState> { protected: using DerivedClass = typename std::conditional<std::is_same<_Derived, void>::value, DMRModel<_tw, _RandGen>, _Derived>::type; using BaseClass = LDAModel<_tw, _RandGen, _Flags, _Interface, DerivedClass, _DocType, _ModelState>; friend BaseClass; friend typename BaseClass::BaseClass; using WeightType = typename BaseClass::WeightType; static constexpr char TMID[] = "DMR\0"; Eigen::Matrix<Float, -1, -1> lambda; Eigen::Matrix<Float, -1, -1> expLambda; Float sigma; uint32_t F = 0; uint32_t optimRepeat = 5; Float alphaEps = 1e-10; Float temperatureScale = 0; static constexpr Float maxLambda = 10; static constexpr size_t maxBFGSIteration = 10; Dictionary metadataDict; LBFGSpp::LBFGSSolver<Float, LBFGSpp::LineSearchBracketing> solver; Float getNegativeLambdaLL(Eigen::Ref<Eigen::Matrix<Float, -1, 1>> x, Eigen::Matrix<Float, -1, 1>& g) const { g = (x.array() - log(this->alpha)) / pow(sigma, 2); return (x.array() - log(this->alpha)).pow(2).sum() / 2 / pow(sigma, 2); } Float evaluateLambdaObj(Eigen::Ref<Eigen::Matrix<Float, -1, 1>> x, Eigen::Matrix<Float, -1, 1>& g, ThreadPool& pool, _ModelState* localData) const { // if one of x is greater than maxLambda, return +inf for preventing searching more if ((x.array() > maxLambda).any()) return INFINITY; const auto K = this->K; Float fx = - static_cast<const DerivedClass*>(this)->getNegativeLambdaLL(x, g); auto alphas = (x.array().exp() + alphaEps).eval(); std::vector<std::future<Eigen::Matrix<Float, -1, 1>>> res; const size_t chStride = pool.getNumWorkers() * 8; for (size_t ch = 0; ch < chStride; ++ch) { res.emplace_back(pool.enqueue([&](size_t threadId) { auto& tmpK = localData[threadId].tmpK; if (!tmpK.size()) tmpK.resize(this->K); Eigen::Matrix<Float, -1, 1> val = Eigen::Matrix<Float, -1, 1>::Zero(K * F + 1); for (size_t docId = ch; docId < this->docs.size(); docId += chStride) { const auto& doc = this->docs[docId]; auto alphaDoc = alphas.segment(doc.metadata * K, K); Float alphaSum = alphaDoc.sum(); for (Tid k = 0; k < K; ++k) { val[K * F] -= math::lgammaT(alphaDoc[k]) - math::lgammaT(doc.numByTopic[k] + alphaDoc[k]); if (!std::isfinite(alphaDoc[k]) && alphaDoc[k] > 0) tmpK[k] = 0; else tmpK[k] = -(math::digammaT(alphaDoc[k]) - math::digammaT(doc.numByTopic[k] + alphaDoc[k])); } //val[K * F] = -(lgammaApprox(alphaDoc.array()) - lgammaApprox(doc.numByTopic.array().cast<Float>() + alphaDoc.array())).sum(); //tmpK = -(digammaApprox(alphaDoc.array()) - digammaApprox(doc.numByTopic.array().cast<Float>() + alphaDoc.array())); val[K * F] += math::lgammaT(alphaSum) - math::lgammaT(doc.getSumWordWeight() + alphaSum); Float t = math::digammaT(alphaSum) - math::digammaT(doc.getSumWordWeight() + alphaSum); if (!std::isfinite(alphaSum) && alphaSum > 0) { val[K * F] = -INFINITY; t = 0; } val.segment(doc.metadata * K, K).array() -= alphaDoc.array() * (tmpK.array() + t); } return val; })); } for (auto& r : res) { auto ret = r.get(); fx += ret[K * F]; g += ret.head(K * F); } // positive fx is an error from limited precision of float. if (fx > 0) return INFINITY; return -fx; } void initParameters() { auto dist = std::normal_distribution<Float>(log(this->alpha), sigma); for (size_t i = 0; i < this->K; ++i) for (size_t j = 0; j < F; ++j) { lambda(i, j) = dist(this->rg); } } void optimizeParameters(ThreadPool& pool, _ModelState* localData, _RandGen* rgs) { Eigen::Matrix<Float, -1, -1> bLambda; Float fx = 0, bestFx = INFINITY; for (size_t i = 0; i < optimRepeat; ++i) { static_cast<DerivedClass*>(this)->initParameters(); int ret = solver.minimize([this, &pool, localData](Eigen::Ref<Eigen::Matrix<Float, -1, 1>> x, Eigen::Matrix<Float, -1, 1>& g) { return static_cast<DerivedClass*>(this)->evaluateLambdaObj(x, g, pool, localData); }, Eigen::Map<Eigen::Matrix<Float, -1, 1>>(lambda.data(), lambda.size()), fx); if (fx < bestFx) { bLambda = lambda; bestFx = fx; //printf("\t(%d) %e\n", ret, fx); } } if (!std::isfinite(bestFx)) { throw exception::TrainingError{ "optimizing parameters has been failed!" }; } lambda = bLambda; //std::cerr << fx << std::endl; expLambda = lambda.array().exp() + alphaEps; } int restoreFromTrainingError(const exception::TrainingError& e, ThreadPool& pool, _ModelState* localData, _RandGen* rgs) { std::cerr << "Failed to optimize! Reset prior and retry!" << std::endl; lambda.setZero(); expLambda = lambda.array().exp() + alphaEps; return 0; } template<bool _asymEta> Float* getZLikelihoods(_ModelState& ld, const _DocType& doc, size_t docId, size_t vid) const { const size_t V = this->realV; assert(vid < V); auto etaHelper = this->template getEtaHelper<_asymEta>(); auto& zLikelihood = ld.zLikelihood; zLikelihood = (doc.numByTopic.array().template cast<Float>() + this->expLambda.col(doc.metadata).array()) * (ld.numByTopicWord.col(vid).array().template cast<Float>() + etaHelper.getEta(vid)) / (ld.numByTopic.array().template cast<Float>() + etaHelper.getEtaSum()); sample::prefixSum(zLikelihood.data(), this->K); return &zLikelihood[0]; } double getLLDocTopic(const _DocType& doc) const { const size_t V = this->realV; const auto K = this->K; auto alphaDoc = expLambda.col(doc.metadata); Float ll = 0; Float alphaSum = alphaDoc.sum(); for (Tid k = 0; k < K; ++k) { ll += math::lgammaT(doc.numByTopic[k] + alphaDoc[k]); ll -= math::lgammaT(alphaDoc[k]); } ll -= math::lgammaT(doc.getSumWordWeight() + alphaSum); ll += math::lgammaT(alphaSum); return ll; } template<typename _DocIter> double getLLDocs(_DocIter _first, _DocIter _last) const { const auto K = this->K; double ll = 0; for (; _first != _last; ++_first) { auto& doc = *_first; auto alphaDoc = expLambda.col(doc.metadata); Float alphaSum = alphaDoc.sum(); for (Tid k = 0; k < K; ++k) { ll += math::lgammaT(doc.numByTopic[k] + alphaDoc[k]) - math::lgammaT(alphaDoc[k]); } ll -= math::lgammaT(doc.getSumWordWeight() + alphaSum) - math::lgammaT(alphaSum); } return ll; } double getLLRest(const _ModelState& ld) const { const auto K = this->K; const auto alpha = this->alpha; const auto eta = this->eta; const size_t V = this->realV; double ll = -(lambda.array() - log(alpha)).pow(2).sum() / 2 / pow(sigma, 2); // topic-word distribution auto lgammaEta = math::lgammaT(eta); ll += math::lgammaT(V*eta) * K; for (Tid k = 0; k < K; ++k) { ll -= math::lgammaT(ld.numByTopic[k] + V * eta); for (Vid v = 0; v < V; ++v) { if (!ld.numByTopicWord(k, v)) continue; ll += math::lgammaT(ld.numByTopicWord(k, v) + eta) - lgammaEta; } } return ll; } void initGlobalState(bool initDocs) { BaseClass::initGlobalState(initDocs); this->globalState.tmpK = Eigen::Matrix<Float, -1, 1>::Zero(this->K); F = metadataDict.size(); if (initDocs) { lambda = Eigen::Matrix<Float, -1, -1>::Constant(this->K, F, log(this->alpha)); } if (_Flags & flags::continuous_doc_data) this->numByTopicDoc = Eigen::Matrix<WeightType, -1, -1>::Zero(this->K, this->docs.size()); expLambda = lambda.array().exp(); LBFGSpp::LBFGSParam<Float> param; param.max_iterations = maxBFGSIteration; solver = decltype(solver){ param }; } public: DEFINE_SERIALIZER_AFTER_BASE_WITH_VERSION(BaseClass, 0, sigma, alphaEps, metadataDict, lambda); DEFINE_TAGGED_SERIALIZER_AFTER_BASE_WITH_VERSION(BaseClass, 1, 0x00010001, sigma, alphaEps, metadataDict, lambda); DMRModel(size_t _K = 1, Float defaultAlpha = 1.0, Float _sigma = 1.0, Float _eta = 0.01, Float _alphaEps = 0, size_t _rg = std::random_device{}()) : BaseClass(_K, defaultAlpha, _eta, _rg), sigma(_sigma), alphaEps(_alphaEps) { if (_sigma <= 0) THROW_ERROR_WITH_INFO(std::runtime_error, text::format("wrong sigma value (sigma = %f)", _sigma)); } template<bool _const = false> _DocType& _updateDoc(_DocType& doc, const std::vector<std::string>& metadata) { std::string metadataJoined = text::join(metadata.begin(), metadata.end(), "_"); Vid xid; if (_const) { xid = metadataDict.toWid(metadataJoined); if (xid == (Vid)-1) throw std::invalid_argument("unknown metadata"); } else { xid = metadataDict.add(metadataJoined); } doc.metadata = xid; return doc; } size_t addDoc(const std::vector<std::string>& words, const std::vector<std::string>& metadata) override { auto doc = this->_makeDoc(words); return this->_addDoc(_updateDoc(doc, metadata)); } std::unique_ptr<DocumentBase> makeDoc(const std::vector<std::string>& words, const std::vector<std::string>& metadata) const override { auto doc = as_mutable(this)->template _makeDoc<true>(words); return make_unique<_DocType>(as_mutable(this)->template _updateDoc<true>(doc, metadata)); } size_t addDoc(const std::string& rawStr, const RawDocTokenizer::Factory& tokenizer, const std::vector<std::string>& metadata) override { auto doc = this->template _makeRawDoc<false>(rawStr, tokenizer); return this->_addDoc(_updateDoc(doc, metadata)); } std::unique_ptr<DocumentBase> makeDoc(const std::string& rawStr, const RawDocTokenizer::Factory& tokenizer, const std::vector<std::string>& metadata) const override { auto doc = as_mutable(this)->template _makeRawDoc<true>(rawStr, tokenizer); return make_unique<_DocType>(as_mutable(this)->template _updateDoc<true>(doc, metadata)); } size_t addDoc(const std::string& rawStr, const std::vector<Vid>& words, const std::vector<uint32_t>& pos, const std::vector<uint16_t>& len, const std::vector<std::string>& metadata) override { auto doc = this->_makeRawDoc(rawStr, words, pos, len); return this->_addDoc(_updateDoc(doc, metadata)); } std::unique_ptr<DocumentBase> makeDoc(const std::string& rawStr, const std::vector<Vid>& words, const std::vector<uint32_t>& pos, const std::vector<uint16_t>& len, const std::vector<std::string>& metadata) const override { auto doc = this->_makeRawDoc(rawStr, words, pos, len); return make_unique<_DocType>(as_mutable(this)->template _updateDoc<true>(doc, metadata)); } GETTER(F, size_t, F); GETTER(Sigma, Float, sigma); GETTER(AlphaEps, Float, alphaEps); GETTER(OptimRepeat, size_t, optimRepeat); void setAlphaEps(Float _alphaEps) override { alphaEps = _alphaEps; } void setOptimRepeat(size_t _optimRepeat) override { optimRepeat = _optimRepeat; } std::vector<Float> getTopicsByDoc(const _DocType& doc) const { std::vector<Float> ret(this->K); auto alphaDoc = expLambda.col(doc.metadata); Eigen::Map<Eigen::Matrix<Float, -1, 1>>{ret.data(), this->K}.array() = (doc.numByTopic.array().template cast<Float>() + alphaDoc.array()) / (doc.getSumWordWeight() + alphaDoc.sum()); return ret; } std::vector<Float> getLambdaByMetadata(size_t metadataId) const override { assert(metadataId < metadataDict.size()); auto l = lambda.col(metadataId); return { l.data(), l.data() + this->K }; } std::vector<Float> getLambdaByTopic(Tid tid) const override { assert(tid < this->K); auto l = lambda.row(tid); return { l.data(), l.data() + F }; } const Dictionary& getMetadataDict() const override { return metadataDict; } }; /* This is for preventing 'undefined symbol' problem in compiling by clang. */ template<TermWeight _tw, typename _RandGen, size_t _Flags, typename _Interface, typename _Derived, typename _DocType, typename _ModelState> constexpr Float DMRModel<_tw, _RandGen, _Flags, _Interface, _Derived, _DocType, _ModelState>::maxLambda; template<TermWeight _tw, typename _RandGen, size_t _Flags, typename _Interface, typename _Derived, typename _DocType, typename _ModelState> constexpr size_t DMRModel<_tw, _RandGen, _Flags, _Interface, _Derived, _DocType, _ModelState>::maxBFGSIteration; }
; A097070: Consider all compositions (ordered partitions) of n into n parts, allowing zeros. E.g., for n = 3 we get 300, 030, 003, 210, 120, 201, 102, 021, 012, 111. Then a(n) is the total number of 1's. ; 1,2,9,40,175,756,3234,13728,57915,243100,1016158,4232592,17577014,72804200,300874500,1240940160,5109183315,21002455980,86213785350,353452638000,1447388552610,5920836618840,24197138082780,98801168731200,403095046038750,1643337883690776,6694900194799404,27257151959073568,110906013711026380,451008997493115600,1833101014255352072,7446853652084177408,30238298325552743811,122730283378276517580,497928225816710092950,2019353000699931217776,8186481995121480415274,33176480722376897986808,134406102649518596414700,544340297383980640312000,2203897779033391617463210,8920476197824626154205640,36096575453555658440317380,146026167870522620407557600,590591371087909151751640500,2388030689613728461502435760,9653693061888390009306160440,39016827368284086013166772480,157659141839724323256329275950,636940306474521422568260715000,2572729285911886930037718680028,10389830226535355752832063442912,41951244975337653146975025395604,169358176582530789137307507293040,683589073517279625564509383003800,2758762118842627989716208445524096,11131816279283996996769420175274844,44911002705095300902940461575100848,181165965133217370170303823892425240,730700991229638574315158198060801600 mov $1,$0 add $0,1 mov $2,$1 mov $3,$1 sub $3,1 add $2,$3 bin $2,$1 mul $0,$2
; void *heap_alloc_unlocked(void *heap, size_t size) SECTION code_clib SECTION code_alloc_malloc PUBLIC heap_alloc_unlocked_callee EXTERN asm_heap_alloc_unlocked heap_alloc_unlocked_callee: pop af pop hl pop de push af jp asm_heap_alloc_unlocked
; A328263: a(n) = number of letters in a(n-1) (in Polish), with a(1) = 1. ; 1,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6,5,4,6 lpb $0 mod $0,3 sub $0,5 sub $1,$0 trn $0,1 lpe add $1,1
;***************************************************************************** ;* MMX/SSE2/AVX-optimized 10-bit H.264 intra prediction code ;***************************************************************************** ;* Copyright (C) 2005-2011 x264 project ;* ;* Authors: Daniel Kang <daniel.d.kang@gmail.com> ;* ;* This file is part of Libav. ;* ;* Libav is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* Libav is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with Libav; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "x86inc.asm" %include "x86util.asm" SECTION_RODATA cextern pw_16 cextern pw_8 cextern pw_4 cextern pw_2 cextern pw_1 pw_m32101234: dw -3, -2, -1, 0, 1, 2, 3, 4 pw_m3: times 8 dw -3 pw_pixel_max: times 8 dw ((1 << 10)-1) pw_512: times 8 dw 512 pd_17: times 4 dd 17 pd_16: times 4 dd 16 SECTION .text ; dest, left, right, src ; output: %1 = (t[n-1] + t[n]*2 + t[n+1] + 2) >> 2 %macro PRED4x4_LOWPASS 4 paddw %2, %3 psrlw %2, 1 pavgw %1, %4, %2 %endmacro ;----------------------------------------------------------------------------- ; void pred4x4_down_right(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- %macro PRED4x4_DR 1 cglobal pred4x4_down_right_10_%1, 3,3 sub r0, r2 lea r1, [r0+r2*2] movhps m1, [r1-8] movhps m2, [r0+r2*1-8] movhps m4, [r0-8] punpckhwd m2, m4 movq m3, [r0] punpckhdq m1, m2 PALIGNR m3, m1, 10, m1 movhps m4, [r1+r2*1-8] PALIGNR m0, m3, m4, 14, m4 movhps m4, [r1+r2*2-8] PALIGNR m2, m0, m4, 14, m4 PRED4x4_LOWPASS m0, m2, m3, m0 movq [r1+r2*2], m0 psrldq m0, 2 movq [r1+r2*1], m0 psrldq m0, 2 movq [r0+r2*2], m0 psrldq m0, 2 movq [r0+r2*1], m0 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED4x4_DR sse2 %define PALIGNR PALIGNR_SSSE3 PRED4x4_DR ssse3 %ifdef HAVE_AVX INIT_AVX PRED4x4_DR avx %endif ;----------------------------------------------------------------------------- ; void pred4x4_vertical_right(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- %macro PRED4x4_VR 1 cglobal pred4x4_vertical_right_10_%1, 3,3,6 sub r0, r2 lea r1, [r0+r2*2] movq m5, [r0] ; ........t3t2t1t0 movhps m1, [r0-8] PALIGNR m0, m5, m1, 14, m1 ; ......t3t2t1t0lt pavgw m5, m0 movhps m1, [r0+r2*1-8] PALIGNR m0, m1, 14, m1 ; ....t3t2t1t0ltl0 movhps m2, [r0+r2*2-8] PALIGNR m1, m0, m2, 14, m2 ; ..t3t2t1t0ltl0l1 movhps m3, [r1+r2*1-8] PALIGNR m2, m1, m3, 14, m3 ; t3t2t1t0ltl0l1l2 PRED4x4_LOWPASS m1, m0, m2, m1 pslldq m0, m1, 12 psrldq m1, 4 movq [r0+r2*1], m5 movq [r0+r2*2], m1 PALIGNR m5, m0, 14, m2 pslldq m0, 2 movq [r1+r2*1], m5 PALIGNR m1, m0, 14, m0 movq [r1+r2*2], m1 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED4x4_VR sse2 %define PALIGNR PALIGNR_SSSE3 PRED4x4_VR ssse3 %ifdef HAVE_AVX INIT_AVX PRED4x4_VR avx %endif ;----------------------------------------------------------------------------- ; void pred4x4_horizontal_down(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- %macro PRED4x4_HD 1 cglobal pred4x4_horizontal_down_10_%1, 3,3 sub r0, r2 lea r1, [r0+r2*2] movq m0, [r0-8] ; lt .. movhps m0, [r0] pslldq m0, 2 ; t2 t1 t0 lt .. .. .. .. movq m1, [r1+r2*2-8] ; l3 movq m3, [r1+r2*1-8] punpcklwd m1, m3 ; l2 l3 movq m2, [r0+r2*2-8] ; l1 movq m3, [r0+r2*1-8] punpcklwd m2, m3 ; l0 l1 punpckhdq m1, m2 ; l0 l1 l2 l3 punpckhqdq m1, m0 ; t2 t1 t0 lt l0 l1 l2 l3 psrldq m0, m1, 4 ; .. .. t2 t1 t0 lt l0 l1 psrldq m3, m1, 2 ; .. t2 t1 t0 lt l0 l1 l2 pavgw m5, m1, m3 PRED4x4_LOWPASS m3, m1, m0, m3 punpcklwd m5, m3 psrldq m3, 8 PALIGNR m3, m5, 12, m4 movq [r1+r2*2], m5 movhps [r0+r2*2], m5 psrldq m5, 4 movq [r1+r2*1], m5 movq [r0+r2*1], m3 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED4x4_HD sse2 %define PALIGNR PALIGNR_SSSE3 PRED4x4_HD ssse3 %ifdef HAVE_AVX INIT_AVX PRED4x4_HD avx %endif ;----------------------------------------------------------------------------- ; void pred4x4_dc(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- %macro HADDD 2 ; sum junk %if mmsize == 16 movhlps %2, %1 paddd %1, %2 pshuflw %2, %1, 0xE paddd %1, %2 %else pshufw %2, %1, 0xE paddd %1, %2 %endif %endmacro %macro HADDW 2 pmaddwd %1, [pw_1] HADDD %1, %2 %endmacro INIT_MMX cglobal pred4x4_dc_10_mmxext, 3,3 sub r0, r2 lea r1, [r0+r2*2] movq m2, [r0+r2*1-8] paddw m2, [r0+r2*2-8] paddw m2, [r1+r2*1-8] paddw m2, [r1+r2*2-8] psrlq m2, 48 movq m0, [r0] HADDW m0, m1 paddw m0, [pw_4] paddw m0, m2 psrlw m0, 3 SPLATW m0, m0, 0 movq [r0+r2*1], m0 movq [r0+r2*2], m0 movq [r1+r2*1], m0 movq [r1+r2*2], m0 RET ;----------------------------------------------------------------------------- ; void pred4x4_down_left(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- %macro PRED4x4_DL 1 cglobal pred4x4_down_left_10_%1, 3,3 sub r0, r2 movq m0, [r0] movhps m0, [r1] psrldq m2, m0, 2 pslldq m3, m0, 2 pshufhw m2, m2, 10100100b PRED4x4_LOWPASS m0, m3, m2, m0 lea r1, [r0+r2*2] movhps [r1+r2*2], m0 psrldq m0, 2 movq [r0+r2*1], m0 psrldq m0, 2 movq [r0+r2*2], m0 psrldq m0, 2 movq [r1+r2*1], m0 RET %endmacro INIT_XMM PRED4x4_DL sse2 %ifdef HAVE_AVX INIT_AVX PRED4x4_DL avx %endif ;----------------------------------------------------------------------------- ; void pred4x4_vertical_left(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- %macro PRED4x4_VL 1 cglobal pred4x4_vertical_left_10_%1, 3,3 sub r0, r2 movu m1, [r0] movhps m1, [r1] psrldq m0, m1, 2 psrldq m2, m1, 4 pavgw m4, m0, m1 PRED4x4_LOWPASS m0, m1, m2, m0 lea r1, [r0+r2*2] movq [r0+r2*1], m4 movq [r0+r2*2], m0 psrldq m4, 2 psrldq m0, 2 movq [r1+r2*1], m4 movq [r1+r2*2], m0 RET %endmacro INIT_XMM PRED4x4_VL sse2 %ifdef HAVE_AVX INIT_AVX PRED4x4_VL avx %endif ;----------------------------------------------------------------------------- ; void pred4x4_horizontal_up(pixel *src, const pixel *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX cglobal pred4x4_horizontal_up_10_mmxext, 3,3 sub r0, r2 lea r1, [r0+r2*2] movq m0, [r0+r2*1-8] punpckhwd m0, [r0+r2*2-8] movq m1, [r1+r2*1-8] punpckhwd m1, [r1+r2*2-8] punpckhdq m0, m1 pshufw m1, m1, 0xFF movq [r1+r2*2], m1 movd [r1+r2*1+4], m1 pshufw m2, m0, 11111001b movq m1, m2 pavgw m2, m0 pshufw m5, m0, 11111110b PRED4x4_LOWPASS m1, m0, m5, m1 movq m6, m2 punpcklwd m6, m1 movq [r0+r2*1], m6 psrlq m2, 16 psrlq m1, 16 punpcklwd m2, m1 movq [r0+r2*2], m2 psrlq m2, 32 movd [r1+r2*1], m2 RET ;----------------------------------------------------------------------------- ; void pred8x8_vertical(pixel *src, int stride) ;----------------------------------------------------------------------------- INIT_XMM cglobal pred8x8_vertical_10_sse2, 2,2 sub r0, r1 mova m0, [r0] %rep 3 mova [r0+r1*1], m0 mova [r0+r1*2], m0 lea r0, [r0+r1*2] %endrep mova [r0+r1*1], m0 mova [r0+r1*2], m0 RET ;----------------------------------------------------------------------------- ; void pred8x8_horizontal(pixel *src, int stride) ;----------------------------------------------------------------------------- INIT_XMM cglobal pred8x8_horizontal_10_sse2, 2,3 mov r2d, 4 .loop: movq m0, [r0+r1*0-8] movq m1, [r0+r1*1-8] pshuflw m0, m0, 0xff pshuflw m1, m1, 0xff punpcklqdq m0, m0 punpcklqdq m1, m1 mova [r0+r1*0], m0 mova [r0+r1*1], m1 lea r0, [r0+r1*2] dec r2d jg .loop REP_RET ;----------------------------------------------------------------------------- ; void predict_8x8_dc(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro MOV8 2-3 ; sort of a hack, but it works %if mmsize==8 movq [%1+0], %2 movq [%1+8], %3 %else movdqa [%1], %2 %endif %endmacro %macro PRED8x8_DC 2 cglobal pred8x8_dc_10_%1, 2,6 sub r0, r1 pxor m4, m4 movq m0, [r0+0] movq m1, [r0+8] %if mmsize==16 punpcklwd m0, m1 movhlps m1, m0 paddw m0, m1 %else pshufw m2, m0, 00001110b pshufw m3, m1, 00001110b paddw m0, m2 paddw m1, m3 punpcklwd m0, m1 %endif %2 m2, m0, 00001110b paddw m0, m2 lea r5, [r1*3] lea r4, [r0+r1*4] movzx r2d, word [r0+r1*1-2] movzx r3d, word [r0+r1*2-2] add r2d, r3d movzx r3d, word [r0+r5*1-2] add r2d, r3d movzx r3d, word [r4-2] add r2d, r3d movd m2, r2d ; s2 movzx r2d, word [r4+r1*1-2] movzx r3d, word [r4+r1*2-2] add r2d, r3d movzx r3d, word [r4+r5*1-2] add r2d, r3d movzx r3d, word [r4+r1*4-2] add r2d, r3d movd m3, r2d ; s3 punpcklwd m2, m3 punpckldq m0, m2 ; s0, s1, s2, s3 %2 m3, m0, 11110110b ; s2, s1, s3, s3 %2 m0, m0, 01110100b ; s0, s1, s3, s1 paddw m0, m3 psrlw m0, 2 pavgw m0, m4 ; s0+s2, s1, s3, s1+s3 %if mmsize==16 punpcklwd m0, m0 pshufd m3, m0, 11111010b punpckldq m0, m0 SWAP 0,1 %else pshufw m1, m0, 0x00 pshufw m2, m0, 0x55 pshufw m3, m0, 0xaa pshufw m4, m0, 0xff %endif MOV8 r0+r1*1, m1, m2 MOV8 r0+r1*2, m1, m2 MOV8 r0+r5*1, m1, m2 MOV8 r0+r1*4, m1, m2 MOV8 r4+r1*1, m3, m4 MOV8 r4+r1*2, m3, m4 MOV8 r4+r5*1, m3, m4 MOV8 r4+r1*4, m3, m4 RET %endmacro INIT_MMX PRED8x8_DC mmxext, pshufw INIT_XMM PRED8x8_DC sse2 , pshuflw ;----------------------------------------------------------------------------- ; void pred8x8_top_dc(pixel *src, int stride) ;----------------------------------------------------------------------------- INIT_XMM cglobal pred8x8_top_dc_10_sse2, 2,4 sub r0, r1 mova m0, [r0] pshuflw m1, m0, 0x4e pshufhw m1, m1, 0x4e paddw m0, m1 pshuflw m1, m0, 0xb1 pshufhw m1, m1, 0xb1 paddw m0, m1 lea r2, [r1*3] lea r3, [r0+r1*4] paddw m0, [pw_2] psrlw m0, 2 mova [r0+r1*1], m0 mova [r0+r1*2], m0 mova [r0+r2*1], m0 mova [r0+r1*4], m0 mova [r3+r1*1], m0 mova [r3+r1*2], m0 mova [r3+r2*1], m0 mova [r3+r1*4], m0 RET ;----------------------------------------------------------------------------- ; void pred8x8_plane(pixel *src, int stride) ;----------------------------------------------------------------------------- INIT_XMM cglobal pred8x8_plane_10_sse2, 2,7,7 sub r0, r1 lea r2, [r1*3] lea r3, [r0+r1*4] mova m2, [r0] pmaddwd m2, [pw_m32101234] HADDD m2, m1 movd m0, [r0-4] psrld m0, 14 psubw m2, m0 ; H movd m0, [r3+r1*4-4] movd m1, [r0+12] paddw m0, m1 psllw m0, 4 ; 16*(src[7*stride-1] + src[-stride+7]) movzx r4d, word [r3+r1*1-2] ; src[4*stride-1] movzx r5d, word [r0+r2*1-2] ; src[2*stride-1] sub r4d, r5d movzx r6d, word [r3+r1*2-2] ; src[5*stride-1] movzx r5d, word [r0+r1*2-2] ; src[1*stride-1] sub r6d, r5d lea r4d, [r4+r6*2] movzx r5d, word [r3+r2*1-2] ; src[6*stride-1] movzx r6d, word [r0+r1*1-2] ; src[0*stride-1] sub r5d, r6d lea r5d, [r5*3] add r4d, r5d movzx r6d, word [r3+r1*4-2] ; src[7*stride-1] movzx r5d, word [r0+r1*0-2] ; src[ -stride-1] sub r6d, r5d lea r4d, [r4+r6*4] movd m3, r4d ; V punpckldq m2, m3 pmaddwd m2, [pd_17] paddd m2, [pd_16] psrad m2, 5 ; b, c mova m3, [pw_pixel_max] pxor m1, m1 SPLATW m0, m0, 1 SPLATW m4, m2, 2 SPLATW m2, m2, 0 pmullw m2, [pw_m32101234] ; b pmullw m5, m4, [pw_m3] ; c paddw m5, [pw_16] mov r2d, 8 add r0, r1 .loop: paddsw m6, m2, m5 paddsw m6, m0 psraw m6, 5 CLIPW m6, m1, m3 mova [r0], m6 paddw m5, m4 add r0, r1 dec r2d jg .loop REP_RET ;----------------------------------------------------------------------------- ; void pred8x8l_128_dc(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_128_DC 1 cglobal pred8x8l_128_dc_10_%1, 4,4 mova m0, [pw_512] ; (1<<(BIT_DEPTH-1)) lea r1, [r3*3] lea r2, [r0+r3*4] MOV8 r0+r3*0, m0, m0 MOV8 r0+r3*1, m0, m0 MOV8 r0+r3*2, m0, m0 MOV8 r0+r1*1, m0, m0 MOV8 r2+r3*0, m0, m0 MOV8 r2+r3*1, m0, m0 MOV8 r2+r3*2, m0, m0 MOV8 r2+r1*1, m0, m0 RET %endmacro INIT_MMX PRED8x8L_128_DC mmxext INIT_XMM PRED8x8L_128_DC sse2 ;----------------------------------------------------------------------------- ; void pred8x8l_top_dc(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_TOP_DC 1 cglobal pred8x8l_top_dc_10_%1, 4,4,6 sub r0, r3 mova m0, [r0] shr r1d, 14 shr r2d, 13 neg r1 pslldq m1, m0, 2 psrldq m2, m0, 2 pinsrw m1, [r0+r1], 0 pinsrw m2, [r0+r2+14], 7 lea r1, [r3*3] lea r2, [r0+r3*4] PRED4x4_LOWPASS m0, m2, m1, m0 HADDW m0, m1 paddw m0, [pw_4] psrlw m0, 3 SPLATW m0, m0, 0 mova [r0+r3*1], m0 mova [r0+r3*2], m0 mova [r0+r1*1], m0 mova [r0+r3*4], m0 mova [r2+r3*1], m0 mova [r2+r3*2], m0 mova [r2+r1*1], m0 mova [r2+r3*4], m0 RET %endmacro INIT_XMM PRED8x8L_TOP_DC sse2 %ifdef HAVE_AVX INIT_AVX PRED8x8L_TOP_DC avx %endif ;----------------------------------------------------------------------------- ;void pred8x8l_dc(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- ;TODO: see if scalar is faster %macro PRED8x8L_DC 1 cglobal pred8x8l_dc_10_%1, 4,6,6 sub r0, r3 lea r4, [r0+r3*4] lea r5, [r3*3] mova m0, [r0+r3*2-16] punpckhwd m0, [r0+r3*1-16] mova m1, [r4+r3*0-16] punpckhwd m1, [r0+r5*1-16] punpckhdq m1, m0 mova m2, [r4+r3*2-16] punpckhwd m2, [r4+r3*1-16] mova m3, [r4+r3*4-16] punpckhwd m3, [r4+r5*1-16] punpckhdq m3, m2 punpckhqdq m3, m1 mova m0, [r0] shr r1d, 14 shr r2d, 13 neg r1 pslldq m1, m0, 2 psrldq m2, m0, 2 pinsrw m1, [r0+r1], 0 pinsrw m2, [r0+r2+14], 7 not r1 and r1, r3 pslldq m4, m3, 2 psrldq m5, m3, 2 pshuflw m4, m4, 11100101b pinsrw m5, [r0+r1-2], 7 PRED4x4_LOWPASS m3, m4, m5, m3 PRED4x4_LOWPASS m0, m2, m1, m0 paddw m0, m3 HADDW m0, m1 paddw m0, [pw_8] psrlw m0, 4 SPLATW m0, m0 mova [r0+r3*1], m0 mova [r0+r3*2], m0 mova [r0+r5*1], m0 mova [r0+r3*4], m0 mova [r4+r3*1], m0 mova [r4+r3*2], m0 mova [r4+r5*1], m0 mova [r4+r3*4], m0 RET %endmacro INIT_XMM PRED8x8L_DC sse2 %ifdef HAVE_AVX INIT_AVX PRED8x8L_DC avx %endif ;----------------------------------------------------------------------------- ; void pred8x8l_vertical(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_VERTICAL 1 cglobal pred8x8l_vertical_10_%1, 4,4,6 sub r0, r3 mova m0, [r0] shr r1d, 14 shr r2d, 13 neg r1 pslldq m1, m0, 2 psrldq m2, m0, 2 pinsrw m1, [r0+r1], 0 pinsrw m2, [r0+r2+14], 7 lea r1, [r3*3] lea r2, [r0+r3*4] PRED4x4_LOWPASS m0, m2, m1, m0 mova [r0+r3*1], m0 mova [r0+r3*2], m0 mova [r0+r1*1], m0 mova [r0+r3*4], m0 mova [r2+r3*1], m0 mova [r2+r3*2], m0 mova [r2+r1*1], m0 mova [r2+r3*4], m0 RET %endmacro INIT_XMM PRED8x8L_VERTICAL sse2 %ifdef HAVE_AVX INIT_AVX PRED8x8L_VERTICAL avx %endif ;----------------------------------------------------------------------------- ; void pred8x8l_horizontal(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_HORIZONTAL 1 cglobal pred8x8l_horizontal_10_%1, 4,4,5 mova m0, [r0-16] shr r1d, 14 dec r1 and r1, r3 sub r1, r3 punpckhwd m0, [r0+r1-16] mova m1, [r0+r3*2-16] punpckhwd m1, [r0+r3*1-16] lea r2, [r0+r3*4] lea r1, [r3*3] punpckhdq m1, m0 mova m2, [r2+r3*0-16] punpckhwd m2, [r0+r1-16] mova m3, [r2+r3*2-16] punpckhwd m3, [r2+r3*1-16] punpckhdq m3, m2 punpckhqdq m3, m1 PALIGNR m4, m3, [r2+r1-16], 14, m0 pslldq m0, m4, 2 pshuflw m0, m0, 11100101b PRED4x4_LOWPASS m4, m3, m0, m4 punpckhwd m3, m4, m4 punpcklwd m4, m4 pshufd m0, m3, 0xff pshufd m1, m3, 0xaa pshufd m2, m3, 0x55 pshufd m3, m3, 0x00 mova [r0+r3*0], m0 mova [r0+r3*1], m1 mova [r0+r3*2], m2 mova [r0+r1*1], m3 pshufd m0, m4, 0xff pshufd m1, m4, 0xaa pshufd m2, m4, 0x55 pshufd m3, m4, 0x00 mova [r2+r3*0], m0 mova [r2+r3*1], m1 mova [r2+r3*2], m2 mova [r2+r1*1], m3 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED8x8L_HORIZONTAL sse2 %define PALIGNR PALIGNR_SSSE3 PRED8x8L_HORIZONTAL ssse3 %ifdef HAVE_AVX INIT_AVX PRED8x8L_HORIZONTAL avx %endif ;----------------------------------------------------------------------------- ;void pred8x8l_down_left(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_DOWN_LEFT 1 cglobal pred8x8l_down_left_10_%1, 4,4,7 sub r0, r3 mova m3, [r0] shr r1d, 14 neg r1 shr r2d, 13 pslldq m1, m3, 2 psrldq m2, m3, 2 pinsrw m1, [r0+r1], 0 pinsrw m2, [r0+r2+14], 7 PRED4x4_LOWPASS m6, m2, m1, m3 jz .fix_tr ; flags from shr r2d mova m1, [r0+16] psrldq m5, m1, 2 PALIGNR m2, m1, m3, 14, m3 pshufhw m5, m5, 10100100b PRED4x4_LOWPASS m1, m2, m5, m1 .do_topright: lea r1, [r3*3] psrldq m5, m1, 14 lea r2, [r0+r3*4] PALIGNR m2, m1, m6, 2, m0 PALIGNR m3, m1, m6, 14, m0 PALIGNR m5, m1, 2, m0 pslldq m4, m6, 2 PRED4x4_LOWPASS m6, m4, m2, m6 PRED4x4_LOWPASS m1, m3, m5, m1 mova [r2+r3*4], m1 PALIGNR m1, m6, 14, m2 pslldq m6, 2 mova [r2+r1*1], m1 PALIGNR m1, m6, 14, m2 pslldq m6, 2 mova [r2+r3*2], m1 PALIGNR m1, m6, 14, m2 pslldq m6, 2 mova [r2+r3*1], m1 PALIGNR m1, m6, 14, m2 pslldq m6, 2 mova [r0+r3*4], m1 PALIGNR m1, m6, 14, m2 pslldq m6, 2 mova [r0+r1*1], m1 PALIGNR m1, m6, 14, m2 pslldq m6, 2 mova [r0+r3*2], m1 PALIGNR m1, m6, 14, m6 mova [r0+r3*1], m1 RET .fix_tr: punpckhwd m3, m3 pshufd m1, m3, 0xFF jmp .do_topright %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED8x8L_DOWN_LEFT sse2 %define PALIGNR PALIGNR_SSSE3 PRED8x8L_DOWN_LEFT ssse3 %ifdef HAVE_AVX INIT_AVX PRED8x8L_DOWN_LEFT avx %endif ;----------------------------------------------------------------------------- ;void pred8x8l_down_right(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_DOWN_RIGHT 1 ; standard forbids this when has_topleft is false ; no need to check cglobal pred8x8l_down_right_10_%1, 4,5,8 sub r0, r3 lea r4, [r0+r3*4] lea r1, [r3*3] mova m0, [r0+r3*1-16] punpckhwd m0, [r0+r3*0-16] mova m1, [r0+r1*1-16] punpckhwd m1, [r0+r3*2-16] punpckhdq m1, m0 mova m2, [r4+r3*1-16] punpckhwd m2, [r4+r3*0-16] mova m3, [r4+r1*1-16] punpckhwd m3, [r4+r3*2-16] punpckhdq m3, m2 punpckhqdq m3, m1 mova m0, [r4+r3*4-16] mova m1, [r0] PALIGNR m4, m3, m0, 14, m0 PALIGNR m1, m3, 2, m2 pslldq m0, m4, 2 pshuflw m0, m0, 11100101b PRED4x4_LOWPASS m6, m1, m4, m3 PRED4x4_LOWPASS m4, m3, m0, m4 mova m3, [r0] shr r2d, 13 pslldq m1, m3, 2 psrldq m2, m3, 2 pinsrw m1, [r0-2], 0 pinsrw m2, [r0+r2+14], 7 PRED4x4_LOWPASS m3, m2, m1, m3 PALIGNR m2, m3, m6, 2, m0 PALIGNR m5, m3, m6, 14, m0 psrldq m7, m3, 2 PRED4x4_LOWPASS m6, m4, m2, m6 PRED4x4_LOWPASS m3, m5, m7, m3 mova [r4+r3*4], m6 PALIGNR m3, m6, 14, m2 pslldq m6, 2 mova [r0+r3*1], m3 PALIGNR m3, m6, 14, m2 pslldq m6, 2 mova [r0+r3*2], m3 PALIGNR m3, m6, 14, m2 pslldq m6, 2 mova [r0+r1*1], m3 PALIGNR m3, m6, 14, m2 pslldq m6, 2 mova [r0+r3*4], m3 PALIGNR m3, m6, 14, m2 pslldq m6, 2 mova [r4+r3*1], m3 PALIGNR m3, m6, 14, m2 pslldq m6, 2 mova [r4+r3*2], m3 PALIGNR m3, m6, 14, m6 mova [r4+r1*1], m3 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED8x8L_DOWN_RIGHT sse2 %define PALIGNR PALIGNR_SSSE3 PRED8x8L_DOWN_RIGHT ssse3 %ifdef HAVE_AVX INIT_AVX PRED8x8L_DOWN_RIGHT avx %endif ;----------------------------------------------------------------------------- ; void pred8x8l_vertical_right(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_VERTICAL_RIGHT 1 ; likewise with 8x8l_down_right cglobal pred8x8l_vertical_right_10_%1, 4,5,7 sub r0, r3 lea r4, [r0+r3*4] lea r1, [r3*3] mova m0, [r0+r3*1-16] punpckhwd m0, [r0+r3*0-16] mova m1, [r0+r1*1-16] punpckhwd m1, [r0+r3*2-16] punpckhdq m1, m0 mova m2, [r4+r3*1-16] punpckhwd m2, [r4+r3*0-16] mova m3, [r4+r1*1-16] punpckhwd m3, [r4+r3*2-16] punpckhdq m3, m2 punpckhqdq m3, m1 mova m0, [r4+r3*4-16] mova m1, [r0] PALIGNR m4, m3, m0, 14, m0 PALIGNR m1, m3, 2, m2 PRED4x4_LOWPASS m3, m1, m4, m3 mova m2, [r0] shr r2d, 13 pslldq m1, m2, 2 psrldq m5, m2, 2 pinsrw m1, [r0-2], 0 pinsrw m5, [r0+r2+14], 7 PRED4x4_LOWPASS m2, m5, m1, m2 PALIGNR m6, m2, m3, 12, m1 PALIGNR m5, m2, m3, 14, m0 PRED4x4_LOWPASS m0, m6, m2, m5 pavgw m2, m5 mova [r0+r3*2], m0 mova [r0+r3*1], m2 pslldq m6, m3, 4 pslldq m1, m3, 2 PRED4x4_LOWPASS m1, m3, m6, m1 PALIGNR m2, m1, 14, m4 mova [r0+r1*1], m2 pslldq m1, 2 PALIGNR m0, m1, 14, m3 mova [r0+r3*4], m0 pslldq m1, 2 PALIGNR m2, m1, 14, m4 mova [r4+r3*1], m2 pslldq m1, 2 PALIGNR m0, m1, 14, m3 mova [r4+r3*2], m0 pslldq m1, 2 PALIGNR m2, m1, 14, m4 mova [r4+r1*1], m2 pslldq m1, 2 PALIGNR m0, m1, 14, m1 mova [r4+r3*4], m0 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED8x8L_VERTICAL_RIGHT sse2 %define PALIGNR PALIGNR_SSSE3 PRED8x8L_VERTICAL_RIGHT ssse3 %ifdef HAVE_AVX INIT_AVX PRED8x8L_VERTICAL_RIGHT avx %endif ;----------------------------------------------------------------------------- ; void pred8x8l_horizontal_up(pixel *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_HORIZONTAL_UP 1 cglobal pred8x8l_horizontal_up_10_%1, 4,4,6 mova m0, [r0+r3*0-16] punpckhwd m0, [r0+r3*1-16] shr r1d, 14 dec r1 and r1, r3 sub r1, r3 mova m4, [r0+r1*1-16] lea r1, [r3*3] lea r2, [r0+r3*4] mova m1, [r0+r3*2-16] punpckhwd m1, [r0+r1*1-16] punpckhdq m0, m1 mova m2, [r2+r3*0-16] punpckhwd m2, [r2+r3*1-16] mova m3, [r2+r3*2-16] punpckhwd m3, [r2+r1*1-16] punpckhdq m2, m3 punpckhqdq m0, m2 PALIGNR m1, m0, m4, 14, m4 psrldq m2, m0, 2 pshufhw m2, m2, 10100100b PRED4x4_LOWPASS m0, m1, m2, m0 psrldq m1, m0, 2 psrldq m2, m0, 4 pshufhw m1, m1, 10100100b pshufhw m2, m2, 01010100b pavgw m4, m0, m1 PRED4x4_LOWPASS m1, m2, m0, m1 punpckhwd m5, m4, m1 punpcklwd m4, m1 mova [r2+r3*0], m5 mova [r0+r3*0], m4 pshufd m0, m5, 11111001b pshufd m1, m5, 11111110b pshufd m2, m5, 11111111b mova [r2+r3*1], m0 mova [r2+r3*2], m1 mova [r2+r1*1], m2 PALIGNR m2, m5, m4, 4, m0 PALIGNR m3, m5, m4, 8, m1 PALIGNR m5, m5, m4, 12, m4 mova [r0+r3*1], m2 mova [r0+r3*2], m3 mova [r0+r1*1], m5 RET %endmacro INIT_XMM %define PALIGNR PALIGNR_MMX PRED8x8L_HORIZONTAL_UP sse2 %define PALIGNR PALIGNR_SSSE3 PRED8x8L_HORIZONTAL_UP ssse3 %ifdef HAVE_AVX INIT_AVX PRED8x8L_HORIZONTAL_UP avx %endif ;----------------------------------------------------------------------------- ; void pred16x16_vertical(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro MOV16 3-5 mova [%1+ 0], %2 mova [%1+mmsize], %3 %if mmsize==8 mova [%1+ 16], %4 mova [%1+ 24], %5 %endif %endmacro %macro PRED16x16_VERTICAL 1 cglobal pred16x16_vertical_10_%1, 2,3 sub r0, r1 mov r2d, 8 mova m0, [r0+ 0] mova m1, [r0+mmsize] %if mmsize==8 mova m2, [r0+16] mova m3, [r0+24] %endif .loop: MOV16 r0+r1*1, m0, m1, m2, m3 MOV16 r0+r1*2, m0, m1, m2, m3 lea r0, [r0+r1*2] dec r2d jg .loop REP_RET %endmacro INIT_MMX PRED16x16_VERTICAL mmxext INIT_XMM PRED16x16_VERTICAL sse2 ;----------------------------------------------------------------------------- ; void pred16x16_horizontal(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_HORIZONTAL 1 cglobal pred16x16_horizontal_10_%1, 2,3 mov r2d, 8 .vloop: movd m0, [r0+r1*0-4] movd m1, [r0+r1*1-4] SPLATW m0, m0, 1 SPLATW m1, m1, 1 MOV16 r0+r1*0, m0, m0, m0, m0 MOV16 r0+r1*1, m1, m1, m1, m1 lea r0, [r0+r1*2] dec r2d jg .vloop REP_RET %endmacro INIT_MMX PRED16x16_HORIZONTAL mmxext INIT_XMM PRED16x16_HORIZONTAL sse2 ;----------------------------------------------------------------------------- ; void pred16x16_dc(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_DC 1 cglobal pred16x16_dc_10_%1, 2,6 mov r5, r0 sub r0, r1 mova m0, [r0+0] paddw m0, [r0+mmsize] %if mmsize==8 paddw m0, [r0+16] paddw m0, [r0+24] %endif HADDW m0, m2 lea r0, [r0+r1-2] movzx r3d, word [r0] movzx r4d, word [r0+r1] %rep 7 lea r0, [r0+r1*2] movzx r2d, word [r0] add r3d, r2d movzx r2d, word [r0+r1] add r4d, r2d %endrep lea r3d, [r3+r4+16] movd m1, r3d paddw m0, m1 psrlw m0, 5 SPLATW m0, m0 mov r3d, 8 .loop: MOV16 r5+r1*0, m0, m0, m0, m0 MOV16 r5+r1*1, m0, m0, m0, m0 lea r5, [r5+r1*2] dec r3d jg .loop REP_RET %endmacro INIT_MMX PRED16x16_DC mmxext INIT_XMM PRED16x16_DC sse2 ;----------------------------------------------------------------------------- ; void pred16x16_top_dc(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_TOP_DC 1 cglobal pred16x16_top_dc_10_%1, 2,3 sub r0, r1 mova m0, [r0+0] paddw m0, [r0+mmsize] %if mmsize==8 paddw m0, [r0+16] paddw m0, [r0+24] %endif HADDW m0, m2 SPLATW m0, m0 paddw m0, [pw_8] psrlw m0, 4 mov r2d, 8 .loop: MOV16 r0+r1*1, m0, m0, m0, m0 MOV16 r0+r1*2, m0, m0, m0, m0 lea r0, [r0+r1*2] dec r2d jg .loop REP_RET %endmacro INIT_MMX PRED16x16_TOP_DC mmxext INIT_XMM PRED16x16_TOP_DC sse2 ;----------------------------------------------------------------------------- ; void pred16x16_left_dc(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_LEFT_DC 1 cglobal pred16x16_left_dc_10_%1, 2,6 mov r5, r0 sub r0, 2 movzx r3d, word [r0] movzx r4d, word [r0+r1] %rep 7 lea r0, [r0+r1*2] movzx r2d, word [r0] add r3d, r2d movzx r2d, word [r0+r1] add r4d, r2d %endrep lea r3d, [r3+r4+8] shr r3d, 4 movd m0, r3d SPLATW m0, m0 mov r3d, 8 .loop: MOV16 r5+r1*0, m0, m0, m0, m0 MOV16 r5+r1*1, m0, m0, m0, m0 lea r5, [r5+r1*2] dec r3d jg .loop REP_RET %endmacro INIT_MMX PRED16x16_LEFT_DC mmxext INIT_XMM PRED16x16_LEFT_DC sse2 ;----------------------------------------------------------------------------- ; void pred16x16_128_dc(pixel *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_128_DC 1 cglobal pred16x16_128_dc_10_%1, 2,3 mova m0, [pw_512] mov r2d, 8 .loop: MOV16 r0+r1*0, m0, m0, m0, m0 MOV16 r0+r1*1, m0, m0, m0, m0 lea r0, [r0+r1*2] dec r2d jg .loop REP_RET %endmacro INIT_MMX PRED16x16_128_DC mmxext INIT_XMM PRED16x16_128_DC sse2
SECTION .DATA happ: dq 0 num: dq 123 num2: dq 456 num3: dq 10 SECTION .TEXT GLOBAL _basic_encrypt GLOBAL _basic_decrypt GLOBAL _basic_encrypt_char GLOBAL _basic_decrypt_char GLOBAL _mid_encrypt GLOBAL _mid_decrypt GLOBAL hard_enc GLOBAL hard_dec _basic_encrypt: mov rax,rdi ;[rbp+16] mov rbx,10 div rbx ret