text
stringlengths
1
1.05M
SECTION code_clib SECTION code_fp_math48 PUBLIC _tgamma EXTERN cm48_sdccix_tgamma defc _tgamma = cm48_sdccix_tgamma
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 004D38 move.l D0, (A4)+ 004D3A move.l D0, (A4)+ 033950 move.w D0, ($a2,A6) 033954 move.b #$ff, ($a5,A6) 034002 move.w #$36, ($a2,A6) 034008 move.b #$1, ($80,A6) [enemy+A2] 034048 subq.w #1, ($a2,A6) 03404C bne $34076 [enemy+A2] 03404E move.w #$24, ($a2,A6) 034054 jsr $119c.l [enemy+A2] 03596A move.l A0, ($a0,A1) [enemy+10] 03596E move.w A1, ($a6,A0) [enemy+A2] 03598C move.l A0, ($a0,A2) [enemy+40, enemy+42] 035990 move.w ($a6,A0), ($76,A2) [enemy+A2] 035CA0 move.b (A0,D1.w), ($a2,A6) 035CA6 move.b #$0, ($a1,A6) [enemy+A2] 035E0E subq.b #1, ($a2,A6) 035E12 rts [enemy+A2] 035FA4 tst.b ($a2,A6) [enemy+B0, enemy+B2] 035FA8 beq $35fb2 [enemy+A2] 035FCC tst.b ($a2,A6) 035FD0 bne $36008 [enemy+A2] 035FF6 move.b #$0, ($a2,A6) [enemy+A1] 035FFC move.b #$0, ($ad,A6) 03627E tst.b ($a2,A6) 036282 beq $3628c [enemy+A2] 036286 subq.b #1, ($a2,A6) 03628A rts [enemy+A2] 038EFC move.l A6, ($a0,A0) 038F00 move.w A0, ($b0,A6) [enemy+A2] 038F1E move.l A6, ($a0,A0) [enemy+26] 038F22 move.w A0, ($b2,A6) [enemy+A2] 038F26 move.w #$b4, ($a2,A6) [enemy+B2] 038F2C addq.b #2, ($5,A6) [enemy+A2] 038F72 move.w #$b4, ($a2,A6) 038F78 addq.b #2, ($5,A6) [enemy+A2] 038F8E move.b #$1, ($a2,A3) [enemy+A6] 038F94 move.w #$3c, ($a2,A6) [enemy+A2] 038F9A addq.b #2, ($5,A6) [enemy+A2] 038FD2 move.w #$3c, ($a2,A6) 038FD8 addq.b #2, ($5,A6) [enemy+A2] 038FE2 subi.w #$1, ($a2,A6) 038FE8 bne $38ff0 [enemy+A2] 038FFC subi.w #$1, ($a2,A6) 039002 bne $3900a [enemy+A2] 03900A move.w ($a2,A6), D0 [enemy+ 5] 03900E andi.w #$1f, D0 [enemy+A2] 03B2A0 movea.l ($a0,A6), A0 03B2A4 cmpi.b #$4, ($4,A0) [enemy+A2] 03B2CE movea.l ($a0,A6), A1 03B2D2 move.w ($8,A1), ($8,A6) [enemy+A2] 03B322 movea.l ($a0,A6), A1 03B326 move.b ($24,A1), ($24,A6) [enemy+A2] 03B492 movea.l ($a0,A6), A1 03B496 tst.b ($5,A1) [enemy+A2] 03BCB2 move.w ($8,A6), ($a2,A6) [enemy+A0] 03BCB8 move.b #$0, ($7d,A6) [enemy+A2] 03DEDE move.b D0, ($a2,A6) 03DEE2 move.b D0, ($a3,A6) 03E4F6 move.b (A0,D1.w), ($a2,A6) 03E4FC move.b #$0, ($a3,A6) [enemy+A2] 03E7C8 tst.b ($a2,A6) [enemy+B0, enemy+B2] 03E7CC beq $3e7d6 [enemy+A2] 03E7D0 subq.b #1, ($a2,A6) 03E7D4 rts [enemy+A2] 03E7F0 tst.b ($a2,A6) 03E7F4 bne $3e826 [enemy+A2] 03E81A move.b #$0, ($a2,A6) [enemy+A3] 03E820 jmp $32b68.l 03E866 tst.b ($a2,A6) [enemy+B4, enemy+B6] 03E86A beq $3e874 [enemy+A2] 03E88E tst.b ($a2,A6) 03E892 bne $3e8c4 [enemy+A2] 03E8B8 move.b #$0, ($a2,A6) [enemy+A3] 03E8BE jmp $32b68.l 03E8F2 tst.b ($a2,A6) 03E8F6 beq $3e900 03E9C2 tst.b ($a2,A6) 03E9C6 beq $3e9d0 [enemy+A2] 03E9CA subq.b #1, ($a2,A6) 03E9CE rts [enemy+A2] 03EA22 move.b #$0, ($a2,A6) [enemy+A3] 03EA28 rts 0402C0 move.l A1, ($a0,A0) [enemy+40, enemy+42] 0402C4 move.b #$1, ($0,A2) [enemy+A2] 0402DE move.l A1, ($a0,A2) [enemy+40, enemy+42] 0402E2 rts [enemy+A2] 040386 move.b D0, ($a2,A6) 04038A move.b D0, ($7a,A6) 04044C tst.b ($a2,A6) 040450 bne $404ae [enemy+A2] 040460 move.b #$1, ($a2,A6) 040466 jsr $483c.l [enemy+A2] 04049E move.l A6, ($a0,A0) [enemy+10] 0404A2 subq.b #1, ($be,A6) [enemy+A2] 0404A8 move.b #$0, ($a2,A6) 0404AE rts 040FC4 move.l A6, ($a0,A0) [enemy+10] 040FC8 subq.b #1, ($be,A6) [enemy+A2] 041F82 move.l D0, ($a0,A6) 041F86 move.l (A0)+, ($a4,A6) [enemy+A0, enemy+A2] 041FD4 move.l ($a0,A6), D0 041FD8 add.l D0, ($8,A6) [enemy+A0, enemy+A2] 0423D0 move.l #$8000, ($a2,A6) 0423D8 moveq #$0, D0 [enemy+A2, enemy+A4] 042478 move.l ($a2,A6), D0 04247C add.l D0, ($c,A6) [enemy+A2, enemy+A4] 0424B2 move.l #$8000, ($a2,A6) 0424BA bra $424be [enemy+A2, enemy+A4] 04429C clr.w (A0)+ 04429E clr.w (A0)+ [enemy+A2] 0442D6 movea.w (A0,D0.w), A0 0442DA move.w A0, ($76,A6) [enemy+A2, enemy+A4, enemy+A6] 044432 move.w A0, (A1)+ 044434 lea ($33f4,A5), A0 [enemy+A2] 044468 tst.w ($a2,A6) 04446C bne $44476 [enemy+A2] 045E54 move.w D1, ($a2,A6) 045E58 move.w ($a2,A6), D0 [enemy+A2] 045E5C move.w ($26,PC,D0.w), D0 [enemy+A2] 045ED4 move.w ($a2,A6), D0 045ED8 move.w ($6,PC,D0.w), D0 [enemy+A2] 045EE6 clr.w ($a2,A6) 045EEA clr.b ($a5,A6) 045F36 move.w #$2, ($a2,A6) 045F3C move.b ($7,A6), D0 [enemy+A2] 0460B4 move.w #$4, ($a2,A6) 0460BA moveq #-$1, D1 [enemy+A2] 04DCDA move.l A6, ($a0,A0) [enemy+20] 04DCDE move.w #$2d0, ($8,A0) [enemy+A2] 04DEE4 movea.l ($a0,A6), A4 04DEE8 moveq #$0, D0 [enemy+A2] 05594A movea.l ($a0,A6), A1 05594E move.b #$1, ($51,A6) [enemy+A2] 0565A4 move.w #$64, ($a2,A6) 0565AA move.w #$10, ($a6,A6) [enemy+A2] 056962 move.w #$64, ($a2,A6) 056968 move.w #$10, ($a6,A6) [enemy+A2] 056E0A move.w #$0, ($a2,A6) [enemy+A6, enemy+A8] 056E10 moveq #$3, D0 056FCE tst.l ($a2,A6) [enemy+ C, enemy+ E] 056FD2 bne $56ffc [enemy+A2, enemy+A4] 056FEE move.w #$1, ($a2,A6) [enemy+AE, enemy+B0] 056FF4 moveq #$2, D0 [enemy+A2] 0571BE clr.b ($a2,A6) [enemy+25] 0571C2 jsr $483c.l [enemy+A2] 057228 tst.b ($a2,A6) 05722C beq $57236 [enemy+A2] 0572F0 movea.l ($a0,A6), A1 [enemy+ 4] 0572F4 cmpi.b #$4, ($4,A1) [enemy+A2] 057324 movea.l ($a0,A6), A1 057328 move.b ($24,A1), ($24,A6) [enemy+A2] 0573B2 movea.l ($a0,A6), A1 [item+10] 0573B6 tst.b ($26,A6) [enemy+A2] 0577B4 cmp.b ($a2,A6), D0 [etc+ 5] 0577B8 beq $577ca [enemy+A2] 0577C6 move.b D0, ($a2,A6) [enemy+ 5] 0577CA rts [enemy+A2] 057B5C cmp.b ($a2,A6), D0 [etc+ 5] 057B60 beq $57b6c [enemy+A2] 057B68 move.b D0, ($a2,A6) [enemy+ 6] 057B6C rts [enemy+A2] 057D66 cmp.b ($a2,A6), D0 [etc+ 5] 057D6A beq $57d7c [enemy+A2] 057D78 move.b D0, ($a2,A6) [enemy+ 5] 057D7C rts [enemy+A2] 057EA2 movea.l ($a0,A6), A3 [enemy+ 4] 057EA6 tst.b ($ac,A3) [enemy+A2] 05813C movea.l ($a0,A6), A1 058140 cmpi.b #$4, ($4,A1) [enemy+A2] 058544 move.b D0, ($a2,A6) 058548 move.b D0, ($bf,A6) 058592 move.l A6, ($a0,A0) [enemy+40, enemy+42] 058596 move.w A0, ($a6,A6) [enemy+A2] 0585D8 move.l A6, ($a0,A0) [enemy+40, enemy+42] 0585DC move.w A0, ($a8,A6) [enemy+A2] 058A62 move.b D2, ($a2,A6) 058A66 move.b #$0, ($ad,A6) [enemy+A2] 058A7E tst.b ($a2,A6) 058A82 bne $58ab6 [enemy+A2] 058ACE tst.b ($a2,A6) 058AD2 bne $58b0a 058E5C tst.b ($a2,A6) [enemy+C4, enemy+C6] 058E60 beq $58e6a [enemy+A2] 058E64 subq.b #1, ($a2,A6) 058E68 rts [enemy+A2] 058EB2 tst.b ($a2,A6) 058EB6 bne $58ee0 [enemy+A2] 058F6A tst.b ($a2,A6) [enemy+C4, enemy+C6] 058F6E beq $58f78 [enemy+A2] 058F72 subq.b #1, ($a2,A6) 058F76 rts [enemy+A2] 058FD8 tst.b ($a2,A6) 058FDC bne $58ffa [enemy+A2] 058FEC move.b #$0, ($a2,A6) [enemy+AD] 058FF2 moveq #$0, D0 0595EA move.l A6, ($a0,A0) [enemy+10] 0595EE move.l #$6f8a6, ($40,A0) [enemy+A2] 05A4FA movea.l ($a0,A6), A0 05A4FE tst.b ($4,A0) [enemy+A2] 05A50E movea.l ($a0,A6), A1 05A512 cmpi.b #$4, ($4,A1) [enemy+A2] 05A544 movea.l ($a0,A6), A1 05A548 tst.b ($b2,A6) [enemy+A2] 05A5E4 movea.l ($a0,A6), A1 05A5E8 move.b ($24,A1), ($24,A6) [enemy+A2] 05AB26 move.b D0, ($a2,A6) 05AB2A move.b D0, ($7a,A6) 05AD70 move.l A6, ($a0,A0) [enemy+10] 05AD74 subq.b #1, ($be,A6) [enemy+A2] 05B31C move.l A0, ($a2,A6) 05B320 clr.w ($a6,A6) [enemy+A2, enemy+A4] 05B32E movea.l ($a2,A6), A0 05B332 moveq #$0, D0 [enemy+A2, enemy+A4] 05B3DC addq.l #1, ($a2,A6) 05B3E0 clr.b ($a6,A6) [enemy+A2, enemy+A4] 05B466 addq.l #1, ($a2,A6) 05B46A clr.b ($a6,A6) [enemy+A2, enemy+A4] 05B4A6 addq.l #1, ($a2,A6) 05B4AA clr.b ($a6,A6) [enemy+A2, enemy+A4] 05B4DC move.l A0, ($a2,A6) 05B4E0 clr.w ($a6,A6) [enemy+A2, enemy+A4] 05B4EE movea.l ($a2,A6), A0 05B4F2 moveq #$0, D0 [enemy+A2, enemy+A4] 05C444 clr.w ($a2,A6) 05C448 addq.b #2, ($5,A6) [enemy+A2] 05C5E4 addi.w #$12, ($a2,A6) 05C5EA move.w ($a2,A6), D0 [enemy+A2] 05EE36 move.b #$1, ($a2,A6) [enemy+7D] 05EE3C move.b #$10, ($25,A6) [enemy+A2] 05EFEC clr.b ($a2,A6) [enemy+ 5] 05EFF0 clr.b ($25,A6) [enemy+A2] 05F1E4 move.w #$4b0, ($a2,A6) [enemy+A0] 05F1EA move.b #$2, D0 [enemy+A2] 05F22A subq.w #1, ($a2,A6) 05F22E move.b ($6,A6), D0 [enemy+A2] 05FF4E move.l #$7500, ($a0,A6) 05FF56 jsr $3140c.l [enemy+A0, enemy+A2] 05FFD2 move.l ($a0,A6), D0 05FFD6 sub.l D0, ($8,A6) [enemy+A0, enemy+A2] 06A2E2 move.w #$258, ($a2,A6) 06A2E8 cmpi.w #$2, ($26,A6) [enemy+A2] 06A318 move.w #$258, ($a2,A6) 06A31E cmpi.w #$3, ($26,A6) [enemy+A2] 06A34E move.w #$258, ($a2,A6) 06A354 cmpi.w #$4, ($26,A6) [enemy+A2] 084746 move.w (A3,D0.w), ($a2,A6) 08474C add.w D0, D0 [enemy+A2, etc+A2] 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, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, 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, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, 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, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, 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, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, 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
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0xfd6d, %rsi lea addresses_normal_ht+0x10f6d, %rdi nop nop nop nop and $52899, %r11 mov $43, %rcx rep movsq nop sub $22078, %r15 lea addresses_normal_ht+0xc56d, %rsi lea addresses_WT_ht+0x2d65, %rdi clflush (%rsi) nop nop nop nop dec %rbx mov $102, %rcx rep movsl nop nop nop nop nop inc %rsi lea addresses_A_ht+0x1d96d, %r15 nop sub %rsi, %rsi movl $0x61626364, (%r15) xor $56844, %r15 lea addresses_WT_ht+0x1ad2d, %rbx nop nop nop add $19059, %rbp mov (%rbx), %r11 add $53360, %r15 lea addresses_WT_ht+0xb96d, %rbp add %rdi, %rdi mov $0x6162636465666768, %r11 movq %r11, (%rbp) sub $33415, %r11 lea addresses_WC_ht+0x436d, %rsi lea addresses_normal_ht+0xc16d, %rdi nop nop nop add $18619, %r11 mov $124, %rcx rep movsq nop nop nop cmp $25429, %r15 lea addresses_A_ht+0x8822, %rsi lea addresses_UC_ht+0x15b6d, %rdi nop and %rdx, %rdx mov $107, %rcx rep movsb nop nop nop nop inc %rdx lea addresses_A_ht+0x1976d, %rsi lea addresses_normal_ht+0x1756d, %rdi nop nop nop add $42190, %rdx mov $65, %rcx rep movsq nop add %rbp, %rbp lea addresses_A_ht+0x11d79, %rsi lea addresses_WC_ht+0x1142d, %rdi nop nop nop cmp %r15, %r15 mov $126, %rcx rep movsw nop nop nop nop xor $64633, %rdx lea addresses_WT_ht+0x1a56d, %rdx nop nop nop cmp %rbx, %rbx mov $0x6162636465666768, %r11 movq %r11, %xmm1 vmovups %ymm1, (%rdx) nop nop xor %r15, %r15 lea addresses_WC_ht+0xd6d, %rsi nop nop nop nop nop cmp %rbp, %rbp mov $0x6162636465666768, %rbx movq %rbx, %xmm1 movups %xmm1, (%rsi) nop nop nop nop cmp $25957, %rbp lea addresses_WT_ht+0x1d9ed, %r11 nop xor $51027, %r15 mov $0x6162636465666768, %rdx movq %rdx, %xmm5 vmovups %ymm5, (%r11) nop nop nop nop nop dec %rbp lea addresses_WC_ht+0xe76d, %rbp nop nop nop nop nop sub %rdx, %rdx mov $0x6162636465666768, %r15 movq %r15, %xmm5 movups %xmm5, (%rbp) nop nop xor %rdx, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r15 push %r9 push %rcx push %rdx // Faulty Load lea addresses_normal+0x1ed6d, %rcx nop nop nop sub $1552, %r10 vmovups (%rcx), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $0, %xmm2, %rdx lea oracles, %r13 and $0xff, %rdx shlq $12, %rdx mov (%r13,%rdx,1), %rdx pop %rdx pop %rcx pop %r9 pop %r15 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}, 'dst': {'same': True, 'congruent': 2, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 6}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 10}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_normal_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_UC_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_normal_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 11}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
/* Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke 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 HOLDER 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. */ #include <QWidget> #include <QPainter> #include <QMouseEvent> #include <QMenu> #include <QAction> #include <QInputDialog> #include "rtabmap/gui/EditMapArea.h" #include <rtabmap/utilite/ULogger.h> namespace rtabmap { EditMapArea::EditMapArea(QWidget *parent) : QWidget(parent) { setAttribute(Qt::WA_StaticContents); modified_ = false; scribbling_ = false; myPenWidth_ = 3; menu_ = new QMenu(tr(""), this); setPenWidth_ = menu_->addAction(tr("Set Pen Width...")); addObstacle_ = menu_->addAction(tr("Add Obstacle")); addObstacle_->setCheckable(true); addObstacle_->setChecked(true); clearObstacle_ = menu_->addAction(tr("Clear Obstacle")); clearObstacle_->setCheckable(true); clearObstacle_->setChecked(false); setUnknown_ = menu_->addAction(tr("Set Unknown")); setUnknown_->setCheckable(true); setUnknown_->setChecked(false); QActionGroup * group = new QActionGroup(this); group->addAction(addObstacle_); group->addAction(clearObstacle_); group->addAction(setUnknown_); resetChanges_ = menu_->addAction(tr("Reset Changes")); } void EditMapArea::setMap(const cv::Mat &map) { UASSERT(!map.empty()); UASSERT(map.type() == CV_8UC1); originalMap_ = map; map_ = uCvMat2QImage(map, true).convertToFormat(QImage::Format_RGB32); modified_ = false; update(); } cv::Mat EditMapArea::getModifiedMap() const { cv::Mat modifiedMap = originalMap_.clone(); if(modified_) { UASSERT(map_.width() == modifiedMap.cols && map_.height() == modifiedMap.rows); UASSERT(modifiedMap.type() == CV_8UC1); for(int j=0; j<map_.height(); ++j) { for(int i=0; i<map_.width(); ++i) { modifiedMap.at<unsigned char>(j,i) = qRed(map_.pixel(i, j)); } } } return modifiedMap; } void EditMapArea::setPenWidth(int newWidth) { myPenWidth_ = newWidth; } void EditMapArea::resetChanges() { map_ = uCvMat2QImage(originalMap_).convertToFormat(QImage::Format_RGB32); modified_ = false; update(); } void EditMapArea::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { float scale, offsetX, offsetY; computeScaleOffsets(rect(), scale, offsetX, offsetY); lastPoint_.setX((event->pos().x()-offsetX)/scale); lastPoint_.setY((event->pos().y()-offsetY)/scale); scribbling_ = true; } } void EditMapArea::mouseMoveEvent(QMouseEvent *event) { if ((event->buttons() & Qt::LeftButton) && scribbling_) { float scale, offsetX, offsetY; computeScaleOffsets(rect(), scale, offsetX, offsetY); QPoint to; to.setX((event->pos().x()-offsetX)/scale); to.setY((event->pos().y()-offsetY)/scale); drawLineTo(to); } } void EditMapArea::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && scribbling_) { float scale, offsetX, offsetY; computeScaleOffsets(rect(), scale, offsetX, offsetY); QPoint to; to.setX((event->pos().x()-offsetX)/scale); to.setY((event->pos().y()-offsetY)/scale); drawLineTo(to); scribbling_ = false; } } void EditMapArea::computeScaleOffsets(const QRect & targetRect, float & scale, float & offsetX, float & offsetY) const { scale = 1.0f; offsetX = 0.0f; offsetY = 0.0f; if(!map_.isNull()) { float w = map_.width(); float h = map_.height(); float widthRatio = float(targetRect.width()) / w; float heightRatio = float(targetRect.height()) / h; //printf("w=%f, h=%f, wR=%f, hR=%f, sW=%d, sH=%d\n", w, h, widthRatio, heightRatio, this->rect().width(), this->rect().height()); if(widthRatio < heightRatio) { scale = widthRatio; } else { scale = heightRatio; } //printf("ratio=%f\n",ratio); w *= scale; h *= scale; if(w < targetRect.width()) { offsetX = (targetRect.width() - w)/2.0f; } if(h < targetRect.height()) { offsetY = (targetRect.height() - h)/2.0f; } //printf("offsetX=%f, offsetY=%f\n",offsetX, offsetY); } } void EditMapArea::paintEvent(QPaintEvent *event) { //Scale float ratio, offsetX, offsetY; this->computeScaleOffsets(event->rect(), ratio, offsetX, offsetY); QPainter painter(this); painter.translate(offsetX, offsetY); painter.scale(ratio, ratio); painter.drawImage(QPoint(0,0), map_); } void EditMapArea::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); } void EditMapArea::contextMenuEvent(QContextMenuEvent * e) { QAction * action = menu_->exec(e->globalPos()); if(action == setPenWidth_) { bool ok; int width = QInputDialog::getInt(this, tr("Set Pen Width"), tr("Width:"), penWidth(), 1, 99, 1, &ok); if(ok) { myPenWidth_ = width; } } else if(action == resetChanges_) { this->resetChanges(); } } void EditMapArea::drawLineTo(const QPoint &endPoint) { QPainter painter(&map_); QColor color; //base on util3d::convertMap2Image8U(); if(addObstacle_->isChecked()) { color.setRgb(0,0,0); } else if(clearObstacle_->isChecked()) { color.setRgb(178,178,178); } else //unknown { color.setRgb(89,89,89); } painter.setPen(QPen(color, myPenWidth_, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter.drawLine(lastPoint_, endPoint); modified_ = true; update(); lastPoint_ = endPoint; } }
#include "Game/Entities/ParticleEmitter.hpp" #include "Util/Random.hpp" #include "Util/Math.hpp" ParticleEmitter::ParticleEmitter(sf::Vector2f pos, sf::Texture* particleTexture, float launchVelocity, float velocityRandomRange, float lifetime, float lifetimeRandomRange, float gravity, bool fadeOut) : GameObject(pos), particleTexture(particleTexture), launchVelocity(launchVelocity), velocityRandomRange(velocityRandomRange), lifetime(lifetime), lifetimeRandomRange(lifetimeRandomRange), gravity(gravity), fadeOut(fadeOut) { } void ParticleEmitter::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform.translate(GetPosition()); for (const auto& particle : particles) target.draw(particle, states); } void ParticleEmitter::Update(float delta) { for (auto it = particles.begin(); it != particles.end(); ) { Particle& particle = (*it); particle.curLifetime += delta; if (particle.curLifetime > particle.lifetime) { it = particles.erase(it); } else { particle.velocity.y += gravity * delta; particle.setPosition(particle.getPosition() + particle.velocity * delta); particle.SetAlpha(255.0f - particle.curLifetime * particle.alphaDelta); it++; } } if (particles.empty()) Kill(); } void ParticleEmitter::Emit(size_t count) { for (size_t i = 0U; i < count; i++) { Particle particle; float launchVel = launchVelocity + Random::Float(velocityRandomRange) - velocityRandomRange / 2.0f; float angle = Random::Float((float)PIELLO_DARKNESS_MY_OLD_FRIEND * 2.0f); particle.velocity = sf::Vector2f(cosf(angle) * launchVel, sinf(angle) * launchVel); particle.lifetime = Math::max(0.0f, lifetime + Random::Float(lifetimeRandomRange) - lifetimeRandomRange / 2.0f); particle.curLifetime = 0.0f; if (fadeOut) particle.alphaDelta = 255.0f / particle.lifetime; else particle.alphaDelta = 0.0f; particle.SetTexture(particleTexture); particles.push_back(particle); } }
; A131673: Size of the largest BDD of symmetric Boolean functions of n variables when the sink nodes are counted. ; 1,3,5,7,10,14,19,25,31,38,46,55,65,76,88,101,115,129,144,160,177,195,214,234,255,277,300,324,349,375,402,430,459,489,519,550,582,615,649,684,720,757,795,834,874,915,957,1000,1044,1089,1135,1182,1230,1279,1329,1380,1432 mov $3,$0 add $3,1 mov $5,$0 lpb $3,1 mov $0,$5 sub $3,1 sub $0,$3 add $0,1 mov $2,$0 mov $4,2 lpb $2,1 mul $4,2 lpb $4,1 mov $4,$2 sub $2,2 lpe sub $0,1 sub $2,1 lpe add $1,$0 lpe
; FREE function for far memory model ; 31/3/00 GWL ; ; $Id: free_far.asm,v 1.6 2017-01-02 20:37:10 aralbrec Exp $ ; SECTION code_clib PUBLIC free_far PUBLIC _free_far PUBLIC free_loop EXTERN malloc_table,pool_table include "memory.def" ; void free(far *p); .free_far ._free_far pop hl pop bc pop de ; EBC=far pointer push de push bc push hl ld a,c cp 2 ret nz ; low byte=2 always dec e ; because 0=local pointer ld c,b ld b,e ; BC=page number ld hl,malloc_table add hl,bc add hl,bc ; HL=address in malloc_table ld a,($04d1) ex af,af' ; save seg 1 binding ld a,(hl) inc hl ld d,(hl) dec hl ld ($04d1),a out ($d1),a ld e,0 ld a,(de) ld c,a inc de ld a,(de) ld b,a ; BC=#pages to deallocate ex af,af' ld ($04d1),a out ($d1),a ; rebind segment 1 .free_loop ld a,(hl) and a jr z,notallocated ld e,a ld d,0 ; DE=bank ld (hl),d inc hl ld ix,pool_table-32 add ix,de ld a,(ix+0) ; A=compressed pool handle add a,a rl d ; D was 0 previously add a,a rl d add a,a rl d add a,a rl d ld ixh,d ld ixl,a ; IX=pool handle ld a,e ; A=bank ld d,(hl) ld e,0 ; DE=address ld (hl),e inc hl push bc ld bc,256 ex de,hl call_oz(os_mfr) ex de,hl pop bc .notallocated dec bc ld a,b or c jr nz,free_loop ret
XLIB pixeladdress XREF base_graphics ; ; $Id: pixladdr.asm,v 1.3 2001/04/18 13:21:38 stefano Exp $ ; ; ****************************************************************** ; ; Get absolute pixel address in map of virtual (x,y) coordinate. ; ; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995 ; ; in: hl = (x,y) coordinate of pixel (h,l) ; ; out: de = address of pixel byte ; a = bit number of byte where pixel is to be placed ; fz = 1 if bit number is 0 of pixel position ; ; registers changed after return: ; ......hl/ixiy same ; afbcde../.... different ; .pixeladdress ld b,l srl b srl b srl b ; linedist = y div 8 * 256 ld a,h and @11111000 ; rowdist = x div 8 * 8 ld c,a ; bc = linedist + rowdist ld a,l and @00000111 ; coldist = y mod 8 ld de,(base_graphics) ; pointer to base of graphics area ld e,a ; coldist = graphicsarea + coldist ld a,h ex de,hl add hl,bc ; bytepos = linedist + rowdist + coldist ex de,hl and @00000111 ; a = x mod 8 xor @00000111 ; a = 7 - a ret ENDIF
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/elasticloadbalancing/model/DeleteLoadBalancerPolicyResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::ElasticLoadBalancing::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; DeleteLoadBalancerPolicyResult::DeleteLoadBalancerPolicyResult() { } DeleteLoadBalancerPolicyResult::DeleteLoadBalancerPolicyResult(const AmazonWebServiceResult<XmlDocument>& result) { *this = result; } DeleteLoadBalancerPolicyResult& DeleteLoadBalancerPolicyResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (rootNode.GetName() != "DeleteLoadBalancerPolicyResult") { resultNode = rootNode.FirstChild("DeleteLoadBalancerPolicyResult"); } if(!resultNode.IsNull()) { } XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; AWS_LOGSTREAM_DEBUG("Aws::ElasticLoadBalancing::Model::DeleteLoadBalancerPolicyResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); return *this; }
// This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // Simple test for a fuzzer. // The fuzzer must find a string based on dictionary words: // "Elvis" // "Presley" #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <iostream> #include <ostream> static volatile int Zero = 0; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { const char *Expected = "ElvisPresley"; if (Size < strlen(Expected)) return 0; size_t Match = 0; for (size_t i = 0; Expected[i]; i++) if (Expected[i] + Zero == Data[i]) Match++; if (Match == strlen(Expected)) { std::cout << "BINGO; Found the target, exiting\n" << std::flush; exit(1); } return 0; }
; A098660: E.g.f. BesselI(0,2*sqrt(2)*x) + BesselI(1,2*sqrt(2)*x)/sqrt(2). ; 1,1,4,6,24,40,160,280,1120,2016,8064,14784,59136,109824,439296,823680,3294720,6223360,24893440,47297536,189190144,361181184,1444724736,2769055744,11076222976,21300428800,85201715200,164317593600,657270374400,1270722723840,5082890895360,9848101109760,39392404439040,76467608616960,305870434467840,594748067020800,2378992268083200,4632774416793600,18531097667174400,36135640450990080,144542561803960320,282202144474398720,1128808577897594880,2206307674981662720,8825230699926650880 mov $1,$0 div $1,2 bin $0,$1 mov $2,2 pow $2,$1 mul $0,$2
; $Id: bit_close_ei.asm,v 1.3 2015/01/19 01:32:44 pauloscustodio Exp $ ; ; Enterprise 64/128 1 bit sound functions ; ; (Close sound) and restore interrupts ; ; Stefano Bodrato - 2011 ; PUBLIC bit_close_ei EXTERN bit_irqstatus .bit_close_ei push hl ld hl,(bit_irqstatus) ex (sp),hl pop af ret po ei ret
; Evolution types EV_LEVEL EQU 1 EV_ITEM EQU 2 EV_TRADE EQU 3 EV_HAPPY EQU 4
; A259319: a(n) = 2*A002309(n). ; 2,164,1414,6216,19338,48620,105742,206992,374034,634676,1023638,1583320,2364570,3427452,4842014,6689056,9060898,12062148,15810470,20437352,26088874,32926476,41127726,50887088,62416690,75947092,91728054,110029304,131141306,155376028,183067710,214573632,250274882,290577124,335911366,386734728,443531210,506812460,577118542,655018704,741112146,836028788,940430038,1055009560,1180494042,1317643964,1467254366,1630155616,1807214178,1999333380,2207454182,2432555944,2675657194,2937816396,3220132718,3523746800,3849841522,4199642772,4574420214,4975488056,5404205818,5861979100,6350260350,6870549632,7424395394,8013395236,8639196678,9303497928,10008048650,10754650732,11545159054,12381482256,13265583506,14199481268,15185250070,16225021272,17320983834,18475385084,19690531486,20968789408,22312585890,23724409412,25206810662,26762403304,28393864746,30103936908,31895426990,33771208240,35734220722,37787472084,39934038326,42177064568,44519765818,46965427740,49517407422,52179134144,54954110146,57845911396,60858188358,63994666760,67259148362,70655511724,74187712974,77859786576,81675846098,85640084980,89756777302,94030278552,98465026394,103065541436,107836427998,112782374880,117908156130,123218631812,128718748774,134413541416,140308132458,146407733708,152717646830,159243264112,165990069234,172963638036,180169639286,187613835448,195302083450,203240335452,211434639614,219891140864,228616081666,237615802788,246896744070,256465445192,266328546442,276492789484,286965018126,297752179088,308861322770,320299604020,332074282902,344192725464,356662404506,369490900348,382685901598,396255205920,410206720802,424548464324,439288565926,454435267176,469996922538,485982000140,502399082542,519256867504,536564168754,554329916756,572563159478,591273063160,610468913082,630160114332,650356192574,671066794816,692301690178,714070770660,736384051910,759251673992,782683902154,806691127596,831283868238,856472769488,882268605010,908682277492,935724819414,963407393816,991741295066,1020737949628,1050408916830,1080765889632,1111820695394,1143585296644,1176071791846,1209292416168,1243259542250,1277985680972,1313483482222,1349765735664,1386845371506,1424735461268,1463449218550,1502999999800,1543401305082,1584666778844,1626810210686,1669845536128,1713786837378,1758648344100,1804444434182,1851189634504,1898898621706,1947586222956,1997267416718,2047957333520,2099671256722,2152424623284,2206233024534,2261112206936,2317078072858,2374146681340,2432334248862,2491657150112,2552131918754,2613775248196,2676603992358,2740635166440,2805885947690,2872373676172,2940115855534,3009130153776,3079434404018,3151046605268,3223984923190,3298267690872,3373913409594,3450940749596,3529368550846,3609215823808,3690501750210,3773245683812,3857467151174,3943185852424,4030421662026,4119194629548,4209524980430,4301433116752,4394939618002,4490065241844,4586830924886,4685257783448,4785367114330,4887180395580,4990719287262,5096005632224,5203061456866,5311908971908,5422570573158,5535068842280,5649426547562,5765666644684,5883812277486,6003886778736,6125913670898,6249916666900 lpb $0,1 mov $2,$0 add $2,$0 sub $0,1 add $2,1 pow $2,4 add $1,$2 lpe mul $1,2 add $1,2
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/execution/executor.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/common.hpp" #include "duckdb/common/mutex.hpp" #include "duckdb/parallel/pipeline.hpp" #include "duckdb/common/unordered_map.hpp" #include <queue> namespace duckdb { class ClientContext; class DataChunk; class PhysicalOperator; class PhysicalOperatorState; class ThreadContext; class Task; struct ProducerToken; class Executor { friend class Pipeline; friend class PipelineTask; public: Executor(ClientContext &context); ~Executor(); ClientContext &context; public: void Initialize(unique_ptr<PhysicalOperator> physical_plan); void BuildPipelines(PhysicalOperator *op, Pipeline *parent); void Reset(); vector<LogicalType> GetTypes(); unique_ptr<DataChunk> FetchChunk(); //! Push a new error void PushError(std::string exception); //! Flush a thread context into the client context void Flush(ThreadContext &context); private: unique_ptr<PhysicalOperator> physical_plan; unique_ptr<PhysicalOperatorState> physical_state; mutex executor_lock; //! The pipelines of the current query vector<unique_ptr<Pipeline>> pipelines; //! The producer of this query unique_ptr<ProducerToken> producer; //! Exceptions that occurred during the execution of the current query vector<string> exceptions; //! The amount of completed pipelines of the query std::atomic<idx_t> completed_pipelines; //! The total amount of pipelines in the query idx_t total_pipelines; unordered_map<ChunkCollection *, Pipeline *> delim_join_dependencies; }; } // namespace duckdb
; A051578: a(n) = (2*n+4)!!/4!!, related to A000165 (even double factorials). ; 1,6,48,480,5760,80640,1290240,23224320,464486400,10218700800,245248819200,6376469299200,178541140377600,5356234211328000,171399494762496000,5827582821924864000,209792981589295104000,7972133300393213952000,318885332015728558080000,13393183944660599439360000,589300093565066375331840000,27107804303993053265264640000,1301174606591666556732702720000,65058730329583327836635136000000,3383053977138333047505027072000000,182684914765469984565271461888000000,10230355226866319135655201865728000000 add $0,2 mov $1,2 lpb $0 sub $0,1 add $2,2 mul $1,$2 lpe div $1,16 mov $0,$1
topirq_install SUBROUTINE lda topirq_rasterline+1 ora #$02 sta $ff0a lda topirq_rasterline sta $ff0b lda #<topirq_stub sta $fffe lda #>topirq_stub sta $ffff rts topirq_stub SUBROUTINE sta .exit+1 stx .exit+3 sty .exit+5 jsr topirq_handler inc $ff09 .exit lda #$00 ldx #$00 ldy #$00 rti topirq_handler SUBROUTINE jsr kp_output lda topirq_plugin+1 beq .skipplugin lda topirq_plugin sta .pluginaddr lda topirq_plugin+1 sta .pluginaddr+1 .pluginaddr = .+1 jsr $1234 .skipplugin jsr lowirq_install rts lowirq_install SUBROUTINE lda lowirq_rasterline+1 ora #$02 sta $ff0a lda lowirq_rasterline sta $ff0b lda #<lowirq_stub sta $fffe lda #>lowirq_stub sta $ffff rts lowirq_stub SUBROUTINE sta .exit+1 stx .exit+3 sty .exit+5 jsr lowirq_handler inc $ff09 .exit lda #$00 ldx #$00 ldy #$00 rti lowirq_handler SUBROUTINE inc framecounter bne .0 inc framecounter+1 .0 jsr kp_output jsr kp_tick lda lowirq_plugin+1 beq .skipplugin lda lowirq_plugin sta .pluginaddr lda lowirq_plugin+1 sta .pluginaddr+1 .pluginaddr = .+1 jsr $1234 .skipplugin jsr topirq_install rts
; A242426: floor(n! / n^3). ; 1,0,0,0,0,3,14,78,497,3628,29990,277200,2834328,31770514,387459072,5108103000,72397196844,1097800704000,17735107218083,304112751022080,5516784599040000 mov $1,$0 add $0,1 fac $1 div $1,$0 div $1,$0 mov $0,6 lpb $0,1 mov $0,3 mul $1,3 lpe div $1,3
; A047329: Numbers that are congruent to {1, 3, 5, 6} mod 7. ; 1,3,5,6,8,10,12,13,15,17,19,20,22,24,26,27,29,31,33,34,36,38,40,41,43,45,47,48,50,52,54,55,57,59,61,62,64,66,68,69,71,73,75,76,78,80,82,83,85,87,89,90,92,94,96,97,99,101,103,104,106,108,110,111 mul $0,7 add $0,6 div $0,4
/* Copyright (C) 2015-present The DotCpp Authors. This file is part of .C++, a native C++ implementation of popular .NET class library APIs developed to facilitate code reuse between C# and C++. http://github.com/dotcpp/dotcpp (source) http://dotcpp.org (documentation) 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. */ #pragma once #include <dot/declare.hpp> #include <dot/system/ptr.hpp> namespace dot { class object; class string_impl; class string; class type_impl; using type = ptr<type_impl>; /// All classes with reference semantics should derive from this type. /// It works with ptr to provide an emulation of reference semantics in C++. class DOT_CLASS object_impl : public reference_counter { template<typename T> friend class ptr; friend class object; public: // METHODS /// Determines whether the specified object is equal to the current object. /// /// Default implementation in object compares pointers. Derived classes /// can override this method to compare by value. virtual bool equals(object obj); /// Serves as the default hash function. /// /// Default implementation in object uses hash based on the pointer. /// Derived classes can override this method to provide value based hash. /// /// Methods Equals() and hash_code() must always be overriden together /// to avoid the situation when objects are equal but hash is not. virtual size_t hash_code(); /// Gets the type of the current instance. virtual type get_type(); /// Gets the type of the class. static type typeof(); /// string that represents the current object. /// /// Default implementation in object returns full name /// of the class by calling get_type().FullName. Derived types /// can override this method to provide custom conversion /// to string. virtual string to_string(); }; }
// 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.) // // This program only needs to handle arguments that satisfy // R0 >= 0, R1 >= 0, and R0*R1 < 32768. // Put your code here. // n = R0 // m = R1 // mult = 0 // LOOP: // if m == 0 goto STOP // m -= 1 // mult +=n // goto LOOP // STOP: // R2 = mult @R0 D=M @n M=D // n = R0 @R1 D=M @m M=D // m = R1 @mult M=0 // mult = 0 (LOOP) @m D=M @STOP D;JEQ // if m == 0 goto STOP D=D-1 // m -1 @m M=D // m = m -1 @mult D=M @n D=D+M @mult M=D // mult = mult + n @LOOP 0;JMP (STOP) @mult D=M @R2 M=D // RAM[2] = mult (END) @END 0;JMP
lda {m1}+1 cmp #$80 ror {m1}+1 ror {m1}
; A005053: Expand (1-2*x)/(1-5*x). ; 1,3,15,75,375,1875,9375,46875,234375,1171875,5859375,29296875,146484375,732421875,3662109375,18310546875,91552734375,457763671875,2288818359375,11444091796875,57220458984375,286102294921875,1430511474609375,7152557373046875,35762786865234375,178813934326171875,894069671630859375,4470348358154296875,22351741790771484375,111758708953857421875,558793544769287109375,2793967723846435546875,13969838619232177734375,69849193096160888671875,349245965480804443359375,1746229827404022216796875 mov $1,5 pow $1,$0 mul $1,30 div $1,100 mul $1,2 add $1,1 mov $0,$1
; ; Copyright (c) 2020 Bitdefender ; SPDX-License-Identifier: Apache-2.0 ; [BITS 32] ; ; section .text global _HvVmcall _HvVmcall: push ebp mov ebp, esp push esi push ebx push edi push ebx mov eax, [ebp+8] mov ecx, [ebp+12] mov edx, [ebp+16] mov esi, [ebp+20] mov edi, [ebp+24] xor ebx, ebx mov ebx, 06C437648H vmcall mov ebx, dword [ebp+28] cmp ebx, 0 jz skip_paramout1 mov [ebx], ecx skip_paramout1: mov ebx, dword [ebp+32] cmp ebx, 0 jz skip_paramout2 mov [ebx], edx skip_paramout2: mov ebx, dword [ebp+36] cmp ebx, 0 jz skip_paramout3 mov [ebx], esi skip_paramout3: mov ebx, dword [ebp+40] cmp ebx, 0 jz skip_paramout4 mov [ebx], edi skip_paramout4: pop ebx pop edi pop ebx pop esi mov esp,ebp pop ebp ret global _CpuGetSecCapabilities _CpuGetSecCapabilities: push ebx mov ebx, [esp + 08h] ; RBX capabilities index xor eax, eax ; RAX param for getsec - 0 = capabilities getsec pop ebx ret
; A170542: Number of reduced words of length n in Coxeter group on 5 generators S_i with relations (S_i)^2 = (S_i S_j)^47 = I. ; 1,5,20,80,320,1280,5120,20480,81920,327680,1310720,5242880,20971520,83886080,335544320,1342177280,5368709120,21474836480,85899345920,343597383680,1374389534720,5497558138880,21990232555520,87960930222080 mov $1,4 pow $1,$0 mul $1,5 div $1,4
;; ;; Copyright (c) 2018-2021, Intel Corporation ;; ;; 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 Intel Corporation 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. ;; %include "include/aesni_emu.inc" %define AES_CBC_DEC_128 aes_cbc_dec_128_sse_no_aesni %include "sse/aes128_cbc_dec_by4_sse.asm"
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR NIRVANA+ ENGINE - by Einar Saukas ; ; See "nirvana+.h" for further details ; ---------------------------------------------------------------- ; void NIRVANAP_fillT_raw(unsigned char attr, unsigned char lin, unsigned char col) ; callee SECTION code_clib SECTION code_nirvanap PUBLIC _NIRVANAP_fillT_raw_callee EXTERN asm_NIRVANAP_fillT_raw _NIRVANAP_fillT_raw_callee: pop hl pop de ; d = lin ld a,e ; a = attr dec sp ex (sp),hl ld e,h ; e = col jp asm_NIRVANAP_fillT_raw
; uchar __FASTCALL__ *zx_saddrcleft(void *pixeladdr) ; aralbrec 06.2007 PUBLIC zx_saddrcleft .zx_saddrcleft ; enter: hl = valid screen address ; exit : carry = moved off screen ; hl = new screen address one character left with line wrap ; uses : af, hl ld a,l dec l or a ret nz ld a,h sub $08 ld h,a cp $40 ret
; A166454: Triangle read by rows: T(n, k) = (1/2)*(A007318(n,k) - A047999(n,k)). ; Submitted by Jamie Morken(s4) ; 1,1,1,2,3,2,2,5,5,2,3,7,10,7,3,3,10,17,17,10,3,4,14,28,35,28,14,4,4,18,42,63,63,42,18,4,5,22,60,105,126,105,60,22,5,5,27,82,165,231,231,165,82,27,5,6,33,110,247,396,462,396,247,110,33,6,6,39,143,357,643,858,858,643,357,143,39,6,7,45,182,500,1001,1501,1716,1501,1001,500,182,45,7,7,52,227,682,1501,2502,3217,3217,2502 lpb $0 add $1,1 sub $0,$1 lpe add $0,1 add $1,2 bin $1,$0 div $1,2 mov $0,$1
db "VIRTUAL@" ; species name db "An artificial" next "#MON created" next "due to extensive" page "research, it can" next "perform only what" next "is in its program.@"
; A017463: a(n) = (11*n + 6)^3. ; 216,4913,21952,59319,125000,226981,373248,571787,830584,1157625,1560896,2048383,2628072,3307949,4096000,5000211,6028568,7189057,8489664,9938375,11543176,13312053,15252992,17373979,19683000,22188041,24897088,27818127,30959144,34328125,37933056,41781923,45882712,50243409,54872000,59776471,64964808,70444997,76225024,82312875,88716536,95443993,102503232,109902239,117649000,125751501,134217728,143055667,152273304,161878625,171879616,182284263,193100552,204336469,216000000,228099131,240641848,253636137,267089984,281011375,295408296,310288733,325660672,341532099,357911000,374805361,392223168,410172407,428661064,447697125,467288576,487443403,508169592,529475129,551368000,573856191,596947688,620650477,644972544,669921875,695506456,721734273,748613312,776151559,804357000,833237621,862801408,893056347,924010424,955671625,988047936,1021147343,1054977832,1089547389,1124864000,1160935651,1197770328,1235376017,1273760704,1312932375,1352899016,1393668613,1435249152,1477648619,1520875000,1564936281,1609840448,1655595487,1702209384,1749690125,1798045696,1847284083,1897413272,1948441249,2000376000,2053225511,2106997768,2161700757,2217342464,2273930875,2331473976,2389979753,2449456192,2509911279,2571353000,2633789341,2697228288,2761677827,2827145944,2893640625,2961169856,3029741623,3099363912,3170044709,3241792000,3314613771,3388518008,3463512697,3539605824,3616805375,3695119336,3774555693,3855122432,3936827539,4019679000,4103684801,4188852928,4275191367,4362708104,4451411125,4541308416,4632407963,4724717752,4818245769,4913000000,5008988431,5106219048,5204699837,5304438784,5405443875,5507723096,5611284433,5716135872,5822285399,5929741000,6038510661,6148602368,6260024107,6372783864,6486889625,6602349376,6719171103,6837362792,6956932429,7077888000,7200237491,7323988888,7449150177,7575729344,7703734375,7833173256,7964053973,8096384512,8230172859,8365427000,8502154921,8640364608,8780064047,8921261224,9063964125,9208180736,9353919043,9501187032,9649992689,9800344000,9952248951,10105715528,10260751717,10417365504,10575564875,10735357816,10896752313,11059756352,11224377919,11390625000,11558505581,11728027648,11899199187,12072028184,12246522625,12422690496,12600539783,12780078472,12961314549,13144256000,13328910811,13515286968,13703392457,13893235264,14084823375,14278164776,14473267453,14670139392,14868788579,15069223000,15271450641,15475479488,15681317527,15888972744,16098453125,16309766656,16522921323,16737925112,16954786009,17173512000,17394111071,17616591208,17840960397,18067226624,18295397875,18525482136,18757487393,18991421632,19227292839,19465109000,19704878101,19946608128,20190307067,20435982904,20683643625 mul $0,11 add $0,6 pow $0,3 mov $1,$0
#include<vector> #include<list> #include<map> #include<bitset> #include<cassert> #include<algorithm> template<typename T, typename Block> class Dependency { typedef std::vector<T> ProducerList; typedef std::vector<T> ConsumerList; typedef std::vector<T> PathList; typedef std::list<Block> BlockList; typedef std::map<Block, BlockList> Paths_t; //typedef std::bitset DUPV; ProducerList Producers; ConsumerList Consumers; Paths_t Paths; //DUPV Dupv; public: void AddProducer(const T& t) { Producers.push_back(t); } void AddConsumer(const T& t) { Consumers.push_back(t); } /** * A -> B, B -> C * => A --> ABC */ void AddPath(const Block& From, const Block& To) { // When no entry enter From as well. if(Paths.find(From) == Paths.end()) { Paths[From].push_back(From); } Paths[From].push_back(To); } /** * For a path ABCDE; From = A, To = C * => AB * i.e., CDE is removed */ void RemovePath(const Block& From, const Block& To) { typename Paths_t::iterator entry = Paths.find(From); assert(entry != Paths.end()); typename BlockList::iterator b_entry = std::find(entry->second.begin(), entry.second.end(), To); assert(b_entry != entry->second.end()); entry.remove(b_entry, entry->second.end()); } typename Paths_t::const_iterator PathExists(const Block& From, const Block& To) { typename Paths_t::const_iterator entry = Paths.find(From); if(entry != Paths.end()) { typename BlockList::iterator b_entry = std::find(entry->second.begin(), entry->second.end(), To); if(b_entry != entry->second.end()) return entry; } return Paths.end(); } };
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %r15 push %rax push %rcx push %rdi push %rsi lea addresses_normal_ht+0x153ac, %r15 nop dec %r12 mov $0x6162636465666768, %rdi movq %rdi, (%r15) and %rax, %rax lea addresses_WC_ht+0x9d34, %rcx nop xor %r13, %r13 mov (%rcx), %r10 nop nop nop sub %r13, %r13 lea addresses_UC_ht+0x77ec, %rsi lea addresses_normal_ht+0x2234, %rdi nop nop and $55139, %r12 mov $111, %rcx rep movsb nop nop nop nop add %r13, %r13 lea addresses_D_ht+0xf634, %rsi lea addresses_WC_ht+0x10874, %rdi nop dec %r12 mov $69, %rcx rep movsb nop nop nop nop cmp $38914, %rax lea addresses_A_ht+0x8134, %r13 nop cmp $33363, %rdi and $0xffffffffffffffc0, %r13 movaps (%r13), %xmm0 vpextrq $0, %xmm0, %rcx nop nop nop nop add %r12, %r12 lea addresses_D_ht+0x19734, %rdi nop nop nop xor $13232, %rax movl $0x61626364, (%rdi) nop nop sub $36911, %rsi lea addresses_WT_ht+0x1e014, %rdi nop nop nop nop nop xor %r10, %r10 mov (%rdi), %r12w nop sub $56294, %r10 lea addresses_D_ht+0xec34, %rsi lea addresses_A_ht+0x13034, %rdi nop nop nop nop add $26135, %rax mov $38, %rcx rep movsq and %r15, %r15 lea addresses_WT_ht+0x8334, %rdi nop nop sub %rax, %rax movb $0x61, (%rdi) nop and %rdi, %rdi lea addresses_UC_ht+0x9bf4, %r15 nop nop and $56697, %rcx movw $0x6162, (%r15) nop nop nop and $35366, %rcx lea addresses_WT_ht+0xfbcc, %r13 nop nop nop xor %rax, %rax vmovups (%r13), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $1, %xmm4, %r15 nop nop nop cmp $34385, %r10 lea addresses_A_ht+0x15934, %rdi nop nop nop nop add $17268, %rsi movw $0x6162, (%rdi) nop nop nop nop and $58762, %rax lea addresses_D_ht+0x5534, %r13 add %rsi, %rsi mov (%r13), %rcx xor %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rax pop %r15 pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r13 push %rax push %rcx push %rdi push %rsi // REPMOV lea addresses_normal+0xc34, %rsi lea addresses_normal+0x1d42e, %rdi nop nop sub %r10, %r10 mov $90, %rcx rep movsq nop nop xor $1895, %rsi // Store lea addresses_US+0x16934, %r11 nop nop nop nop and %rax, %rax mov $0x5152535455565758, %rsi movq %rsi, %xmm5 vmovups %ymm5, (%r11) nop nop nop nop xor $21859, %r10 // Faulty Load lea addresses_PSE+0xa534, %rsi and $45909, %rcx mov (%rsi), %r10 lea oracles, %rsi and $0xff, %r10 shlq $12, %r10 mov (%rsi,%r10,1), %r10 pop %rsi pop %rdi pop %rcx pop %rax pop %r13 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_normal', 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 9, 'size': 32, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': True, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 9, 'size': 8, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': True, 'congruent': 8, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': True, 'congruent': 9, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 7, 'size': 1, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 3, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': True, 'congruent': 9, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 11, 'size': 8, 'same': False, 'NT': False}} {'33': 2088} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
#include <Switch/Switch> using namespace System; namespace Examples { class TextReader abstract_ { public: virtual int ReadByte() = 0; string ReadLine() { string line; for (int b = ReadByte(); b != -1 && b != '\n'; b = ReadByte()) line += as<char32>(b); return line; } string ReadText() { string text; for (int b = ReadByte(); b != -1; b = ReadByte()) text += as<char32>(b); return text; } }; class StringReader : public TextReader { public: StringReader(const string& value) : enumerator(value.GetEnumerator()) {} int ReadByte() override { if (this->enumerator.MoveNext() == false) return -1; return as<int>(this->enumerator.Current()); } private: System::Collections::Generic::Enumerator<char32> enumerator; }; class Program { public: static void Main() { string text = "Line 1\nLine 2\nLine 3"; StringReader sr(text); Console::WriteLine(sr.ReadLine()); } }; } startup_(Examples::Program); // This code produces the following output: // // Line 1
; Licensed to the .NET Foundation under one or more agreements. ; The .NET Foundation licenses this file to you under the MIT license. include <AsmMacros.inc> include AsmConstants.inc extern ExternalMethodFixupWorker:proc extern ProcessCLRException:proc ifdef FEATURE_READYTORUN extern DynamicHelperWorker:proc endif ;============================================================================================ ;; EXTERN_C VOID __stdcall ExternalMethodFixupStub() NESTED_ENTRY ExternalMethodFixupStub, _TEXT, ProcessCLRException PROLOG_WITH_TRANSITION_BLOCK 0, 8, rdx lea rcx, [rsp + __PWTB_TransitionBlock] ; pTransitionBlock sub rdx, 5 ; pThunk mov r8, 0 ; sectionIndex mov r9, 0 ; pModule call ExternalMethodFixupWorker EPILOG_WITH_TRANSITION_BLOCK_TAILCALL PATCH_LABEL ExternalMethodFixupPatchLabel TAILJMP_RAX NESTED_END ExternalMethodFixupStub, _TEXT ifdef FEATURE_READYTORUN NESTED_ENTRY DelayLoad_MethodCall, _TEXT PROLOG_WITH_TRANSITION_BLOCK 0, 10h, r8, r9 lea rcx, [rsp + __PWTB_TransitionBlock] ; pTransitionBlock mov rdx, rax ; pIndirection call ExternalMethodFixupWorker EPILOG_WITH_TRANSITION_BLOCK_TAILCALL ; Share the patch label jmp ExternalMethodFixupPatchLabel NESTED_END DelayLoad_MethodCall, _TEXT ;============================================================================================ DYNAMICHELPER macro frameFlags, suffix NESTED_ENTRY DelayLoad_Helper&suffix, _TEXT PROLOG_WITH_TRANSITION_BLOCK 8h, 10h, r8, r9 mov qword ptr [rsp + SIZEOF_MAX_OUTGOING_ARGUMENT_HOMES], frameFlags lea rcx, [rsp + __PWTB_TransitionBlock] ; pTransitionBlock mov rdx, rax ; pIndirection call DynamicHelperWorker test rax,rax jnz @F mov rax, [rsp + __PWTB_ArgumentRegisters] ; The result is stored in the argument area of the transition block EPILOG_WITH_TRANSITION_BLOCK_RETURN @@: EPILOG_WITH_TRANSITION_BLOCK_TAILCALL TAILJMP_RAX NESTED_END DelayLoad_Helper&suffix, _TEXT endm DYNAMICHELPER DynamicHelperFrameFlags_Default DYNAMICHELPER DynamicHelperFrameFlags_ObjectArg, _Obj DYNAMICHELPER <DynamicHelperFrameFlags_ObjectArg OR DynamicHelperFrameFlags_ObjectArg2>, _ObjObj endif ; FEATURE_READYTORUN end
; This patch modifies the game's code to make certain items progressive, so even if you get them out of order, they will always be upgraded, never downgraded. ; (Note that most of the modifications for this are in the make_items_progressive function of tweaks.py, not here.) ; Swap out the item ID of progressive items for item get events as well as for field items so that their model and item get text change depending on what the next progressive tier of that item you should get is. .open "sys/main.dol" .org 0x80026A24 ; In createDemoItem (for item get events) ; Convert progressive item ID before storing in params bl convert_progressive_item_id_for_createDemoItem .org @NextFreeSpace .global convert_progressive_item_id_for_createDemoItem convert_progressive_item_id_for_createDemoItem: stwu sp, -0x10 (sp) mflr r0 stw r0, 0x14 (sp) mr r3, r26 ; createDemoItem keeps the item ID in r26 bl convert_progressive_item_id ; Get the correct item ID mr r26, r3 ; Put it back where createDemoItem expects it, in r26 li r3, 259 ; And then simply replace the line of code in createDemoItem that we overwrote to call this function lwz r0, 0x14 (sp) mtlr r0 addi sp, sp, 0x10 blr .org 0x800F5550 ; In daItem_create ; Read params, convert progressive item ID, and store back bl convert_progressive_item_id_for_daItem_create .org @NextFreeSpace .global convert_progressive_item_id_for_daItem_create convert_progressive_item_id_for_daItem_create: stwu sp, -0x10 (sp) mflr r0 stw r0, 0x14 (sp) lbz r3, 0xB3 (r31) ; Read this field item's item ID from its params (params are at 0xB0, the item ID is has the mask 0x000000FF) bl convert_progressive_item_id ; Get the correct item ID stb r3, 0xB3 (r31) ; Store the corrected item ID back into the field item's params ; Then we return the item ID in r0 so that the next few lines in daItem_create can use it. mr r0, r3 lwz r3, 0x14 (sp) mtlr r3 addi sp, sp, 0x10 blr .org 0x8012E7B8 ; In dProcGetItem_init__9daPy_lk_cFv ; Read item ID property for this event action and convert progressive item ID bl convert_progressive_item_id_for_dProcGetItem_init_1 .org @NextFreeSpace .global convert_progressive_item_id_for_dProcGetItem_init_1 convert_progressive_item_id_for_dProcGetItem_init_1: stwu sp, -0x10 (sp) mflr r0 stw r0, 0x14 (sp) lwz r3, 0x30C (r28) ; Read the item ID property for this event action bl convert_progressive_item_id ; Get the correct item ID ; Then we return the item ID in r0 so that the next few lines in dProcGetItem_init can use it. mr r0, r3 lwz r3, 0x14 (sp) mtlr r3 addi sp, sp, 0x10 blr .org 0x8012E7DC ; In dProcGetItem_init__9daPy_lk_cFv bl convert_progressive_item_id_for_dProcGetItem_init_2 .org @NextFreeSpace .global convert_progressive_item_id_for_dProcGetItem_init_2 convert_progressive_item_id_for_dProcGetItem_init_2: stwu sp, -0x10 (sp) mflr r0 stw r0, 0x14 (sp) lbz r3, 0x52AC (r3) ; Read the item ID from 803C9EB4 bl convert_progressive_item_id ; Get the correct item ID ; Then we return the item ID in r27 so that the next few lines in dProcGetItem_init can use it. mr r27, r3 lwz r0, 0x14 (sp) mtlr r0 addi sp, sp, 0x10 blr .close .open "files/rels/d_a_shop_item.rel" .org 0x9C0 ; This is where the shop item would originally read its item ID from its params & 0x000000FF and store them to shop item entity+0x63A. ; We need to call a custom function to make the item look progressive, but because this is in a relocatable object file, we can't easily add a new function call to the main executable where there was no function call originally. ; So instead we first remove this original code. nop nop .org 0x8B8 bl convert_progressive_item_id_for_shop_item .org @NextFreeSpace .global convert_progressive_item_id_for_shop_item convert_progressive_item_id_for_shop_item: stwu sp, -0x10 (sp) mflr r0 stw r0, 0x14 (sp) ; Replace the call to savegpr we overwrote to call this custom function bl _savegpr_28 mr r30, r3 ; Preserve the shop item entity pointer lbz r3, 0xB3 (r30) bl convert_progressive_item_id ; Get the correct item ID stb r3, 0x63A (r30) ; Store the item ID to shop item entity+0x63A mr r3, r30 ; Put the shop item entity pointer back into r3, because that's where the function that called this one expects it to be lwz r0, 0x14 (sp) mtlr r0 addi sp, sp, 0x10 blr .close ; Fix a big where buying a progressive item from the shop would not show the item get animation if it's the tier 2+ item. .open "files/rels/d_a_npc_bs1.rel" .org 0x1D00 ; For the Bait Bag slot. bl custom_getSelectItemNo_progressive .org 0x1F3C ; For the 3 Rock Spire Shop Ship slots. bl custom_getSelectItemNo_progressive ; Acts as a replacement to getSelectItemNo, but should only be called when the shopkeeper is checking if the item get animation should play or not, in order to have that properly show for progressive items past the first tier. ; If this was used all the time as a replacement for getSelectItemNo it would cause the shop to be buggy since it uses the item ID to know what slot it's on. .org @NextFreeSpace .global custom_getSelectItemNo_progressive custom_getSelectItemNo_progressive: stwu sp, -0x10 (sp) mflr r0 stw r0, 0x14 (sp) bl getSelectItemNo__11ShopItems_cFv bl convert_progressive_item_id lwz r0, 0x14 (sp) mtlr r0 addi sp, sp, 0x10 blr .close
; A286283: a(n) = floor(7*n^2/48). ; 0,0,0,1,2,3,5,7,9,11,14,17,21,24,28,32,37,42,47,52,58,64,70,77,84,91,98,106,114,122,131,140,149,158,168,178,189,199,210,221,233,245,257,269,282,295,308,322,336,350,364,379,394,409,425,441,457,473,490,507,525,542,560,578,597,616,635,654,674,694,714,735,756,777,798,820,842,864,887,910,933,956,980,1004,1029,1053,1078,1103,1129,1155,1181,1207,1234,1261,1288,1316,1344,1372,1400,1429 mul $0,7 pow $0,2 div $0,336
; ; Z88 Small C+ Run Time Library ; Long support functions ; ; ; aralbrec 01/2007 ; sped up some more ; ; djm 25/2/99 ; Rewritten for size and speed (untested, but should be OK) ; ; djm 22/3/99 Unsigned version SECTION code_l_sccz80 PUBLIC l_long_asr_u EXTERN l_lsr_dehl l_long_asr_u: ; Shift primary (on stack) right by secondary, ld a,l ; a = shift amount pop hl ; hl = return address pop de ; de = primary.LSW ex (sp),hl ; hl = primary.MSW ex de,hl jp l_lsr_dehl
SECTION "Egg Moves 3", ROMX EggMovePointers3:: dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 dw NoEggMoves3 NoEggMoves3: dw -1 ; end
#note: r40 (the exception handler) and r46 (the start of usermode code) must #be specified in hex (0xwhatever) #I just don't see any reason not to, and it makes programming the script #much nicer to deal with... #load exception handler lc r40, 0x80000050 leh r40 #enable exceptions cle #load TLB entries #virtual page 0 is for instructions #virtual page 1 is for data lc r46, 0x0000005c #usermode start address lc r47, 1 #interrupts off lc r48, 1 #in user mode lc r42, 0x00000000 #denotes VPN 0 lc r43, 0x0000000d #denotes VPN 0 maps to physical page 0 #and is fetchable, readable, and valid tlbse r0, r42 #load into entry 0 lc r42, 0x00001000 #denotes VPN 1 lc r43, 0x0000101e #denotes VPN 1 maps to physical page 1 #and is readable, writable, valid, and dirty #(dirty to prevent taking a #read-only exception) tlbse r48, r42 #load into entry 1 #this last tlb entry is designed to produce a bus error lc r44, 2 #load into TLB entry 2 lc r42, 0x3fffe000 #denotes VPN 0x3fffe lc r43, 0x3fffe01f #map VPN 0x3fffe to page 0x3fffe #and is readable, writable, valid, and dirty #(dirty to prevent taking a #read-only exception) tlbse r44, r42 #warp to user mode rfe r46, r47, r48 #handle exceptions lc r49, 0xdeadbeef halt #or rather don't =) lc r30, 1 bez e2, r30, r30 trap #@expected values #e3 = 0x000000a0 #mode = S #interrupts = off #exceptions = off #r40 = 0x80000050 #r46 = 0x0000005c #r47 = 1 #r48 = 1 #r42 = 0x3fffe000 #r43 = 0x3fffe01f #r44 = 2 #r49 = 0xdeadbeef #pc = 0x8000005c #e0 = 0x00000060 #e2 = 0x00000060 #e1 = 0x00000001 #tlb 0: # vpn = 0x00000 # os = 0x000 # ppn = 0x00000 # at = 0x00d #tlb 1: # vpn = 0x00001 # os = 0x000 # ppn = 0x00001 # at = 0x01e #tlb 2: # vpn = 0x3fffe # os = 0x000 # ppn = 0x3fffe # at = 0x01f
; A080827: Rounded up staircase on natural numbers. ; 1,3,5,9,13,19,25,33,41,51,61,73,85,99,113,129,145,163,181,201,221,243,265,289,313,339,365,393,421,451,481,513,545,579,613,649,685,723,761,801,841,883,925,969,1013,1059,1105,1153,1201,1251,1301,1353,1405,1459,1513,1569,1625,1683,1741,1801,1861,1923,1985,2049,2113,2179,2245,2313,2381,2451,2521,2593,2665,2739,2813,2889,2965,3043,3121,3201,3281,3363,3445,3529,3613,3699,3785,3873,3961,4051,4141,4233,4325,4419,4513,4609,4705,4803,4901,5001,5101,5203,5305,5409,5513,5619,5725,5833,5941,6051,6161,6273,6385,6499,6613,6729,6845,6963,7081,7201,7321,7443,7565,7689,7813,7939,8065,8193,8321,8451,8581,8713,8845,8979,9113,9249,9385,9523,9661,9801,9941,10083,10225,10369,10513,10659,10805,10953,11101,11251,11401,11553,11705,11859,12013,12169,12325,12483,12641,12801,12961,13123,13285,13449,13613,13779,13945,14113,14281,14451,14621,14793,14965,15139,15313,15489,15665,15843,16021,16201,16381,16563,16745,16929,17113,17299,17485,17673,17861,18051,18241,18433,18625,18819,19013,19209,19405,19603,19801,20001,20201,20403,20605,20809,21013,21219,21425,21633,21841,22051,22261,22473,22685,22899,23113,23329,23545,23763,23981,24201,24421,24643,24865,25089,25313,25539,25765,25993,26221,26451,26681,26913,27145,27379,27613,27849,28085,28323,28561,28801,29041,29283,29525,29769,30013,30259,30505,30753,31001,31251 add $0,1 mov $1,$0 pow $1,2 div $1,2 add $1,1
; A031915: a(n) = prime(8*n - 7). ; 2,23,59,97,137,179,227,269,313,367,419,461,509,571,617,661,727,773,829,883,947,1009,1051,1103,1171,1229,1289,1327,1427,1471,1523,1579,1621,1697,1753,1823,1879,1951,2011,2081,2131,2207,2269,2333,2381,2437,2521,2591,2659,2699,2749,2803,2879,2953,3019,3083,3169,3229,3307,3359,3433,3499,3547,3613,3673,3733,3803,3877,3929,4007,4073,4133,4217,4261,4339,4421,4483,4549,4637,4679,4759,4817,4919,4969,5021,5099,5171,5237,5323,5407,5449,5519,5581,5657,5717,5801,5851,5903,6011,6079 mul $0,8 seq $0,40 ; The prime numbers.
; A061352: First row of array shown below. ; 1,2,6,7,5,6,8,9,5,6,6,7,1,2,0,1,3,4,0,1,1,2,6,7,5,6,8,9,5,6,6,7,1,2,0,1,3,4,0,1,1,2,6,7,5,6,8,9,5,6,6,7,1,2,0,1,3,4,0,1,1,2,6,7,5,6,8,9,5,6,6,7,1,2,0,1,3,4,0,1,1,2,6,7,5,6,8,9,5,6,6,7,1,2,0,1,3,4,0,1,1,2,6,7,5 add $0,5 cal $0,61353 ; First column of array shown in A061352. mov $1,$0
; float __fspoly (const float x, const float d[], uint16_t n) SECTION code_clib SECTION code_fp_math32 PUBLIC cm32_sdcc_fspoly EXTERN m32_fspoly_callee .cm32_sdcc_fspoly ; evaluation of a polynomial function ; ; enter : stack = uint16_t n, float d[], float x, ret ; ; exit : dehl = 32-bit product ; carry reset ; ; uses : af, bc, de, hl, af', bc', de', hl' pop af ; my return pop hl ; (float)x pop de exx pop hl ; (float*)d pop de ; (uint16_t)n push af ; my return push de ; (uint16_t)n push hl ; (float*)d exx push de ; (float)x push hl call m32_fspoly_callee pop af ; my return push af push af push af push af push af ret
align macro cnop 0,\1 endm ; ======================================================================================= ; Sega CD Header (Based on Sonic CD's header) ; ======================================================================================= DiscType: dc.b 'SEGADISCSYSTEM ' ; Disc Type (Must be SEGADISCSYSTEM) VolumeName: dc.b 'SEGACDGAME ',0 ; Disc ID VolumeSystem: dc.w $100, $1 ; System ID, Type SystemName: dc.b 'SEGACDGAME ',0 ; System Name SystemVersion: dc.w 0,0 ; System Version, Type IP_Addr: dc.l $800 ; IP Start Address (Must be $800) IP_Size: dc.l $800 ; IP End Address (Must be $800) IP_Entry: dc.l 0 IP_WorkRAM: dc.l 0 SP_Addr: dc.l $1000 ; SP Start Address (Must be $1000) SP_Size: dc.l $7000 ; SP End Address (Must be $7000) SP_Entry: dc.l 0 SP_WorkRAM: dc.l 0 align $100 ; Pad to $100 ; ======================================================================================= ; Game Header ; ======================================================================================= HardwareType: dc.b 'SEGA MEGA DRIVE ' Copyright: dc.b '(C)LUKE 2010.OCT' NativeName: dc.b 'SEGA CD TEST GAME ' OverseasName: dc.b 'SEGA CD TEST GAME ' DiscID: dc.b 'GM 00-0000-00 ' IO: dc.b 'J ' ; Modem information, notes, and padding, left undefined as it is not used ; Padded to $1F0 instead (Start of Region Code) align $1F0 Region: dc.b 'E ' ; ======================================================================================== ; IP (Includes security sector) ; ======================================================================================== incbin "ip.bin"; ; ======================================================================================= ; Sub CPU Program (SP) ; ======================================================================================= align $1000 incbin "sp.bin" ; ======================================================================================= ; Padding, to $8000 (Size of boot area of iso) ; ======================================================================================= align $8000
// // Created by nis on 19.01.17. // #include "uint_to_str.h" namespace util { size_t const get_length(uint32_t value) { if (value < 1e5) { if (value < 1e3) { if (value < 1e2) { if (value < 1e1) { return 1; } else { return 2; } } else { return 3; } } else { if (value < 1e4) { return 4; } else { return 5; } } } else { if (value < 1e7) { if (value < 1e6) { return 6; } else { return 7; } } else { if (value < 1e9) { if (value < 1e8) { return 8; } else { return 9; } } else { return 10; } } } } size_t uint32_to_str(uint32_t value, char *dst) { static const char digits[201] = "0001020304050607080910111213141516171819" "2021222324252627282930313233343536373839" "4041424344454647484950515253545556575859" "6061626364656667686970717273747576777879" "8081828384858687888990919293949596979899"; size_t const length = get_length(value); size_t next = length - 1; while (value >= 100) { auto const i = (value % 100) * 2; value /= 100; dst[next] = digits[i + 1]; dst[next - 1] = digits[i]; next -= 2; } // Handle last 1-2 digits if (value < 10) { dst[next] = (char) ('0' + uint32_t(value)); } else { auto i = uint32_t(value) * 2; dst[next] = digits[i + 1]; dst[next - 1] = digits[i]; } return length; } }
; A035008: Total number of possible knight moves on an (n+2) X (n+2) chessboard, if the knight is placed anywhere. ; 0,16,48,96,160,240,336,448,576,720,880,1056,1248,1456,1680,1920,2176,2448,2736,3040,3360,3696,4048,4416,4800,5200,5616,6048,6496,6960,7440,7936,8448,8976,9520,10080,10656,11248,11856,12480,13120,13776,14448,15136,15840,16560,17296,18048,18816,19600,20400,21216,22048,22896,23760,24640,25536,26448,27376,28320,29280,30256,31248,32256,33280,34320,35376,36448,37536,38640,39760,40896,42048,43216,44400,45600,46816,48048,49296,50560,51840,53136,54448,55776,57120,58480,59856,61248,62656,64080,65520,66976,68448,69936,71440,72960,74496,76048,77616,79200 sub $1,$0 bin $1,2 mul $1,16 mov $0,$1
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/lambda/model/LayersListItem.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Lambda { namespace Model { LayersListItem::LayersListItem() : m_layerNameHasBeenSet(false), m_layerArnHasBeenSet(false), m_latestMatchingVersionHasBeenSet(false) { } LayersListItem::LayersListItem(JsonView jsonValue) : m_layerNameHasBeenSet(false), m_layerArnHasBeenSet(false), m_latestMatchingVersionHasBeenSet(false) { *this = jsonValue; } LayersListItem& LayersListItem::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("LayerName")) { m_layerName = jsonValue.GetString("LayerName"); m_layerNameHasBeenSet = true; } if(jsonValue.ValueExists("LayerArn")) { m_layerArn = jsonValue.GetString("LayerArn"); m_layerArnHasBeenSet = true; } if(jsonValue.ValueExists("LatestMatchingVersion")) { m_latestMatchingVersion = jsonValue.GetObject("LatestMatchingVersion"); m_latestMatchingVersionHasBeenSet = true; } return *this; } JsonValue LayersListItem::Jsonize() const { JsonValue payload; if(m_layerNameHasBeenSet) { payload.WithString("LayerName", m_layerName); } if(m_layerArnHasBeenSet) { payload.WithString("LayerArn", m_layerArn); } if(m_latestMatchingVersionHasBeenSet) { payload.WithObject("LatestMatchingVersion", m_latestMatchingVersion.Jsonize()); } return payload; } } // namespace Model } // namespace Lambda } // namespace Aws
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <ripple/module/app/main/RPCHTTPServer.h> #include <ripple/module/rpc/RPCHandler.h> #include <ripple/module/rpc/RPCServerHandler.h> namespace ripple { RPCServerHandler::RPCServerHandler (NetworkOPs& networkOPs, Resource::Manager& resourceManager) : m_networkOPs (networkOPs) , m_resourceManager (resourceManager) { } std::string RPCServerHandler::createResponse ( int statusCode, std::string const& description) { return HTTPReply (statusCode, description); } bool RPCServerHandler::isAuthorized ( std::map <std::string, std::string> const& headers) { return HTTPAuthorized (headers); } std::string RPCServerHandler::processRequest (std::string const& request, beast::IP::Endpoint const& remoteIPAddress) { Json::Value jsonRequest; { Json::Reader reader; if ((request.size() > 1000000) || ! reader.parse (request, jsonRequest) || jsonRequest.isNull () || ! jsonRequest.isObject ()) { return createResponse (400, "Unable to parse request"); } } Config::Role const role (getConfig ().getAdminRole (jsonRequest, remoteIPAddress)); Resource::Consumer usage; if (role == Config::ADMIN) usage = m_resourceManager.newAdminEndpoint (remoteIPAddress.to_string()); else usage = m_resourceManager.newInboundEndpoint (remoteIPAddress); if (usage.disconnect ()) return createResponse (503, "Server is overloaded"); // Parse id now so errors from here on will have the id // // VFALCO NOTE Except that "id" isn't included in the following errors... // Json::Value const& id = jsonRequest ["id"]; Json::Value const& method = jsonRequest ["method"]; if (method.isNull ()) { return createResponse (400, "Null method"); } else if (! method.isString ()) { return createResponse (400, "method is not string"); } std::string strMethod = method.asString (); if (jsonRequest["params"].isNull()) jsonRequest["params"] = Json::Value (Json::arrayValue); // Parse params Json::Value& params = jsonRequest ["params"]; if (!params.isArray ()) return HTTPReply (400, "params unparseable"); // VFALCO TODO Shouldn't we handle this earlier? // if (role == Config::FORBID) { // VFALCO TODO Needs implementing // FIXME Needs implementing // XXX This needs rate limiting to prevent brute forcing password. return HTTPReply (403, "Forbidden"); } // This code does all the work on the io_service thread and // has no rate-limiting based on source IP or anything. // This is a temporary safety if ((role != Config::ADMIN) && (getApp().getFeeTrack().isLoadedLocal())) { return HTTPReply (503, "Unable to service at this time"); } std::string response; WriteLog (lsDEBUG, RPCServer) << "Query: " << strMethod << params; { Json::Value ripple_params (params.size() ? params [0u] : Json::Value (Json::objectValue)); if (!ripple_params.isObject()) return HTTPReply (400, "params must be an object"); ripple_params ["command"] = strMethod; RPC::Request req (LogPartition::getJournal <RPCServer> (), strMethod, ripple_params, getApp ()); // VFALCO Try processing the command using the new code if (getApp().getRPCManager().dispatch (req)) { usage.charge (req.fee); WriteLog (lsDEBUG, RPCServer) << "Reply: " << req.result; return createResponse (200, JSONRPCReply (req.result, Json::Value (), id)); } } // legacy dispatcher Resource::Charge fee (Resource::feeReferenceRPC); RPCHandler rpcHandler (m_networkOPs); Json::Value const result = rpcHandler.doRpcCommand ( strMethod, params, role, fee); usage.charge (fee); WriteLog (lsDEBUG, RPCServer) << "Reply: " << result; response = JSONRPCReply (result, Json::Value (), id); return createResponse (200, response); } }
; void *b_vector_init(void *p, size_t capacity, size_t max_size) SECTION code_adt_b_vector PUBLIC _b_vector_init EXTERN asm_b_vector_init _b_vector_init: pop af pop de pop bc pop hl push hl push bc push de push af jp asm_b_vector_init
; A322830: a(n) = 32*n^3 + 48*n^2 + 18*n + 1. ; 1,99,485,1351,2889,5291,8749,13455,19601,27379,36981,48599,62425,78651,97469,119071,143649,171395,202501,237159,275561,317899,364365,415151,470449,530451,595349,665335,740601,821339,907741,999999,1098305,1202851,1313829,1431431,1555849,1687275,1825901,1971919,2125521,2286899,2456245,2633751,2819609,3014011,3217149,3429215,3650401,3880899,4120901,4370599,4630185,4899851,5179789,5470191,5771249,6083155,6406101,6740279,7085881,7443099,7812125,8193151,8586369,8991971,9410149,9841095,10285001,10742059,11212461,11696399,12194065,12705651,13231349,13771351,14325849,14895035,15479101,16078239,16692641,17322499,17968005,18629351,19306729,20000331,20710349,21436975,22180401,22940819,23718421,24513399,25325945,26156251,27004509,27870911,28755649,29658915,30580901,31521799 mov $1,$0 mul $0,2 mul $1,4 add $1,3 pow $1,2 mul $0,$1 div $0,2 mul $0,2 add $0,1
global _start section .data name db 'Zara Ali', 0xa nameLen equ $-name section .text _start: ; Output name mov eax, 4 mov ebx, 1 mov ecx, name mov edx, nameLen int 0x80 ; Change the name value mov [name], dword 'Nuha' ; Output the new name mov eax, 4 mov ebx, 1 mov ecx, name mov edx, nameLen int 0x80 ; Exit mov eax, 1 mov ebx, 0 int 0x80 ; Type Specifier Bytes addressed ; BYTE 1 ; WORD 2 ; DWORD 4 ; QWORD 8 ; TBYTE 10
SECTION code_fp_math16 PUBLIC _negf16 EXTERN cm16_sdcc_neg defc _negf16 = cm16_sdcc_neg
BITS 32 extern print_line global mystery1 global mystery2 global mystery3 global mystery4 global mystery5 global mystery6 global mystery7 global mystery8 global mystery9 section .text mystery1: push ebp mov ebp, esp xor ecx, ecx mov edi, [ebp+8] not ecx xor al, al cld repne scasb not ecx lea eax, [ecx-1] leave ret ;;;;;;;;;;;;;;;;;;;;;;;am terminat de optimizat mystery1;;;;;;;;;;;;;;;;;;;;;;; mystery2: push ebp mov ebp, esp mov edi, DWORD[ebp+0x8] mov dl, BYTE[ebp+0xc] xor eax, eax repeta: cmp BYTE[edi], dl je final cmp BYTE[edi], BYTE 0 je terminator add edi, 1 add eax, 1 jmp repeta terminator: mov edi, 0x0 mov eax, 0xffffffff final: leave ret ;;;;;;;;;;;;;;;;;;;;;;;am terminat de optimizat mystery2;;;;;;;;;;;;;;;;;;;;;;; mystery3: push ebp mov ebp, esp mov ebx, DWORD[ebp+0x8] mov edx, DWORD[ebp+0xc] mov ecx, DWORD[ebp+0x10] mystery3_l1: mov al, BYTE[ebx] mov ah, BYTE[edx] cmp al, ah jne mystery3_l2 inc ebx inc edx dec ecx jnz mystery3_l1 xor eax, eax jmp mystery3_l3 mystery3_l2: mov eax, 0x1 mystery3_l3: leave ret ;;;;;;;;;;;;;;;;;;;;;;;am terminat de optimizat mystery3;;;;;;;;;;;;;;;;;;;;;;; mystery4: push ebp mov ebp, esp mov eax, DWORD[ebp+0x8] mov ebx, DWORD[ebp+0xc] mov ecx, DWORD[ebp+0x10] mystery4_l1: mov dl, BYTE[ebx] mov BYTE[eax], dl inc eax inc ebx dec ecx jnz mystery4_l1 leave ret ;;;;;;;;;;;;;;;;;;;;;;;am terminat de optimizat mystery4;;;;;;;;;;;;;;;;;;;;;;; mystery5: push ebp mov ebp, esp mov eax, DWORD[ebp+0x8] cmp al, 0x30 jl mystery5_l1 cmp al, 0x39 jg mystery5_l1 mov eax, 0x1 jmp mystery5_l2 mystery5_l1: mov eax, 0x0 mystery5_l2: leave ret ;;;;;;;;;;;;;;;;;;;;;;;TODO;;;;;;;;;;;;;;;;;;;;;;; mystery6: push ebp mov ebp, esp mov edi, DWORD[ebp+0x8] xor ecx, ecx not ecx xor al, al cld repne scasb not ecx lea eax, [ecx-1] mov edi, DWORD[ebp+0x8] mov ecx, eax mystery6_l1: mov dl, BYTE[edi+ecx-1] mov BYTE[ebx], dl inc ebx dec ecx jnz mystery6_l1 mystery6_l2: mov dl, BYTE[ebx] mov BYTE[eax], dl inc eax inc ebx dec ecx jnz mystery6_l2 leave ret ;;;;;;;;;;;;;;;;;;;;;;;TODO;;;;;;;;;;;;;;;;;;;;;;; mystery7: push ebp mov ebp, esp xor eax, eax mov edi, dword[ebp + 8] mystery7_l1: mov dl, byte[edi] sub dl, 0x30 cmp dl, 0 jl mystery7_l2 cmp dl, 9 jg mystery7_l2 imul eax, 10 add eax, edx inc edi cmp byte[edi], 0x00 jne mystery7_l1 leave ret mystery7_l2: mov eax, 0xffffffff leave ret ;;;;;;;;;;;;;;;;;;;;;;;am optimizat mystery7;;;;;;;;;;;;;;;;;;;;;;; mystery8: push ebp mov ebp, esp mov esi, [ebp + 8] mov edi, [ebp + 12] mov ecx, [ebp + 16] xor ebx, ebx mystery8_l1: cmp ebx, ecx jge mystery8_l22 mov al, BYTE [esi] cmp al, 0 je mystery8_l2 cmp al, 10 je mystery8_l2 mov dl, [edi + ebx] cmp dl, al je mystery8_l11 mov ebx, -1 mystery8_l11: inc ebx inc esi jmp mystery8_l1 mystery8_l22: mov eax, 1 jmp mystery8_l3 mystery8_l2: xor eax, eax mystery8_l3: leave ret ;;;;;;;;;;;;;;;;;;;;;;;am optimizat mystery8;;;;;;;;;;;;;;;;;;;;;;; mystery9: push ebp mov ebp, esp sub esp, 0x14 mov eax, DWORD[ebp+0xc] mov DWORD[ebp-0x10], eax mov DWORD[ebp-0xc], eax push DWORD[ebp+0x14] call mystery1 add esp, 0x4 mov DWORD[ebp-0x14], eax mystery9_l1: mov eax, DWORD[ebp-0xc] cmp eax, DWORD[ebp+0x10] jae mystery9_l2 mov edx, DWORD[ebp+0x8] lea eax, [eax + edx] mov al, BYTE[eax] cmp al, 0xa jne mystery9_l3 mov eax, DWORD[ebp-0x10] lea eax, [eax + edx] push DWORD[ebp-0x14] push DWORD[ebp+0x14] push eax call mystery8 add esp, 0xc test eax, eax je mystery9_l4 mov edx, DWORD[ebp+0x8] mov eax, DWORD[ebp-0x10] lea eax, [eax + edx] push eax call print_line add esp, 0x4 mystery9_l4: mov eax, DWORD[ebp-0xc] inc eax mov DWORD[ebp-0x10], eax mystery9_l3: inc DWORD[ebp-0xc] jmp mystery9_l1 mystery9_l2: leave ret ;;;;;;;;;;;;;;;;;;;;;;;TODO;;;;;;;;;;;;;;;;;;;;;;;
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file 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 <condition_variable> #include <future> #include <memory> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <rapidjson/document.h> #include "MockAttachmentManager.h" #include "MockContextManager.h" #include "MockDirectiveHandlerResult.h" #include "MockExceptionEncounteredSender.h" #include "MockMessageSender.h" #include "MockFocusManager.h" #include <AVSCommon/Utils/Configuration/ConfigurationNode.h> #include <AVSCommon/Utils/JSON/JSONUtils.h> #include <AVSCommon/Utils/Logger/Logger.h> #include <AVSCommon/Utils/Memory/Memory.h> #include <SmartScreenSDKInterfaces/ActivityEvent.h> #include <SmartScreenSDKInterfaces/AlexaPresentationObserverInterface.h> #include <SmartScreenSDKInterfaces/VisualStateProviderInterface.h> #include "AlexaPresentation/AlexaPresentation.h" namespace alexaSmartScreenSDK { namespace smartScreenCapabilityAgents { namespace alexaPresentation { namespace test { using namespace alexaClientSDK; using namespace alexaClientSDK::avsCommon::avs; using namespace alexaClientSDK::avsCommon::sdkInterfaces; using namespace alexaClientSDK::avsCommon::utils::configuration; using namespace alexaClientSDK::avsCommon::utils::memory; using namespace rapidjson; using namespace ::testing; /// Alias for JSON stream type used in @c ConfigurationNode initialization using JSONStream = std::vector<std::shared_ptr<std::istream>>; /// Timeout when waiting for futures to be set. static std::chrono::milliseconds TIMEOUT(1000); /// The second namespace registered for this capability agent. static const std::string NAMESPACE1{"Alexa.Presentation"}; /// The third namespace registered for this capability agent. static const std::string NAMESPACE2{"Alexa.Presentation.APL"}; /// An unknown directive signature. static const std::string UNKNOWN_DIRECTIVE{"Unknown"}; /// The RenderDocument directive signature. static const NamespaceAndName DOCUMENT{NAMESPACE2, "RenderDocument"}; /// The RenderDocument directive signature. static const NamespaceAndName COMMAND{NAMESPACE2, "ExecuteCommands"}; /// The name for UserEvent event. static const std::string USER_EVENT_EVENT{"UserEvent"}; /// The name for LoadIndexListData event. static const std::string LOAD_INDEX_LIST_DATA{"LoadIndexListData"}; /// The name for LoadTokenListData event. static const std::string LOAD_TOKEN_LIST_DATA{"LoadTokenListData"}; /// The name for UserEvent event. static const std::string DOCUMENT_DISMISSED_EVENT{"Dismissed"}; /// The @c MessageId identifer. static const std::string MESSAGE_ID("messageId"); /// The @c MessageId identifer. static const std::string MESSAGE_ID_2("messageId2"); /// Payload to be sent for UserEvent static const std::string SAMPLE_USER_EVENT_PAYLOAD = R"({"key":"value"})"; /// DynamicIndexList DataSource type static const std::string DYNAMIC_INDEX_LIST("dynamicIndexList"); /// Payload to be sent for ListDataSourceFetchRequest static const std::string SAMPLE_INDEX_DATA_SOURCE_FETCH_REQUEST = R"({"correlationToken":"101","count":10.0,"listId":"vQdpOESlok","startIndex":1.0})"; /// DynamicTokenList DataSource type static const std::string DYNAMIC_TOKEN_LIST("dynamicTokenList"); /// Payload to be sent for TokenDataSourceFetchRequest static const std::string SAMPLE_TOKEN_DATA_SOURCE_FETCH_REQUEST = R"({"correlationToken":"101","listId":"vQdpOESlok","pageToken":"nextPage"})"; /// String to identify log entries originating from this file. static const std::string TAG("AlexaPresentationTest"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) /** * Expected payload to be sent with Dismissed event when * @c DOCUMENT_APL_PAYLOAD was the RenderDocument directive payload */ static const std::string EXPECTED_DOCUMENT_DISMISSED_PAYLOAD = R"({"presentationToken":"APL_TOKEN"})"; /** * Expected payload to be sent with Dismissed event when * @c DOCUMENT_APL_PAYLOAD_2 was the RenderDocument directive payload */ static const std::string EXPECTED_DOCUMENT_DISMISSED_PAYLOAD_2 = R"({"presentationToken":"APL_TOKEN_2"})"; /// JSON key for the event section of a message. static const std::string MESSAGE_EVENT_KEY = "event"; /// JSON key for the namespace field of a message header. static const std::string MESSAGE_NAMESPACE_KEY = "namespace"; /// JSON key for the name field of a message header. static const std::string MESSAGE_NAME_KEY = "name"; /// JSON key for the header section of a message. static const std::string MESSAGE_HEADER_KEY = "header"; /// JSON key for the payload section of an message. static const std::string MESSAGE_PAYLOAD_KEY = "payload"; // clang-format off /// A RenderDocument directive with APL payload. static const std::string DOCUMENT_APL_PAYLOAD = "{" "\"presentationToken\":\"APL_TOKEN\"," "\"windowId\":\"WINDOW_ID\"," "\"document\":\"{}\"" "}"; /// A 2nd RenderDocument directive with APL payload. static const std::string DOCUMENT_APL_PAYLOAD_2 = "{" "\"presentationToken\":\"APL_TOKEN_2\"," "\"windowId\":\"WINDOW_ID\"," "\"document\":\"{}\"" "}"; /// A malformed RenderDocument directive with APL payload without presentationToken. static const std::string DOCUMENT_APL_PAYLOAD_MALFORMED = "{" "\"token\":\"APL_TOKEN\"" "}"; /// A malformed RenderDocument directive with APL payload without document. static const std::string DOCUMENT_APL_PAYLOAD_MALFORMED_2 = "{" "\"presentationToken\":\"APL_TOKEN\"" "}"; /// A malformed ExecuteCommand directive with APL payload without commands. static const std::string EXECUTE_COMMAND_PAYLOAD_MALFORMED = "{" "\"presentationToken\":\"APL_TOKEN\"" "}"; /// A malformed ExecuteCommand directive with APL payload without presentationToken. static const std::string EXECUTE_COMMAND_PAYLOAD_MALFORMED_2 = "{" "\"token\":\"APL_TOKEN\"" "}"; // Properly formed execute command static const std::string EXECUTE_COMMAND_PAYLOAD = "{" "\"presentationToken\":\"APL_TOKEN\"," "\"commands\": [" " {\"type\": \"idleCommand\"} " "]" "}"; static const std::string SETTINGS_CONFIG = R"({"alexaPresentationCapabilityAgent":{ "displayDocumentInteractionIdleTimeout":500, "minStateReportIntervalMs": 250, "stateReportCheckIntervalMs": 300 }})"; /// Test window ID static const std::string WINDOW_ID = "WINDOW_ID"; /// A visual state request token. static const unsigned int STATE_REQUEST_TOKEN = 1; /// A state request token for a proactive state request static const unsigned int PROACTIVE_STATE_REQUEST_TOKEN = 0; static std::shared_ptr<avsCommon::utils::metrics::MetricRecorderInterface> metricRecorder; // clang-format on /// Mock of AlexaPresentationObserverInterface for testing. class MockGui : public smartScreenSDKInterfaces::AlexaPresentationObserverInterface { public: MOCK_METHOD2(executeCommands, void(const std::string& jsonPayload, const std::string& token)); MOCK_METHOD3( renderDocument, void( const std::string& jsonPayload, const std::string& token, const std::string& windowId)); MOCK_METHOD3( dataSourceUpdate, void(const std::string& sourceType, const std::string& jsonPayload, const std::string& token)); MOCK_METHOD0(clearDocument, void()); MOCK_METHOD0(interruptCommandSequence, void()); MOCK_METHOD0(onPresentationSessionChanged, void()); }; /// Mock of VisualStateProviderInterface for testing. class MockVisualStateProvider : public alexaSmartScreenSDK::smartScreenSDKInterfaces::VisualStateProviderInterface { public: MOCK_METHOD1(provideState, void(const unsigned int stateRequestToken)); }; std::mutex m; std::condition_variable conditionVariable; /// Test harness for @c AlexaPresentation class. class AlexaPresentationTest : public ::testing::Test { public: /// Set up the test harness for running a test. void SetUp() override; /// Clean up the test harness after running a test. void TearDown() override; /// A constructor which initializes the promises and futures needed for the test class. AlexaPresentationTest() : m_wakeAcquireChannelPromise{}, m_wakeAcquireChannelFuture{m_wakeAcquireChannelPromise.get_future()}, m_wakeReleaseChannelPromise{}, m_wakeReleaseChannelFuture{m_wakeReleaseChannelPromise.get_future()} { } protected: /// Promise to synchronize acquireChannel calls. std::promise<void> m_wakeAcquireChannelPromise; /// Future to synchronize acquireChannel calls. std::future<void> m_wakeAcquireChannelFuture; /// Promise to synchronize releaseChannel calls. std::promise<void> m_wakeReleaseChannelPromise; /// Future to synchronize releaseChannel calls. std::future<void> m_wakeReleaseChannelFuture; /// This is the condition variable to be used to control getting of a context in test cases. std::condition_variable m_contextTrigger; /// mutex for the conditional variables. std::mutex m_mutex; /// A strict mock that allows the test to fetch context. std::shared_ptr<StrictMock<smartScreenSDKInterfaces::test::MockContextManager>> m_mockContextManager; /// A strict mock that allows the test to strictly monitor the exceptions being sent. std::shared_ptr<StrictMock<smartScreenSDKInterfaces::test::MockExceptionEncounteredSender>> m_mockExceptionSender; /// A strict mock that allows the test to strictly monitor the handling of directives. std::unique_ptr<StrictMock<smartScreenSDKInterfaces::test::MockDirectiveHandlerResult>> m_mockDirectiveHandlerResult; /// @c FocusManager to request focus to the Visual channel. std::shared_ptr<smartScreenSDKInterfaces::test::MockFocusManager> m_mockFocusManager; /// A strict mock to allow testing of the observer callback. std::shared_ptr<StrictMock<MockGui>> m_mockGui; /// A pointer to an instance of the AlexaPresentation that will be instantiated per test. std::shared_ptr<AlexaPresentation> m_AlexaPresentation; /// The mock @c MessageSenderInterface. std::shared_ptr<StrictMock<smartScreenSDKInterfaces::test::MockMessageSender>> m_mockMessageSender; /// A strict mock to allow testing for visual state provider. std::shared_ptr<StrictMock<MockVisualStateProvider>> m_mockVisualStateProvider; // The pointer into the @c Executor used by the tested object. std::shared_ptr<alexaClientSDK::avsCommon::utils::threading::Executor> m_executor; }; /* * Utility function to generate @c ConfigurationNode from JSON string. */ static void setConfig() { auto stream = std::shared_ptr<std::stringstream>(new std::stringstream(SETTINGS_CONFIG)); JSONStream jsonStream({stream}); ConfigurationNode::initialize(jsonStream); } void AlexaPresentationTest::SetUp() { setConfig(); m_mockContextManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockContextManager>>(); m_mockExceptionSender = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockExceptionEncounteredSender>>(); m_mockDirectiveHandlerResult = make_unique<StrictMock<smartScreenSDKInterfaces::test::MockDirectiveHandlerResult>>(); m_mockFocusManager = std::make_shared<NiceMock<smartScreenSDKInterfaces::test::MockFocusManager>>(); m_mockGui = std::make_shared<StrictMock<MockGui>>(); m_mockMessageSender = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockMessageSender>>(); m_mockVisualStateProvider = std::make_shared<StrictMock<MockVisualStateProvider>>(); EXPECT_CALL(*m_mockContextManager, setStateProvider(_, _)).Times(Exactly(1)); m_AlexaPresentation = AlexaPresentation::create( m_mockFocusManager, m_mockExceptionSender, metricRecorder, m_mockMessageSender, m_mockContextManager, m_mockVisualStateProvider); m_executor = std::make_shared<alexaClientSDK::avsCommon::utils::threading::Executor>(); m_AlexaPresentation->setExecutor(m_executor); m_AlexaPresentation->addObserver(m_mockGui); ON_CALL(*m_mockFocusManager, acquireChannel(_, _, _)).WillByDefault(InvokeWithoutArgs([this] { m_AlexaPresentation->onFocusChanged( avsCommon::avs::FocusState::FOREGROUND, alexaClientSDK::avsCommon::avs::MixingBehavior::UNDEFINED); return true; })); ON_CALL(*m_mockFocusManager, releaseChannel(_, _)).WillByDefault(InvokeWithoutArgs([this] { auto releaseChannelSuccess = std::make_shared<std::promise<bool>>(); std::future<bool> returnValue = releaseChannelSuccess->get_future(); m_AlexaPresentation->onFocusChanged( avsCommon::avs::FocusState::NONE, alexaClientSDK::avsCommon::avs::MixingBehavior::UNDEFINED); releaseChannelSuccess->set_value(true); return returnValue; })); } void AlexaPresentationTest::TearDown() { if (m_AlexaPresentation) { m_AlexaPresentation->shutdown(); m_AlexaPresentation.reset(); } } /** * Tests creating the AlexaPresentation with a null contextManager. */ TEST_F(AlexaPresentationTest, testNullContextManagerInterface) { auto alexaPresentation = AlexaPresentation::create( m_mockFocusManager, m_mockExceptionSender, metricRecorder, m_mockMessageSender, nullptr); ASSERT_EQ(alexaPresentation, nullptr); } /** * Tests creating the AlexaPresentation with a null focusManagerInterface. */ TEST_F(AlexaPresentationTest, testNullFocusManagerInterface) { auto alexaPresentation = AlexaPresentation::create( nullptr, m_mockExceptionSender, metricRecorder, m_mockMessageSender, m_mockContextManager); ASSERT_EQ(alexaPresentation, nullptr); } /** * Tests creating the AlexaPresentation with a null exceptionSender. */ TEST_F(AlexaPresentationTest, testNullExceptionSender) { auto alexaPresentation = AlexaPresentation::create( m_mockFocusManager, nullptr, metricRecorder, m_mockMessageSender, m_mockContextManager); ASSERT_EQ(alexaPresentation, nullptr); } TEST_F(AlexaPresentationTest, testNullMessageSender) { auto alexaPresentation = AlexaPresentation::create( m_mockFocusManager, m_mockExceptionSender, metricRecorder, nullptr, m_mockContextManager); ASSERT_EQ(alexaPresentation, nullptr); } /** * Tests unknown Directive. Expect that the sendExceptionEncountered and setFailed will be called. */ TEST_F(AlexaPresentationTest, testUnknownDirective) { // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(NAMESPACE1, UNKNOWN_DIRECTIVE, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, "", attachmentManager, ""); EXPECT_CALL(*m_mockExceptionSender, sendExceptionEncountered(_, _, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setFailed(_)).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); } /** * Verify the request sent to AVS is as expected. */ static void verifySendMessage( std::shared_ptr<avsCommon::avs::MessageRequest> request, const std::string expectedEventName, const std::string expectedPayload, const std::string expectedNameSpace) { rapidjson::Document document; document.Parse(request->getJsonContent()); auto event = document.FindMember(MESSAGE_EVENT_KEY); EXPECT_NE(event, document.MemberEnd()); auto header = event->value.FindMember(MESSAGE_HEADER_KEY); EXPECT_NE(header, event->value.MemberEnd()); auto payload = event->value.FindMember(MESSAGE_PAYLOAD_KEY); EXPECT_NE(payload, event->value.MemberEnd()); EXPECT_EQ(header->value.FindMember(MESSAGE_NAMESPACE_KEY)->value.GetString(), expectedNameSpace); EXPECT_EQ(header->value.FindMember(MESSAGE_NAME_KEY)->value.GetString(), expectedEventName); EXPECT_NE(header->value.FindMember(MESSAGE_ID)->value.GetString(), ""); std::string messagePayload; avsCommon::utils::json::jsonUtils::convertToValue(payload->value, &messagePayload); EXPECT_EQ(messagePayload, expectedPayload); EXPECT_EQ(request->attachmentReadersCount(), 0); conditionVariable.notify_all(); } /** * Tests when a malformed RenderDocument Directive (without presentationToken) is received. Expect that the * sendExceptionEncountered and setFailed will be called. */ TEST_F(AlexaPresentationTest, testMalformedRenderDocumentDirective) { // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD_MALFORMED, attachmentManager, ""); EXPECT_CALL(*m_mockExceptionSender, sendExceptionEncountered(_, _, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setFailed(_)).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); } /** * Tests when a malformed RenderDocument Directive (without document) is received. Expect that the * sendExceptionEncountered and setFailed will be called. */ TEST_F(AlexaPresentationTest, testMalformedRenderDocumentDirective2) { // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD_MALFORMED_2, attachmentManager, ""); EXPECT_CALL(*m_mockExceptionSender, sendExceptionEncountered(_, _, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setFailed(_)).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); } /** * Tests when a malformed ExecuteCommands Directive is received (without presentationToken). Expect that the * sendExceptionEncountered and setFailed will be called. */ TEST_F(AlexaPresentationTest, testMalformedExecuteCommandDirective) { // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(COMMAND.nameSpace, COMMAND.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, EXECUTE_COMMAND_PAYLOAD_MALFORMED, attachmentManager, ""); EXPECT_CALL(*m_mockExceptionSender, sendExceptionEncountered(_, _, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setFailed(_)).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); } /** * Tests when a malformed ExecuteCommands Directive (without commands) is received. Expect that the * sendExceptionEncountered and setFailed will be called. */ TEST_F(AlexaPresentationTest, testMalformedExecuteCommandDirective2) { // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(COMMAND.nameSpace, COMMAND.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, EXECUTE_COMMAND_PAYLOAD_MALFORMED_2, attachmentManager, ""); EXPECT_CALL(*m_mockExceptionSender, sendExceptionEncountered(_, _, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setFailed(_)).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); } /** * Tests when a ExecuteCommands Directive is received after an APL card id displayed. In this case the * ExecuteCommand should fail as presentationToken(APL rendered) != presentationToken(ExecuteCommand). */ TEST_F(AlexaPresentationTest, testExecuteCommandAfterMismatchedAPLCard) { avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD_2, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD_2, "APL_TOKEN_2", WINDOW_ID)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN_2", true, ""); m_executor->waitForSubmittedTasks(); m_mockDirectiveHandlerResult = make_unique<StrictMock<smartScreenSDKInterfaces::test::MockDirectiveHandlerResult>>(); // Create Directive. auto attachmentManager1 = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader1 = std::make_shared<AVSMessageHeader>(COMMAND.nameSpace, COMMAND.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive1 = AVSDirective::create("", avsMessageHeader1, EXECUTE_COMMAND_PAYLOAD, attachmentManager1, ""); EXPECT_CALL(*m_mockExceptionSender, sendExceptionEncountered(_, _, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setFailed(_)).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive1, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_AlexaPresentation->processExecuteCommandsResult(MESSAGE_ID, true, ""); m_executor->waitForSubmittedTasks(); } /** * Tests when a ExecuteCommands Directive is received after displaying an APL card with matching presentationToken. * The command should be successful. * * @note DISABLED for now. Following up JIRA https://issues.labcollab.net/browse/ARC-871 */ TEST_F(AlexaPresentationTest, testExecuteCommandAfterRightAPL) { avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); // Create Directive. auto attachmentManager1 = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader1 = std::make_shared<AVSMessageHeader>(COMMAND.nameSpace, COMMAND.name, MESSAGE_ID_2); std::shared_ptr<AVSDirective> directive1 = AVSDirective::create("", avsMessageHeader1, EXECUTE_COMMAND_PAYLOAD, attachmentManager1, ""); m_mockDirectiveHandlerResult = make_unique<StrictMock<smartScreenSDKInterfaces::test::MockDirectiveHandlerResult>>(); EXPECT_CALL(*m_mockGui, executeCommands(EXECUTE_COMMAND_PAYLOAD, _)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive1, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID_2); m_AlexaPresentation->processExecuteCommandsResult(MESSAGE_ID_2, true, ""); m_executor->waitForSubmittedTasks(); } /** * Tests that if clearCard() is called and the card being cleared is APL, then * 1. clearDocument() will not be called. * 2. DocumentDismissed event will be sent to AVS * 3. When provideState is called, we do not call the visual context provider for context since the document has been * clear */ TEST_F(AlexaPresentationTest, testAPLClearCard) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)); EXPECT_CALL(*m_mockGui, clearDocument()).Times(1); // Expect a call to getContext as part of sending APL_DISMISSED event. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); EXPECT_CALL(*m_mockFocusManager, releaseChannel(_, _)).Times(Exactly(1)).WillOnce(InvokeWithoutArgs([this] { auto releaseChannelSuccess = std::make_shared<std::promise<bool>>(); std::future<bool> returnValue = releaseChannelSuccess->get_future(); m_AlexaPresentation->onFocusChanged( avsCommon::avs::FocusState::NONE, alexaClientSDK::avsCommon::avs::MixingBehavior::UNDEFINED); releaseChannelSuccess->set_value(true); return returnValue; })); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, DOCUMENT_DISMISSED_EVENT, EXPECTED_DOCUMENT_DISMISSED_PAYLOAD, NAMESPACE1); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); EXPECT_CALL(*m_mockContextManager, setState(_, _, _, _)).Times(Exactly((1))); // Make sure that this is not called, because the last APL has been cleared EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Exactly(0)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->clearCard(); m_AlexaPresentation->provideState(DOCUMENT, STATE_REQUEST_TOKEN); m_executor->waitForSubmittedTasks(); // wait for first call of getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); } /** * Tests that when APL is dismissed for timeout, we send Dismissed. * When this timeout is followed by another card, we don't send Dismissed again * We do not ask for visual context either */ TEST_F(AlexaPresentationTest, testAPLTimeout) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)) .WillRepeatedly(InvokeWithoutArgs([this] { m_AlexaPresentation->recordRenderComplete(); })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); EXPECT_CALL(*m_mockGui, clearDocument()).Times(Exactly(1)); EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)); EXPECT_CALL(*m_mockFocusManager, releaseChannel(_, _)).Times(Exactly(1)).WillOnce(InvokeWithoutArgs([this] { auto releaseChannelSuccess = std::make_shared<std::promise<bool>>(); std::future<bool> returnValue = releaseChannelSuccess->get_future(); m_AlexaPresentation->onFocusChanged( avsCommon::avs::FocusState::NONE, alexaClientSDK::avsCommon::avs::MixingBehavior::UNDEFINED); releaseChannelSuccess->set_value(true); return returnValue; })); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, DOCUMENT_DISMISSED_EVENT, EXPECTED_DOCUMENT_DISMISSED_PAYLOAD, NAMESPACE1); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->onDialogUXStateChanged( avsCommon::sdkInterfaces::DialogUXStateObserverInterface::DialogUXState::IDLE); m_executor->waitForSubmittedTasks(); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); auto attachmentManager2 = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader2 = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID_2); std::shared_ptr<AVSDirective> directive2 = AVSDirective::create("", avsMessageHeader2, DOCUMENT_APL_PAYLOAD_2, attachmentManager2, ""); // Re-initializing the uniqe pointer after moved above. m_mockDirectiveHandlerResult = make_unique<StrictMock<smartScreenSDKInterfaces::test::MockDirectiveHandlerResult>>(); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD_2, "APL_TOKEN_2", WINDOW_ID)) .Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); EXPECT_CALL(*m_mockGui, clearDocument()).Times(Exactly(1)); EXPECT_CALL(*m_mockFocusManager, releaseChannel(_, _)).Times(Exactly(1)).WillOnce(InvokeWithoutArgs([this] { auto releaseChannelSuccess = std::make_shared<std::promise<bool>>(); std::future<bool> returnValue = releaseChannelSuccess->get_future(); m_AlexaPresentation->onFocusChanged( avsCommon::avs::FocusState::NONE, alexaClientSDK::avsCommon::avs::MixingBehavior::UNDEFINED); releaseChannelSuccess->set_value(true); return returnValue; })); EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); EXPECT_CALL(*m_mockContextManager, setState(_, _, _, _)).Times(Exactly((1))); // Make sure that this is not called, because the last APL has been cleared EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Exactly(0)); m_AlexaPresentation->provideState(DOCUMENT, STATE_REQUEST_TOKEN); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive2, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID_2); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN_2", true, ""); m_executor->waitForSubmittedTasks(); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); } /** * Tests that APL is not dismissed while there are active interaction reported. */ TEST_F(AlexaPresentationTest, testAPLIdleRespectsGUIActive) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); EXPECT_CALL(*m_mockGui, clearDocument()).Times(0); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processActivityEvent("TEST", smartScreenSDKInterfaces::ActivityEvent::ACTIVATED); m_AlexaPresentation->onDialogUXStateChanged( avsCommon::sdkInterfaces::DialogUXStateObserverInterface::DialogUXState::IDLE); m_executor->waitForSubmittedTasks(); } /** * Tests that APL is dismissed as usual when there are no interaction reported. */ TEST_F(AlexaPresentationTest, testAPLIdleRespectsGUIInactive) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)) .WillRepeatedly(InvokeWithoutArgs([this] { m_AlexaPresentation->recordRenderComplete(); })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); EXPECT_CALL(*m_mockGui, clearDocument()).Times(1); EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)); EXPECT_CALL(*m_mockFocusManager, releaseChannel(_, _)).Times(Exactly(1)).WillOnce(InvokeWithoutArgs([this] { auto releaseChannelSuccess = std::make_shared<std::promise<bool>>(); std::future<bool> returnValue = releaseChannelSuccess->get_future(); m_AlexaPresentation->onFocusChanged( avsCommon::avs::FocusState::NONE, alexaClientSDK::avsCommon::avs::MixingBehavior::UNDEFINED); releaseChannelSuccess->set_value(true); return returnValue; })); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, DOCUMENT_DISMISSED_EVENT, EXPECTED_DOCUMENT_DISMISSED_PAYLOAD, NAMESPACE1); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processActivityEvent("TEST", smartScreenSDKInterfaces::ActivityEvent::ACTIVATED); m_AlexaPresentation->processActivityEvent("TEST", smartScreenSDKInterfaces::ActivityEvent::DEACTIVATED); m_executor->waitForSubmittedTasks(); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); } /** * Tests that APL is not dismissed on DEACTIVATED event when DialogUX is on. */ TEST_F(AlexaPresentationTest, testAPLIdleRespectsDialogUXWhenGUIInactive) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); EXPECT_CALL(*m_mockGui, clearDocument()).Times(0); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->onDialogUXStateChanged( avsCommon::sdkInterfaces::DialogUXStateObserverInterface::DialogUXState::SPEAKING); m_AlexaPresentation->processActivityEvent("TEST", smartScreenSDKInterfaces::ActivityEvent::DEACTIVATED); m_executor->waitForSubmittedTasks(); } /** * Tests that when APL is dismissed by another card, we send DocumentDismissed * for the 1st card with the first token and for the 2nd card with the 2nd token */ TEST_F(AlexaPresentationTest, testAPLFollowedByAPL) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(1) .WillRepeatedly(InvokeWithoutArgs([this] { m_AlexaPresentation->recordRenderComplete(); })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(AtLeast(1)); EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); // Create another directive auto attachmentManager2 = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader2 = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID_2); std::shared_ptr<AVSDirective> directive2 = AVSDirective::create("", avsMessageHeader2, DOCUMENT_APL_PAYLOAD_2, attachmentManager, ""); // Re-initializing the uniqe pointer after moved above. m_mockDirectiveHandlerResult = make_unique<StrictMock<smartScreenSDKInterfaces::test::MockDirectiveHandlerResult>>(); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD_2, "APL_TOKEN_2", WINDOW_ID)).Times(1) .WillRepeatedly(InvokeWithoutArgs([this] { m_AlexaPresentation->recordRenderComplete(); })); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(AtLeast(1)); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, DOCUMENT_DISMISSED_EVENT, EXPECTED_DOCUMENT_DISMISSED_PAYLOAD, NAMESPACE1); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive2, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID_2); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN_2", true, ""); m_executor->waitForSubmittedTasks(); // clearDocument() is going to be called for the 2nd APL card because it's cleared by timeout. EXPECT_CALL(*m_mockGui, clearDocument()).Times(Exactly(1)); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); auto verifyEvent2 = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, DOCUMENT_DISMISSED_EVENT, EXPECTED_DOCUMENT_DISMISSED_PAYLOAD_2, NAMESPACE1); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent2)); m_AlexaPresentation->onDialogUXStateChanged( avsCommon::sdkInterfaces::DialogUXStateObserverInterface::DialogUXState::IDLE); m_executor->waitForSubmittedTasks(); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); conditionVariable.wait_for(lk, TIMEOUT); } TEST_F(AlexaPresentationTest, testSendUserEvent) { std::unique_lock<std::mutex> exitLock(m_mutex); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, USER_EVENT_EVENT, SAMPLE_USER_EVENT_PAYLOAD, NAMESPACE2); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); m_AlexaPresentation->sendUserEvent(SAMPLE_USER_EVENT_PAYLOAD); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); } TEST_F(AlexaPresentationTest, testIndexListDataSourceFetchRequestEvent) { std::unique_lock<std::mutex> exitLock(m_mutex); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, LOAD_INDEX_LIST_DATA, SAMPLE_INDEX_DATA_SOURCE_FETCH_REQUEST, NAMESPACE2); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); m_AlexaPresentation->sendDataSourceFetchRequestEvent(DYNAMIC_INDEX_LIST, SAMPLE_INDEX_DATA_SOURCE_FETCH_REQUEST); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); } TEST_F(AlexaPresentationTest, testTokenListDataSourceFetchRequestEvent) { std::unique_lock<std::mutex> exitLock(m_mutex); auto verifyEvent = [](std::shared_ptr<avsCommon::avs::MessageRequest> request) { verifySendMessage(request, LOAD_TOKEN_LIST_DATA, SAMPLE_TOKEN_DATA_SOURCE_FETCH_REQUEST, NAMESPACE2); }; EXPECT_CALL(*m_mockMessageSender, sendMessage(_)).Times(Exactly(1)).WillOnce(Invoke(verifyEvent)); // Expect a call to getContext. EXPECT_CALL(*m_mockContextManager, getContext(_, _, _)) .WillOnce(Invoke([this]( std::shared_ptr<ContextRequesterInterface> contextRequester, const std::string&, const std::chrono::milliseconds&) { m_contextTrigger.notify_one(); return 0; })); m_AlexaPresentation->sendDataSourceFetchRequestEvent(DYNAMIC_TOKEN_LIST, SAMPLE_TOKEN_DATA_SOURCE_FETCH_REQUEST); // wait for getContext m_contextTrigger.wait_for(exitLock, TIMEOUT); m_AlexaPresentation->onContextAvailable(""); std::unique_lock<std::mutex> lk(m); conditionVariable.wait(lk); } TEST_F(AlexaPresentationTest, testAPLProactiveStateReportNotSentIfNotRendering) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Make sure that this is not called, because no APL is being presented EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Exactly(0)); m_contextTrigger.wait_for(exitLock, TIMEOUT); m_executor->waitForSubmittedTasks(); } TEST_F(AlexaPresentationTest, testAPLProactiveStateReportSentIfRendering) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)) .WillRepeatedly(InvokeWithoutArgs([this] { m_AlexaPresentation->recordRenderComplete(); })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); // At least one state request will come as a result of rendering, depending on timing a second one may be made // by the state reporter EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Between(1, 2)); m_AlexaPresentation->provideState(DOCUMENT, STATE_REQUEST_TOKEN); m_executor->waitForSubmittedTasks(); // Expect a state reponse for the original provideState request EXPECT_CALL(*m_mockContextManager, provideStateResponse(_, _, _)).Times(Exactly(1)); m_AlexaPresentation->onVisualContextAvailable(STATE_REQUEST_TOKEN, "{ 1 }"); m_executor->waitForSubmittedTasks(); EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Exactly(1)); EXPECT_CALL(*m_mockContextManager, provideStateResponse(_, _, _)).Times(Exactly(0)); EXPECT_CALL(*m_mockContextManager, reportStateChange(_, _, _)).Times(Exactly(1)); // Now wait, and we should get a proactive state change following a different request m_contextTrigger.wait_for(exitLock, std::chrono::milliseconds(400)); m_AlexaPresentation->onVisualContextAvailable(PROACTIVE_STATE_REQUEST_TOKEN, "{ 2 }"); m_executor->waitForSubmittedTasks(); } TEST_F(AlexaPresentationTest, testAPLProactiveStateReportNotSentIfStateUnchanged) { std::unique_lock<std::mutex> exitLock(m_mutex); avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)) .WillRepeatedly(InvokeWithoutArgs([this] { m_AlexaPresentation->recordRenderComplete(); })); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); // At least one state request will come as a result of rendering, depending on timing a second one may be made // by the state reporter EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Between(1, 2)); m_AlexaPresentation->provideState(DOCUMENT, STATE_REQUEST_TOKEN); m_executor->waitForSubmittedTasks(); // Expect a state reponse for the original provideState request EXPECT_CALL(*m_mockContextManager, provideStateResponse(_, _, _)).Times(Exactly(1)); m_AlexaPresentation->onVisualContextAvailable(STATE_REQUEST_TOKEN, "{ 1 }"); m_executor->waitForSubmittedTasks(); EXPECT_CALL(*m_mockVisualStateProvider, provideState(_)).Times(Exactly(1)); EXPECT_CALL(*m_mockContextManager, provideStateResponse(_, _, _)).Times(Exactly(0)); EXPECT_CALL(*m_mockContextManager, reportStateChange(_, _, _)).Times(Exactly(0)); // Now wait, and we should get a proactive state change following a different request m_contextTrigger.wait_for(exitLock, std::chrono::milliseconds(400)); m_AlexaPresentation->onVisualContextAvailable(PROACTIVE_STATE_REQUEST_TOKEN, "{ 1 }"); m_executor->waitForSubmittedTasks(); } TEST_F(AlexaPresentationTest, testAPLProactiveStateReportNotSentIfRenderingNotComplete) { avsCommon::utils::logger::getConsoleLogger()->setLevel(avsCommon::utils::logger::Level::DEBUG9); // Create Directive. auto attachmentManager = std::make_shared<StrictMock<smartScreenSDKInterfaces::test::MockAttachmentManager>>(); auto avsMessageHeader = std::make_shared<AVSMessageHeader>(DOCUMENT.nameSpace, DOCUMENT.name, MESSAGE_ID); std::shared_ptr<AVSDirective> directive = AVSDirective::create("", avsMessageHeader, DOCUMENT_APL_PAYLOAD, attachmentManager, ""); EXPECT_CALL(*m_mockGui, renderDocument(DOCUMENT_APL_PAYLOAD, "APL_TOKEN", WINDOW_ID)).Times(Exactly(1)); EXPECT_CALL(*m_mockDirectiveHandlerResult, setCompleted()).Times(Exactly(1)); m_AlexaPresentation->CapabilityAgent::preHandleDirective(directive, std::move(m_mockDirectiveHandlerResult)); m_AlexaPresentation->CapabilityAgent::handleDirective(MESSAGE_ID); m_executor->waitForSubmittedTasks(); m_AlexaPresentation->processRenderDocumentResult("APL_TOKEN", true, ""); m_executor->waitForSubmittedTasks(); // At least one state request will come as a result of rendering, depending on timing a second one may be made // by the state reporter EXPECT_CALL(*m_mockVisualStateProvider, provideState(STATE_REQUEST_TOKEN)).Times(Exactly(1)); EXPECT_CALL(*m_mockVisualStateProvider, provideState(PROACTIVE_STATE_REQUEST_TOKEN)).Times(Exactly(0)); m_AlexaPresentation->provideState(DOCUMENT, STATE_REQUEST_TOKEN); m_executor->waitForSubmittedTasks(); // Expect a state reponse for the original provideState request EXPECT_CALL(*m_mockContextManager, provideStateResponse(_, _, STATE_REQUEST_TOKEN)).Times(Exactly(1)); m_AlexaPresentation->onVisualContextAvailable(STATE_REQUEST_TOKEN, "{ 1 }"); m_executor->waitForSubmittedTasks(); } } // namespace test } // namespace alexaPresentation } // namespace smartScreenCapabilityAgents } // namespace alexaSmartScreenSDK
; void dzx7_standard(void *src, void *dst) SECTION code_compress_zx7 PUBLIC _dzx7_standard EXTERN asm_dzx7_standard _dzx7_standard: pop af pop hl pop de push de push hl push af jp asm_dzx7_standard
; ; Put character to console ; ; fputc_cons(char c) ; ; ; $Id: fputc_cons.asm,v 1.6 2016-05-15 20:15:46 dom Exp $ ; SECTION code_clib PUBLIC fputc_cons_native ; PUBLIC _fputc_cons INCLUDE "target/test/def/test_cmds.def" .fputc_cons_native ld hl,2 add hl,sp ld l,(hl) ld h,0 ld a,CMD_PRINTCHAR call SYSCALL ret
// init @256 //SP = 256 D=A @SP M=D @Sys.init //call Sys.init 0 which can't be recurisive and has no return command 0;JMP (__Sys.init$return__) {infloop} @LCL //TODO: @ARG //TODO: @16383 //TODO: heap D=A @THIS M=D @THAT M=D @{main} //TODO: main 0;JMP //Arithmwtic & Logic @SP //pop arg2 M=M-1 A=M // A now at the top of the stack M=-M //neg M=!M //not @SP M=M+1 D=M //arg2 @SP //pop arg1 M=M-1 A=M D=D+M //add D=M-D //sub D=D&M //and D=D|M //or D=M-D //D=M-D //eq @eq_true_{eq_true} D;JEQ D=0 //eq_false @eq_end_{eq_end} 0;JMP (eq_true_{eq_true}) D=-1 (eq_end_{eq_end}) //D=M-D //gt @gt_true_{gt_true} D;JGT D=0 //gt_false @gt_end_{gt_end} 0;JMP (gt_true_{gt_true}) D=-1 (gt_end_{gt_end}) //D=M-D //lt @lt_true_{lt_true} D;JLT D=0 //gt_false @lt_end_{lt_end} 0;JMP (lt_true_{lt_true}) D=-1 (lt_end_{lt_end}) @SP //push end A=M M=D @SP M=M+1 //Push & Pop //push segment index //argument @ARG\nD=M\n@{index}\nA=D+A\nD=M //local @LCL\nD=M\n@{index}\nA=D+A\nD=M //static @{filename}.{index}\nD=M //constant @{index}\nD=A //this @THIS\nD=M\n@{index}\nA=D+A\nD=M //that @THAT\nD=M\n@{index}\nA=D+A\nD=M //pointer 0 1 @{index+3}\nD=M //%if 0% @THIS D=M %elif 1% @THAT D=M //temp @{index+5}\nD=M %s @SP A=M M=D @SP M=M+1 //pop segment index //argument @ARG\nD=M\n@{index}\nD=D+A\n@R15\nM=D //local @LCL\nD=M\n@{index}\nD=D+A\n@R15\nM=D //static @{filename}.{index}\nD=A\n@R15\nM=D //constant @{index}\nD=A //meaningless //this @THIS\nD=M\n@{index}\nD=D+A\n@R15\nM=D //that @THAT\nD=M\n@{index}\nD=D+A\n@R15\nM=D //pointer 0 1 @{index+3}\nD=A\n@R15\nM=D //%if 0% @THIS D=M %elif 1% @THAT D=M //temp @{index+5}\nD=A\n@R15\nM=D %s @SP M=M-1 A=M D=M @R15 A=M M=D //label label ({functionname}${label}) //goto label @{functionname}${label} 0;JMP //if-goto label @SP //pop M=M-1 A=M D=M @{functionname}${label} D;JNE //true : -1 //call f nArgs @__{functionname}$return{cnt_return}__ D=A {push} @LCL //saved D=M {push} @ARG D=M {push} @THIS D=M {push} @THAT D=M {push} @SP D=M @{nArgs} D=D-A @5 //5 push-es for saving D=D-A @ARG M=D //ARG = SP - n - 5 @SP D=M @LCL //local = SP M=D @{functionname} 0;JMP (__{functionname}$return{cnt_return}__) //function f kVars ({functionname}) {for i in range(kVars):} //initialize the local variables D=0 {push} //return @LCL D=M @R14 M=D //FRAME = LCL @5 A=D-A D=M //D = *(FRAME-5) @R15 //RET M=D //RET = *(FRAME-5) {pop} //--> D @ARG A=M M=D //*ARG = pop() @ARG D=M+1 @SP M=D //SP = ARG + 1 {frame%(1,"THAT")} //THAT = *(FRAME-1) {frame%(2,"THIS")} //THIS = *(FRAME-2) {frame%(3,"ARG")} //ARG = *(FRAME-3) {frame%(4,"LCL")} //LCL = *(FRAME-4) @R15 A=M 0;JMP // goto return //pop @SP //pop --> D M=M-1 A=M D=M //push @SP //push <-- D A=M M=D @SP M=M+1 //frame @R14 //%s = *(Frame - %d) D=M @%d A=D-A D=M @%s M=D
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r8 push %rax push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1220b, %rdx nop nop cmp %rbx, %rbx movb $0x61, (%rdx) and %rax, %rax lea addresses_D_ht+0x538b, %rdi nop nop nop nop and %r10, %r10 mov $0x6162636465666768, %rbp movq %rbp, %xmm4 and $0xffffffffffffffc0, %rdi movntdq %xmm4, (%rdi) nop xor %rdi, %rdi lea addresses_WT_ht+0x7b1d, %r8 nop nop nop xor $51614, %r10 mov $0x6162636465666768, %rdx movq %rdx, %xmm0 movups %xmm0, (%r8) nop nop nop xor %rdx, %rdx lea addresses_UC_ht+0x17c0b, %rdx nop nop nop nop nop dec %r8 movw $0x6162, (%rdx) nop nop nop mfence lea addresses_UC_ht+0x17b0b, %rsi lea addresses_WC_ht+0xa58b, %rdi and %rbp, %rbp mov $85, %rcx rep movsl inc %rsi lea addresses_UC_ht+0x119cb, %rax nop nop sub %r10, %r10 mov $0x6162636465666768, %rbp movq %rbp, %xmm5 movups %xmm5, (%rax) nop nop xor %rsi, %rsi lea addresses_WT_ht+0xe1b7, %rdi nop nop nop nop xor %rbp, %rbp movw $0x6162, (%rdi) nop nop and %rcx, %rcx lea addresses_D_ht+0x870b, %rax nop nop sub %rbp, %rbp movw $0x6162, (%rax) nop nop nop sub $3576, %rdx lea addresses_A_ht+0x1670b, %r10 nop nop nop nop cmp $20851, %rbx mov $0x6162636465666768, %rdx movq %rdx, (%r10) nop nop nop nop nop add %rdi, %rdi lea addresses_D_ht+0x17c23, %rcx nop nop nop and %rsi, %rsi mov $0x6162636465666768, %rdi movq %rdi, (%rcx) nop nop nop sub %rax, %rax pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r8 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %r15 push %r9 push %rax // Faulty Load lea addresses_PSE+0x1670b, %r9 nop nop nop cmp $4567, %r10 movaps (%r9), %xmm6 vpextrq $1, %xmm6, %r15 lea oracles, %r10 and $0xff, %r15 shlq $12, %r15 mov (%r10,%r15,1), %r15 pop %rax pop %r9 pop %r15 pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': True, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': True, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}} {'c6': 1, '00': 21828} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
.include "LKS/MC_OAM.asm" .include "LKS/MC_Joypad.asm" .include "LKS/MC_Printf.asm" .include "LKS/MC_Load.asm" .include "LKS/MC_Clear.asm" .include "LKS/MC_BG.asm" .include "LKS/MC_DMA.asm" .include "LKS/MC_PAL.asm" .include "LKS/variable.asm"
/** * \file * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "CreateThermoMechanicalPhaseFieldProcess.h" #include <cassert> #include "MaterialLib/SolidModels/CreateConstitutiveRelation.h" #include "MaterialLib/SolidModels/MechanicsBase.h" #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" #include "ThermoMechanicalPhaseFieldProcess.h" #include "ThermoMechanicalPhaseFieldProcessData.h" namespace ProcessLib { namespace ThermoMechanicalPhaseField { template <int DisplacementDim> std::unique_ptr<Process> createThermoMechanicalPhaseFieldProcess( std::string name, MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<ProcessVariable> const& variables, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, boost::optional<ParameterLib::CoordinateSystem> const& local_coordinate_system, unsigned const integration_order, BaseLib::ConfigTree const& config) { //! \ogs_file_param{prj__processes__process__type} config.checkConfigParameter("type", "THERMO_MECHANICAL_PHASE_FIELD"); DBUG("Create ThermoMechanicalPhaseFieldProcess."); INFO( "Solve the coupling with the staggered scheme," "which is the only option for TM-Phasefield in the current code"); // Process variable. //! \ogs_file_param{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__process_variables} auto const pv_config = config.getConfigSubtree("process_variables"); std::vector<std::vector<std::reference_wrapper<ProcessVariable>>> process_variables; int heat_conduction_process_id = 0; int mechanics_related_process_id = 1; int phase_field_process_id = 2; auto process_variable_T = findProcessVariables( variables, pv_config, {//! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__process_variables__temperature} "temperature"}); process_variables.push_back(std::move(process_variable_T)); ProcessVariable* variable_T = &process_variables[process_variables.size() - 1][0].get(); auto process_variable_u = findProcessVariables( variables, pv_config, {//! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__process_variables__displacement} "displacement"}); process_variables.push_back(std::move(process_variable_u)); ProcessVariable* variable_u = &process_variables[process_variables.size() - 1][0].get(); auto process_variable_ph = findProcessVariables( variables, pv_config, {//! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__process_variables__phasefield} "phasefield"}); process_variables.push_back(std::move(process_variable_ph)); ProcessVariable* variable_ph = &process_variables[process_variables.size() - 1][0].get(); DBUG("Associate displacement with process variable '{:s}'.", variable_u->getName()); if (variable_u->getNumberOfComponents() != DisplacementDim) { OGS_FATAL( "Number of components of the process variable '{:s}' is different " "from the displacement dimension: got {:d}, expected {:d}", variable_u->getName(), variable_u->getNumberOfComponents(), DisplacementDim); } DBUG("Associate phase field with process variable '{:s}'.", variable_ph->getName()); if (variable_ph->getNumberOfComponents() != 1) { OGS_FATAL( "Phasefield process variable '{:s}' is not a scalar variable but " "has " "{:d} components.", variable_ph->getName(), variable_ph->getNumberOfComponents()); } DBUG("Associate temperature with process variable '{:s}'.", variable_T->getName()); if (variable_T->getNumberOfComponents() != 1) { OGS_FATAL( "Temperature process variable '{:s}' is not a scalar variable but " "has " "{:d} components.", variable_T->getName(), variable_T->getNumberOfComponents()); } auto solid_constitutive_relations = MaterialLib::Solids::createConstitutiveRelations<DisplacementDim>( parameters, local_coordinate_system, config); auto const phasefield_parameters_config = //! \ogs_file_param{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__phasefield_parameters} config.getConfigSubtree("phasefield_parameters"); auto const thermal_parameters_config = //! \ogs_file_param{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters} config.getConfigSubtree("thermal_parameters"); // Residual stiffness auto& residual_stiffness = ParameterLib::findParameter<double>( phasefield_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__phasefield_parameters__residual_stiffness} "residual_stiffness", parameters, 1, &mesh); DBUG("Use '{:s}' as residual stiffness.", residual_stiffness.name); // Crack resistance auto& crack_resistance = ParameterLib::findParameter<double>( phasefield_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__phasefield_parameters__crack_resistance} "crack_resistance", parameters, 1, &mesh); DBUG("Use '{:s}' as crack resistance.", crack_resistance.name); // Crack length scale auto& crack_length_scale = ParameterLib::findParameter<double>( phasefield_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__phasefield_parameters__crack_length_scale} "crack_length_scale", parameters, 1, &mesh); DBUG("Use '{:s}' as crack length scale.", crack_length_scale.name); // Kinetic coefficient auto& kinetic_coefficient = ParameterLib::findParameter<double>( phasefield_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__phasefield_parameters__kinetic_coefficient} "kinetic_coefficient", parameters, 1, &mesh); DBUG("Use '{:s}' as kinetic coefficient.", kinetic_coefficient.name); // Solid density auto& solid_density = ParameterLib::findParameter<double>( config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__reference_solid_density} "solid_density", parameters, 1, &mesh); DBUG("Use '{:s}' as solid density parameter.", solid_density.name); // Linear thermal expansion coefficient auto& linear_thermal_expansion_coefficient = ParameterLib::findParameter< double>( thermal_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters__linear_thermal_expansion_coefficient} "linear_thermal_expansion_coefficient", parameters, 1, &mesh); DBUG("Use '{:s}' as linear thermal expansion coefficient.", linear_thermal_expansion_coefficient.name); // Specific heat capacity auto& specific_heat_capacity = ParameterLib::findParameter<double>( thermal_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters__specific_heat_capacity} "specific_heat_capacity", parameters, 1, &mesh); DBUG("Use '{:s}' as specific heat capacity.", specific_heat_capacity.name); // Thermal conductivity auto& thermal_conductivity = ParameterLib::findParameter<double>( thermal_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters__thermal_conductivity} "thermal_conductivity", parameters, 1, &mesh); DBUG("Use '{:s}' as thermal conductivity parameter.", thermal_conductivity.name); // Residual thermal conductivity auto& residual_thermal_conductivity = ParameterLib::findParameter<double>( thermal_parameters_config, //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters__residual_thermal_conductivity} "residual_thermal_conductivity", parameters, 1, &mesh); DBUG("Use '{:s}' as residual thermal conductivity parameter.", residual_thermal_conductivity.name); // Reference temperature const auto reference_temperature = //! \ogs_file_param{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__reference_temperature} config.getConfigParameter<double>("reference_temperature"); // Specific body force Eigen::Matrix<double, DisplacementDim, 1> specific_body_force; { std::vector<double> const b = //! \ogs_file_param{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__specific_body_force} config.getConfigParameter<std::vector<double>>( "specific_body_force"); if (specific_body_force.size() != DisplacementDim) { OGS_FATAL( "The size of the specific body force vector does not match the " "displacement dimension. Vector size is {:d}, displacement " "dimension is {:d}", specific_body_force.size(), DisplacementDim); } std::copy_n(b.data(), b.size(), specific_body_force.data()); } ThermoMechanicalPhaseFieldProcessData<DisplacementDim> process_data{ materialIDs(mesh), std::move(solid_constitutive_relations), residual_stiffness, crack_resistance, crack_length_scale, kinetic_coefficient, solid_density, linear_thermal_expansion_coefficient, specific_heat_capacity, thermal_conductivity, residual_thermal_conductivity, specific_body_force, reference_temperature}; SecondaryVariableCollection secondary_variables; ProcessLib::createSecondaryVariables(config, secondary_variables); return std::make_unique<ThermoMechanicalPhaseFieldProcess<DisplacementDim>>( std::move(name), mesh, std::move(jacobian_assembler), parameters, integration_order, std::move(process_variables), std::move(process_data), std::move(secondary_variables), mechanics_related_process_id, phase_field_process_id, heat_conduction_process_id); } template std::unique_ptr<Process> createThermoMechanicalPhaseFieldProcess<2>( std::string name, MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<ProcessVariable> const& variables, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, boost::optional<ParameterLib::CoordinateSystem> const& local_coordinate_system, unsigned const integration_order, BaseLib::ConfigTree const& config); template std::unique_ptr<Process> createThermoMechanicalPhaseFieldProcess<3>( std::string name, MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<ProcessVariable> const& variables, std::vector<std::unique_ptr<ParameterLib::ParameterBase>> const& parameters, boost::optional<ParameterLib::CoordinateSystem> const& local_coordinate_system, unsigned const integration_order, BaseLib::ConfigTree const& config); } // namespace ThermoMechanicalPhaseField } // namespace ProcessLib
; Hyperion 64-Bit container.exe include 'image_base.inc' include 'main_prolog.inc' ;format PE64 ... entry start include '..\..\..\Fasm\INCLUDE\win64a.inc' include 'pe.inc' ;automatically generated by hyperion cpp stub include 'key_size.inc' include 'infile_size.inc' include 'image_size.inc' ;--- SIZE_DATA_SECTION_NAME equ 5 SIZE_CHECKSUM equ 4 ;this contains the decrypted and loaded executable section '.bss' data readable writeable decrypted_infile: db IMAGE_SIZE dup (?) ;-------------------------------------------------- ;this contains the encrypted exe section '.data' data readable writeable encrypted_infile: include 'infile_array.inc' ;-------------------------------------------------- section '.text' code readable executable ;automatically generated by hyperion cpp stub include 'logfile_select.asm' include 'decryption_payload.asm' ;pe loader functions include 'loadexecutable.asm' ;--- start: sub rsp,8 fastcall MainMethod test rax,rax jz the_end_my_friend ;file was loaded, execute it add rsp,8 jmp rax the_end_my_friend: invoke ExitProcess,0 proc MainMethod uses rbx local str1[256]:BYTE ;create logfile and write initial message into it initLogFile main_exit ;decrypt exe in data section fastcall decryptExecutable, encrypted_infile test rax,rax jz main_exiterror ;load the executable at its image base ;(this will overwrite current MZ header and bss section) fastcall loadExecutable, encrypted_infile test rax,rax jz main_exiterror ;start program execution mov rdx,IMAGE_BASE xor rax,rax mov eax,[rdx+IMAGE_DOS_HEADER.e_lfanew] add rax,rdx add rax,4 ;image file header now in eax add rax,sizeof.IMAGE_FILE_HEADER xor rdx,rdx mov edx,[rax+IMAGE_OPTIONAL_HEADER64.AddressOfEntryPoint] mov rax,IMAGE_BASE add rdx,rax ;entry point of original exe is now in rbx mov rbx,rdx ;finished without errors main_exitsuccess: writeNewLineToLog main_exit createStringDone str1 writeLog rax, main_exit mov rax,rbx jmp main_exit ;finished with errors after logfile API loading main_exiterror: writeNewLineToLog main_exit createStringError str1 writeLog rax, main_exit sub rax,rax main_exit: ret endp ;import table section '.idata' import data readable writeable library kernel,'KERNEL32.DLL' import kernel,\ LoadLibrary,'LoadLibraryA',\ GetProcAddress,'GetProcAddress',\ GetFileSize,'GetFileSize',\ CreateFileMapping,'CreateFileMappingA',\ MapViewOfFile,'MapViewOfFile',\ UnmapViewOfFile,'UnmapViewOfFile',\ CreateFile,'CreateFileA',\ CloseHandle,'CloseHandle',\ DeleteFile,'DeleteFileA',\ GetModuleHandle,'GetModuleHandle',\ VirtualAlloc,'VirtualAlloc',\ VirtualProtect,'VirtualProtect',\ VirtualFree,'VirtualFree',\ ExitProcess,'ExitProcess'
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_ProjPoop_Shapeshifter_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function ProjPoop_Shapeshifter.ProjPoop_Shapeshifter_C.BP_IgnoreProjectileImpact struct AProjPoop_Shapeshifter_C_BP_IgnoreProjectileImpact_Params { struct FHitResult* ImpactHit; // (Parm) bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function ProjPoop_Shapeshifter.ProjPoop_Shapeshifter_C.BPProjectileBounced struct AProjPoop_Shapeshifter_C_BPProjectileBounced_Params { struct FHitResult ImpactResult; // (Parm, OutParm, ReferenceParm) struct FVector ImpactVelocity; // (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData) }; // Function ProjPoop_Shapeshifter.ProjPoop_Shapeshifter_C.ReceiveBeginPlay struct AProjPoop_Shapeshifter_C_ReceiveBeginPlay_Params { }; // Function ProjPoop_Shapeshifter.ProjPoop_Shapeshifter_C.UserConstructionScript struct AProjPoop_Shapeshifter_C_UserConstructionScript_Params { }; // Function ProjPoop_Shapeshifter.ProjPoop_Shapeshifter_C.ExecuteUbergraph_ProjPoop_Shapeshifter struct AProjPoop_Shapeshifter_C_ExecuteUbergraph_ProjPoop_Shapeshifter_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
; File to tests address file association when executing self modifyfing code. ; In SLD files there is only the address of the start of an instruction. ; If the instruction is modified by the program also addresses "inside" ; the original instruction may occur. ; If such an new instruction is executed DeZog would create adisassembly file. ; The behavior is a little inconsistent as the first address still ; navigates to the original file although the instruction is "wrong". ; ; to at least get a consisten behavior deZog tries to estimate the size of an ; instruction and assiciates all addresses to this file. DEVICE ZXSPECTRUMNEXT SLDOPT COMMENT WPMEM, LOGPOINT, ASSERTION ORG 0x8000 jp 0x9000 ; 3 bytes will be associated nop ORG 0x8100 jp 0x9000 ; Only one byte is associated as the following address is more than 4 bytes away ORG 0x8200 nop ; 1 byte instruction ld a,10 ; 2 byte instruction jp 0x9000 ; 3 bytes will be associated ld (ix+9),5 ; 4 byte instruction nop ORG 0x8300 ld a,9 ; 2 byte instruction followed by data is not associated defb 0x0E
.file "deflate.c" .section .rodata .align 32 .globl deflate_copyright .type deflate_copyright, @object deflate_copyright: .string " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler " .size deflate_copyright, 68 # ---------------------- .section .data.rel.ro.local,"aw",@progbits .align 32 .local configuration_table .type configuration_table, @object configuration_table: .value 0 .value 0 .value 0 .value 0 .long deflate_stored .value 4 .value 4 .value 8 .value 4 .long deflate_fast .value 4 .value 5 .value 16 .value 8 .long deflate_fast .value 4 .value 6 .value 32 .value 32 .long deflate_fast .value 4 .value 4 .value 16 .value 16 .long deflate_slow .value 8 .value 16 .value 32 .value 32 .long deflate_slow .value 8 .value 16 .value 128 .value 128 .long deflate_slow .value 8 .value 32 .value 128 .value 256 .long deflate_slow .value 32 .value 128 .value 258 .value 1024 .long deflate_slow .value 32 .value 258 .value 258 .value 4096 .long deflate_slow .size configuration_table, 120 # ---------------------- .text .p2align 2,,3 # ---------------------- .globl deflateInit_ .type deflateInit_, @function deflateInit_: pushl %ebp movl %esp, %ebp pushl %ebx pushl %eax pushl 20(%ebp) pushl 16(%ebp) pushl $0 pushl $8 pushl $15 pushl $8 pushl 12(%ebp) call .L2 .L2: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L2], %ebx pushl 8(%ebp) call deflateInit2_@PLT movl -4(%ebp), %ebx leave ret .size deflateInit_, .-deflateInit_ # ---------------------- .section .rodata .local my_version.0 .type my_version.0, @object my_version.0: .string "1.2.8" .size my_version.0, 6 # ---------------------- .text .p2align 2,,3 # ---------------------- .globl deflateInit2_ .type deflateInit2_, @function deflateInit2_: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $12, %esp movl 32(%ebp), %eax call .L24 .L24: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L24], %ebx testl %eax, %eax movl 8(%ebp), %edi movl $1, %esi je .L5 cmpb $49, (%eax) je .L19 .L5: movl $-6, %eax .L3: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .p2align 2,,3 .L19: cmpl $56, 36(%ebp) jne .L5 testl %edi, %edi movl $-2, %eax je .L3 movl 32(%edi), %edx testl %edx, %edx movl $0, 24(%edi) jne .L7 leal zcalloc@GOTOFF(%ebx), %edx movl %edx, 32(%edi) movl $0, 40(%edi) .L7: movl 36(%edi), %ecx testl %ecx, %ecx jne .L8 leal zcfree@GOTOFF(%ebx), %edx movl %edx, 36(%edi) .L8: cmpl $-1, 12(%ebp) je .L20 .L9: movl 20(%ebp), %ecx testl %ecx, %ecx js .L21 cmpl $15, 20(%ebp) jle .L11 movl $2, %esi subl $16, 20(%ebp) .L11: movl 24(%ebp), %edx decl %edx cmpl $8, %edx ja .L14 cmpl $8, 16(%ebp) je .L22 .L14: movl $-2, %eax jmp .L3 .L22: cmpl $7, 20(%ebp) jle .L14 cmpl $15, 20(%ebp) jg .L14 movl 12(%ebp), %ecx testl %ecx, %ecx js .L14 cmpl $9, 12(%ebp) jg .L14 movl 28(%ebp), %edx testl %edx, %edx js .L14 cmpl $4, 28(%ebp) jg .L14 cmpl $8, 20(%ebp) je .L23 .L15: pushl %ecx pushl $5828 pushl $1 pushl 40(%edi) call *32(%edi) movl %eax, -16(%ebp) movl -16(%ebp), %ecx addl $16, %esp testl %ecx, %ecx movl $-4, %eax je .L3 movl -16(%ebp), %ecx movl %esi, 24(%ecx) movl 20(%ebp), %esi movl %esi, 48(%ecx) movl $1, %esi movl %ecx, 28(%edi) movl %edi, (%ecx) movl $0, 28(%ecx) movl %esi, %eax movb 20(%ebp), %cl movl -16(%ebp), %edx sall %cl, %eax movl %eax, 44(%edx) movl 24(%ebp), %ecx decl %eax movl %eax, 52(%edx) addl $7, %ecx movl %esi, %eax sall %cl, %eax movl %ecx, 80(%edx) movl %eax, %ecx decl %ecx movl %eax, 76(%edx) movl %ecx, 84(%edx) movl 24(%ebp), %edx addl $9, %edx movl $-1431655765, %eax mull %edx movl %edx, %eax shrl $1, %eax movl -16(%ebp), %ecx movl %eax, 88(%ecx) pushl %eax pushl $2 pushl 44(%ecx) pushl 40(%edi) call *32(%edi) addl $12, %esp movl -16(%ebp), %edx movl %eax, 56(%edx) pushl $2 pushl 44(%edx) pushl 40(%edi) call *32(%edi) addl $12, %esp movl -16(%ebp), %ecx movl %eax, 64(%ecx) pushl $2 pushl 76(%ecx) pushl 40(%edi) call *32(%edi) movl 24(%ebp), %ecx movl -16(%ebp), %edx addl $6, %ecx addl $12, %esp movl %eax, 68(%edx) movl $0, 5824(%edx) sall %cl, %esi movl -16(%ebp), %edx movl %esi, 5788(%edx) pushl $4 pushl 5788(%edx) pushl 40(%edi) call *32(%edi) movl %eax, %ecx movl -16(%ebp), %eax movl 5788(%eax), %edx movl %eax, %esi movl %ecx, 8(%eax) leal 0(,%edx,4), %eax movl %eax, 12(%esi) movl 56(%esi), %eax addl $16, %esp testl %eax, %eax je .L18 movl 64(%esi), %eax testl %eax, %eax je .L18 movl 68(%esi), %eax testl %eax, %eax je .L18 testl %ecx, %ecx je .L18 movl %edx, %esi andl $-2, %esi leal (%esi,%ecx), %eax movl -16(%ebp), %esi movl %eax, 5796(%esi) leal (%edx,%edx,2), %eax leal (%eax,%ecx), %edx movl %edx, 5784(%esi) movl 28(%ebp), %eax movl 12(%ebp), %edx subl $12, %esp movl %edx, 132(%esi) movl %eax, 136(%esi) movb $8, 36(%esi) pushl %edi call deflateReset@PLT jmp .L3 .p2align 2,,3 .L18: movl z_errmsg@GOT(%ebx), %ecx movl -16(%ebp), %esi movl 24(%ecx), %edx subl $12, %esp movl $666, 4(%esi) movl %edx, 24(%edi) pushl %edi call deflateEnd@PLT movl $-4, %eax jmp .L3 .L23: movl $9, 20(%ebp) jmp .L15 .p2align 2,,3 .L21: xorl %esi, %esi negl 20(%ebp) jmp .L11 .L20: movl $6, 12(%ebp) jmp .L9 .size deflateInit2_, .-deflateInit2_ # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateSetDictionary .type deflateSetDictionary, @function deflateSetDictionary: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $60, %esp movl 8(%ebp), %edx call .L71 .L71: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L71], %ebx testl %edx, %edx movl 12(%ebp), %edi movl 16(%ebp), %esi je .L29 movl 8(%ebp), %ecx movl 28(%ecx), %edx testl %edx, %edx movl %edx, -28(%ebp) je .L29 testl %edi, %edi je .L29 movl -28(%ebp), %eax movl 24(%eax), %edx cmpl $2, %edx movl %edx, -16(%ebp) je .L29 decl %edx je .L68 .L30: movl -28(%ebp), %edx movl 116(%edx), %ecx testl %ecx, %ecx je .L28 .p2align 2,,3 .L29: movl $-2, %eax .L25: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L28: cmpl $1, -16(%ebp) je .L69 .L31: movl -28(%ebp), %ecx movl 44(%ecx), %eax cmpl %eax, %esi movl $0, 24(%ecx) movl %ecx, %edx jb .L32 movl -16(%ebp), %ecx testl %ecx, %ecx je .L70 .L33: subl %eax, %esi addl %esi, %edi movl %eax, %esi .L32: movl 8(%ebp), %edx movl 4(%edx), %eax subl $12, %esp movl 8(%ebp), %edx movl %eax, -20(%ebp) movl 8(%ebp), %eax movl (%edx), %ecx movl %esi, 4(%eax) movl %edi, (%eax) pushl -28(%ebp) movl %ecx, -24(%ebp) call fill_window movl -28(%ebp), %esi movl 116(%esi), %edx addl $16, %esp cmpl $2, %edx movl %edx, %eax jbe .L67 .p2align 2,,3 .L65: movl -28(%ebp), %edi movl 68(%edi), %edx movl 88(%edi), %ecx subl $2, %eax movl 108(%edi), %esi movl %eax, -64(%ebp) movl %edx, -44(%ebp) movl 84(%edi), %eax movl 56(%edi), %edx movl %ecx, -52(%ebp) movl -28(%ebp), %edi movl -28(%ebp), %ecx movl %edx, -36(%ebp) movl 52(%edi), %edx movl 64(%ecx), %edi movl %eax, -48(%ebp) movl %edx, -32(%ebp) movl %edi, -40(%ebp) .p2align 2,,3 .L61: movl -28(%ebp), %edi movl 72(%edi), %eax movb -52(%ebp), %cl movl -36(%ebp), %edx sall %cl, %eax movzbl 2(%esi,%edx), %ecx xorl %ecx, %eax andl -48(%ebp), %eax movl -28(%ebp), %ecx movl -44(%ebp), %edx movl %eax, 72(%ecx) movl -32(%ebp), %ecx movw (%edx,%eax,2), %di andl %esi, %ecx movl -40(%ebp), %edx movw %di, (%edx,%ecx,2) movl -44(%ebp), %edi movw %si, (%edi,%eax,2) incl %esi decl -64(%ebp) jne .L61 movl -28(%ebp), %edi subl $12, %esp movl %esi, 108(%edi) movl $2, 116(%edi) pushl %edi call fill_window movl 116(%edi), %edx addl $16, %esp cmpl $2, %edx movl %edx, %eax ja .L65 .L67: movl -28(%ebp), %esi movl 108(%esi), %ecx addl %edx, %ecx movl %ecx, 108(%esi) movl %edx, 5812(%esi) movl -16(%ebp), %eax movl %ecx, 92(%esi) movl -24(%ebp), %edx movl 8(%ebp), %ecx movl -20(%ebp), %edi movl $0, 116(%esi) movl $2, 120(%esi) movl $2, 96(%esi) movl $0, 104(%esi) movl %edx, (%ecx) movl %edi, 4(%ecx) movl %eax, 24(%esi) xorl %eax, %eax jmp .L25 .L70: movl 76(%edx), %eax sall $1, %eax movl 68(%edx), %edx movw $0, -2(%eax,%edx) subl $2, %eax pushl %ecx pushl %eax pushl $0 pushl %edx call memset@PLT movl -28(%ebp), %edx addl $16, %esp movl $0, 108(%edx) movl $0, 92(%edx) movl $0, 5812(%edx) movl 44(%edx), %eax jmp .L33 .L69: pushl %eax pushl %esi pushl %edi movl 8(%ebp), %eax pushl 48(%eax) call adler32@PLT movl 8(%ebp), %edx movl %eax, 48(%edx) addl $16, %esp jmp .L31 .L68: movl -28(%ebp), %edx cmpl $42, 4(%edx) jne .L29 jmp .L30 .size deflateSetDictionary, .-deflateSetDictionary # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateResetKeep .type deflateResetKeep, @function deflateResetKeep: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $12, %esp movl 8(%ebp), %edi call .L83 .L83: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L83], %ebx testl %edi, %edi je .L74 movl 28(%edi), %esi testl %esi, %esi je .L74 movl 32(%edi), %eax testl %eax, %eax je .L74 movl 36(%edi), %edx testl %edx, %edx jne .L73 .p2align 2,,3 .L74: movl $-2, %eax .L72: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .p2align 2,,3 .L73: movl $2, 44(%edi) movl 24(%esi), %eax movl 8(%esi), %ecx testl %eax, %eax movl $0, 20(%edi) movl $0, 8(%edi) movl $0, 24(%edi) movl $0, 20(%esi) movl %ecx, 16(%esi) js .L81 .L75: movl 24(%esi), %ecx xorl %edx, %edx testl %ecx, %ecx sete %dl decl %edx andl $-71, %edx addl $113, %edx cmpl $2, %ecx movl %edx, 4(%esi) je .L82 pushl %eax pushl $0 pushl $0 pushl $0 call adler32@PLT .L80: movl %eax, 48(%edi) movl $0, 40(%esi) movl %esi, (%esp) call _tr_init xorl %eax, %eax jmp .L72 .L82: pushl %eax pushl $0 pushl $0 pushl $0 call crc32@PLT jmp .L80 .L81: negl %eax movl %eax, 24(%esi) jmp .L75 .size deflateResetKeep, .-deflateResetKeep # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateReset .type deflateReset, @function deflateReset: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $24, %esp movl 8(%ebp), %edi call .L87 .L87: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L87], %ebx pushl %edi call deflateResetKeep@PLT addl $16, %esp testl %eax, %eax movl %eax, %esi je .L86 .L85: leal -12(%ebp), %esp popl %ebx movl %esi, %eax popl %esi popl %edi leave ret .p2align 2,,3 .L86: subl $12, %esp pushl 28(%edi) call lm_init addl $16, %esp jmp .L85 .size deflateReset, .-deflateReset # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateSetHeader .type deflateSetHeader, @function deflateSetHeader: pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax testl %eax, %eax je .L92 movl 28(%eax), %edx testl %edx, %edx je .L92 cmpl $2, 24(%edx) je .L91 .L92: movl $-2, %eax .L88: leave ret .p2align 2,,3 .L91: movl 12(%ebp), %ecx movl %ecx, 28(%edx) xorl %eax, %eax jmp .L88 .size deflateSetHeader, .-deflateSetHeader # ---------------------- .p2align 2,,3 # ---------------------- .globl deflatePending .type deflatePending, @function deflatePending: pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax testl %eax, %eax pushl %esi movl 12(%ebp), %ecx movl 16(%ebp), %esi je .L95 movl 28(%eax), %edx testl %edx, %edx jne .L94 .L95: movl $-2, %eax .L93: movl (%esp), %esi leave ret .p2align 2,,3 .L94: testl %ecx, %ecx je .L96 movl 20(%edx), %eax movl %eax, (%ecx) .L96: testl %esi, %esi je .L97 movl 5820(%edx), %ecx movl %ecx, (%esi) .L97: xorl %eax, %eax jmp .L93 .size deflatePending, .-deflatePending # ---------------------- .p2align 2,,3 # ---------------------- .globl deflatePrime .type deflatePrime, @function deflatePrime: pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax pushl %edi testl %eax, %eax pushl %esi je .L100 movl 28(%eax), %esi testl %esi, %esi jne .L99 .L100: movl $-2, %eax .L98: leal -8(%ebp), %esp popl %esi popl %edi leave ret .p2align 2,,3 .L99: movl 16(%esi), %edx addl $2, %edx cmpl %edx, 5796(%esi) jae .L102 movl $-5, %eax jmp .L98 .p2align 2,,3 .L102: movl 5820(%esi), %edx movl $16, %edi subl %edx, %edi cmpl 12(%ebp), %edi jle .L105 movl 12(%ebp), %edi .L105: movl %edi, %ecx movl $1, %eax sall %cl, %eax decl %eax andl 16(%ebp), %eax movb %dl, %cl sall %cl, %eax subl $12, %esp leal (%edi,%edx), %ecx orw %ax, 5816(%esi) movl %ecx, 5820(%esi) pushl %esi call _tr_flush_bits movl %edi, %ecx sarl %cl, 16(%ebp) addl $16, %esp subl %edi, 12(%ebp) jne .L102 xorl %eax, %eax jmp .L98 .size deflatePrime, .-deflatePrime # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateParams .type deflateParams, @function deflateParams: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $28, %esp movl 8(%ebp), %edx call .L122 .L122: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L122], %ebx testl %edx, %edx movl 12(%ebp), %esi movl $0, -20(%ebp) je .L112 movl 28(%edx), %ecx testl %ecx, %ecx movl %ecx, -36(%ebp) je .L112 cmpl $-1, %esi je .L118 .L110: cmpl $9, %esi ja .L112 movl 16(%ebp), %eax testl %eax, %eax js .L112 cmpl $4, 16(%ebp) jle .L111 .p2align 2,,3 .L112: movl $-2, %eax .L107: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L111: movl -36(%ebp), %eax movl 132(%eax), %ecx leal configuration_table@GOTOFF(%ebx), %edi leal (%ecx,%ecx,2), %eax movl %ecx, -32(%ebp) movl 8(%edi,%eax,4), %ecx movl %edi, -24(%ebp) movl %ecx, -16(%ebp) movl 16(%ebp), %edi movl -36(%ebp), %ecx cmpl 136(%ecx), %edi je .L119 .L114: movl 8(%edx), %edi testl %edi, %edi jne .L120 .L113: cmpl %esi, -32(%ebp) je .L116 movl -36(%ebp), %edx movl %esi, 132(%edx) leal (%esi,%esi,2), %edx sall $2, %edx movl -24(%ebp), %ecx movl -36(%ebp), %esi movzwl 2(%ecx,%edx), %edi movl %edi, 128(%esi) movzwl (%ecx,%edx), %edi movl %edi, 140(%esi) movzwl 4(%ecx,%edx), %edi movl %edi, 144(%esi) movzwl 6(%ecx,%edx), %edi movl %edi, 124(%esi) .L116: movl 16(%ebp), %eax movl -36(%ebp), %ecx movl %eax, 136(%ecx) movl -20(%ebp), %eax jmp .L107 .L120: subl $8, %esp pushl $5 pushl %edx call deflate@PLT addl $16, %esp cmpl $-5, %eax movl %eax, -20(%ebp) je .L121 movl -36(%ebp), %ecx movl 132(%ecx), %eax movl %eax, -32(%ebp) jmp .L113 .L121: movl -36(%ebp), %ecx xorl %edx, %edx cmpl $0, 20(%ecx) sete %dl decl %edx andl $-5, %edx movl 132(%ecx), %eax movl %edx, -20(%ebp) movl %eax, -32(%ebp) jmp .L113 .L119: leal (%esi,%esi,2), %ecx movl -16(%ebp), %eax movl -24(%ebp), %edi cmpl 8(%edi,%ecx,4), %eax jne .L114 jmp .L113 .p2align 2,,3 .L118: movl $6, %esi jmp .L110 .size deflateParams, .-deflateParams # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateTune .type deflateTune, @function deflateTune: pushl %ebp movl %esp, %ebp movl 8(%ebp), %eax testl %eax, %eax je .L125 movl 28(%eax), %edx testl %edx, %edx jne .L124 .L125: movl $-2, %eax .L123: leave ret .p2align 2,,3 .L124: movl 12(%ebp), %ecx movl %ecx, 140(%edx) movl 16(%ebp), %ecx movl %ecx, 128(%edx) movl 20(%ebp), %ecx movl %ecx, 144(%edx) movl 24(%ebp), %ecx movl %ecx, 124(%edx) xorl %eax, %eax jmp .L123 .size deflateTune, .-deflateTune # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateBound .type deflateBound, @function deflateBound: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi subl $8, %esp movl 12(%ebp), %esi leal 7(%esi), %eax shrl $3, %eax leal 63(%esi), %edi shrl $6, %edi leal (%eax,%esi), %edx movl 8(%ebp), %ecx leal (%edi,%edx), %eax leal 5(%eax), %edi testl %ecx, %ecx movl %edi, -12(%ebp) je .L128 movl 28(%ecx), %edx testl %edx, %edx jne .L127 .L128: addl $11, %eax .L126: addl $8, %esp popl %esi popl %edi leave ret .p2align 2,,3 .L127: movl 24(%edx), %eax cmpl $1, %eax je .L131 cmpl $1, %eax jle .L153 cmpl $2, %eax je .L134 .L148: movl $6, %edi .L129: cmpl $15, 48(%edx) je .L154 .L152: movl -12(%ebp), %eax addl %edi, %eax jmp .L126 .p2align 2,,3 .L154: cmpl $15, 80(%edx) jne .L152 movl %esi, %ecx shrl $12, %ecx leal (%ecx,%esi), %edx shrl $14, %esi addl %esi, %edx shrl $11, %esi addl %esi, %edx leal 7(%edi,%edx), %eax jmp .L126 .L134: movl 28(%edx), %eax testl %eax, %eax movl $18, %edi movl %eax, -16(%ebp) je .L129 movl 16(%eax), %ecx testl %ecx, %ecx je .L136 movl 20(%eax), %edi addl $20, %edi .L136: movl -16(%ebp), %eax movl 28(%eax), %ecx testl %ecx, %ecx je .L137 .p2align 2,,3 .L138: movb (%ecx), %al incl %edi incl %ecx testb %al, %al jne .L138 .L137: movl -16(%ebp), %eax movl 36(%eax), %ecx testl %ecx, %ecx je .L142 .p2align 2,,3 .L143: movb (%ecx), %al incl %edi incl %ecx testb %al, %al jne .L143 .L142: movl -16(%ebp), %eax movl 44(%eax), %ecx testl %ecx, %ecx je .L129 addl $2, %edi jmp .L129 .L153: xorl %edi, %edi testl %eax, %eax je .L129 jmp .L148 .p2align 2,,3 .L131: movl 108(%edx), %eax testl %eax, %eax setne %al movzbl %al, %ecx leal 6(,%ecx,4), %edi jmp .L129 .size deflateBound, .-deflateBound # ---------------------- .p2align 2,,3 # ---------------------- .globl deflate .type deflate, @function deflate: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $60, %esp movl 8(%ebp), %edx call .L386 .L386: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L386], %ebx testl %edx, %edx je .L345 movl 8(%ebp), %edx movl 28(%edx), %edi testl %edi, %edi je .L345 cmpl $5, 12(%ebp) jg .L345 movl 12(%ebp), %ecx testl %ecx, %ecx js .L345 movl 8(%ebp), %edx movl 12(%edx), %esi testl %esi, %esi je .L159 movl (%edx), %ecx testl %ecx, %ecx jne .L160 movl 4(%edx), %eax testl %eax, %eax jne .L159 .L160: movl 4(%edi), %eax cmpl $666, %eax movl %eax, %edx je .L347 .L158: movl 8(%ebp), %esi movl 16(%esi), %ecx testl %ecx, %ecx jne .L161 movl z_errmsg@GOT(%ebx), %edi movl 28(%edi), %ecx movl %ecx, 24(%esi) .L344: movl $-5, %eax .p2align 2,,3 .L155: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L161: movl 8(%ebp), %esi movl 40(%edi), %ecx movl %esi, (%edi) cmpl $42, %edx movl 12(%ebp), %esi movl %ecx, -16(%ebp) movl %esi, 40(%edi) je .L348 .L162: cmpl $69, %eax je .L349 movl 20(%edi), %esi movl %esi, -56(%ebp) .L195: cmpl $73, %eax je .L350 .L211: cmpl $91, %eax je .L351 .L227: cmpl $103, %eax je .L352 .L243: movl -56(%ebp), %ecx testl %ecx, %ecx jne .L353 movl 8(%ebp), %edx movl 4(%edx), %ecx testl %ecx, %ecx jne .L258 movl -16(%ebp), %eax movl 12(%ebp), %edx sall $1, %eax sall $1, %edx cmpl $4, 12(%ebp) jle .L260 subl $9, %edx .L260: cmpl $4, -16(%ebp) jle .L261 subl $9, %eax .L261: cmpl %eax, %edx jg .L258 cmpl $4, 12(%ebp) je .L258 .L343: movl z_errmsg@GOT(%ebx), %ecx movl 28(%ecx), %esi movl 8(%ebp), %edi movl %esi, 24(%edi) jmp .L344 .L258: movl 4(%edi), %eax cmpl $666, %eax je .L354 testl %ecx, %ecx jne .L265 .L338: movl 116(%edi), %edx testl %edx, %edx jne .L265 movl 12(%ebp), %esi testl %esi, %esi je .L264 cmpl $666, %eax je .L264 .L265: movl 136(%edi), %eax cmpl $2, %eax je .L355 cmpl $3, %eax je .L356 subl $8, %esp movl 132(%edi), %edx pushl 12(%ebp) leal (%edx,%edx,2), %esi pushl %edi leal configuration_table@GOTOFF(%ebx), %ecx call *8(%ecx,%esi,4) .L340: leal -2(%eax), %esi addl $16, %esp cmpl $1, %esi movl %eax, %edx ja .L270 movl $666, 4(%edi) .L270: testl %edx, %edx je .L272 cmpl $2, %edx je .L272 decl %edx je .L357 .L264: xorl %eax, %eax cmpl $4, 12(%ebp) jne .L155 movl 24(%edi), %edx testl %edx, %edx movl $1, %eax jle .L155 cmpl $2, %edx je .L358 movl 8(%ebp), %esi movl 48(%esi), %ecx movl %ecx, %eax movl 20(%edi), %edx movl 8(%edi), %esi shrl $24, %eax movb %al, (%edx,%esi) movl 20(%edi), %esi movl 8(%edi), %edx incl %esi shrl $16, %ecx movl %esi, 20(%edi) movb %cl, (%esi,%edx) movl 8(%ebp), %eax movzwl 48(%eax), %esi movl 20(%edi), %ecx movl %esi, %eax incl %ecx movl 8(%edi), %edx shrl $8, %eax movl %ecx, 20(%edi) movb %al, (%ecx,%edx) movl 20(%edi), %edx incl %edx movl 8(%edi), %eax movl %esi, %ecx movl %edx, 20(%edi) movb %cl, (%edx,%eax) .L341: movl 8(%ebp), %ecx movl 28(%ecx), %eax subl $12, %esp incl 20(%edi) pushl %eax movl %eax, -52(%ebp) call _tr_flush_bits movl -52(%ebp), %edx movl 8(%ebp), %ecx movl 20(%edx), %esi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %esi jbe .L315 movl %eax, %esi .L315: testl %esi, %esi jne .L359 .L317: movl 24(%edi), %eax testl %eax, %eax jle .L319 negl %eax movl %eax, 24(%edi) .L319: xorl %eax, %eax cmpl $0, 20(%edi) sete %al jmp .L155 .L359: pushl %eax pushl %esi movl -52(%ebp), %edx pushl 16(%edx) movl 8(%ebp), %ecx pushl 12(%ecx) call memcpy@PLT movl 8(%ebp), %eax movl -52(%ebp), %ecx subl %esi, 16(%eax) movl 20(%ecx), %edx addl %esi, 12(%eax) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%eax) testl %edx, %edx movl %edx, 20(%ecx) jne .L317 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L317 .L358: movl 8(%ebp), %esi movl 20(%edi), %edx movl 8(%edi), %ecx movb 48(%esi), %al movb %al, (%edx,%ecx) movl 20(%edi), %edx movl 48(%esi), %eax movl 8(%edi), %ecx incl %edx shrl $8, %eax movl %edx, 20(%edi) movb %al, (%edx,%ecx) movl 20(%edi), %ecx movl 8(%edi), %edx movzwl 50(%esi), %eax incl %ecx movl %ecx, 20(%edi) movb %al, (%ecx,%edx) movl 20(%edi), %ecx movl 8(%edi), %edx movzbl 51(%esi), %eax incl %ecx movl %ecx, 20(%edi) movb %al, (%ecx,%edx) movl 20(%edi), %ecx movl 8(%edi), %edx movb 8(%esi), %al incl %ecx movl %ecx, 20(%edi) movb %al, (%ecx,%edx) movl 20(%edi), %edx movl 8(%esi), %eax incl %edx movl 8(%edi), %ecx shrl $8, %eax movl %edx, 20(%edi) movb %al, (%edx,%ecx) movl 20(%edi), %ecx incl %ecx movl 8(%edi), %edx movzwl 10(%esi), %eax movl %ecx, 20(%edi) movb %al, (%ecx,%edx) movl 20(%edi), %ecx incl %ecx movl 8(%edi), %edx movzbl 11(%esi), %eax movl %ecx, 20(%edi) movb %al, (%ecx,%edx) jmp .L341 .L357: cmpl $1, 12(%ebp) je .L360 cmpl $5, 12(%ebp) je .L276 pushl $0 pushl $0 pushl $0 pushl %edi call _tr_stored_block addl $16, %esp cmpl $3, 12(%ebp) je .L361 .L276: movl 8(%ebp), %ecx movl 28(%ecx), %eax subl $12, %esp pushl %eax movl %eax, -48(%ebp) call _tr_flush_bits movl -48(%ebp), %edx movl 8(%ebp), %ecx movl 20(%edx), %esi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %esi jbe .L304 movl %eax, %esi .L304: testl %esi, %esi jne .L362 .L306: testl %eax, %eax jne .L264 .L346: movl $-1, 40(%edi) .L342: xorl %eax, %eax jmp .L155 .L362: pushl %eax pushl %esi movl -48(%ebp), %eax pushl 16(%eax) movl 8(%ebp), %edx pushl 12(%edx) call memcpy@PLT movl 8(%ebp), %edx movl -48(%ebp), %ecx subl %esi, 16(%edx) movl 20(%ecx), %eax addl %esi, 12(%edx) subl %esi, %eax addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%edx) testl %eax, %eax movl %eax, 20(%ecx) jne .L335 movl 8(%ecx), %esi movl %esi, 16(%ecx) movl 16(%edx), %eax jmp .L306 .L335: movl 8(%ebp), %ecx movl 16(%ecx), %eax jmp .L306 .L361: movl 76(%edi), %edx movl 68(%edi), %esi sall $1, %edx movw $0, -2(%edx,%esi) subl $2, %edx pushl %ecx pushl %edx pushl $0 pushl %esi call memset@PLT movl 116(%edi), %ecx addl $16, %esp testl %ecx, %ecx jne .L276 movl $0, 108(%edi) movl $0, 92(%edi) movl $0, 5812(%edi) jmp .L276 .p2align 2,,3 .L360: subl $12, %esp pushl %edi call _tr_align addl $16, %esp jmp .L276 .p2align 2,,3 .L272: movl 8(%ebp), %edx movl 16(%edx), %eax testl %eax, %eax jne .L342 jmp .L346 .L356: subl $8, %esp pushl 12(%ebp) pushl %edi call deflate_rle jmp .L340 .L355: subl $8, %esp pushl 12(%ebp) pushl %edi call deflate_huff jmp .L340 .L354: testl %ecx, %ecx je .L338 jmp .L343 .L353: movl 8(%ebp), %eax movl 28(%eax), %esi subl $12, %esp pushl %esi movl %esi, -44(%ebp) call _tr_flush_bits movl -44(%ebp), %edx movl 8(%ebp), %ecx movl 20(%edx), %esi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %esi jbe .L253 movl %eax, %esi .L253: testl %esi, %esi jne .L363 .L255: testl %eax, %eax je .L346 movl 8(%ebp), %eax movl 4(%eax), %ecx jmp .L258 .L363: pushl %eax pushl %esi movl -44(%ebp), %edx pushl 16(%edx) movl 8(%ebp), %ecx pushl 12(%ecx) call memcpy@PLT movl 8(%ebp), %edx movl -44(%ebp), %ecx subl %esi, 16(%edx) movl 20(%ecx), %eax addl %esi, 12(%edx) subl %esi, %eax addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%edx) testl %eax, %eax movl %eax, 20(%ecx) jne .L333 movl 8(%ecx), %esi movl %esi, 16(%ecx) movl 16(%edx), %eax jmp .L255 .L333: movl 8(%ebp), %ecx movl 16(%ecx), %eax jmp .L255 .L352: movl 28(%edi), %edx movl 44(%edx), %esi testl %esi, %esi je .L244 movl -56(%ebp), %ecx addl $2, %ecx movl 12(%edi), %edx cmpl %edx, %ecx ja .L364 .L245: movl -56(%ebp), %esi addl $2, %esi cmpl %edx, %esi ja .L243 movl 8(%ebp), %eax movb 48(%eax), %dl movl 8(%edi), %esi movl -56(%ebp), %ecx movb %dl, (%ecx,%esi) movl 8(%ebp), %esi movl 20(%edi), %edx movl 48(%esi), %eax movl 8(%edi), %ecx incl %edx shrl $8, %eax movl %edx, 20(%edi) movb %al, (%edx,%ecx) incl 20(%edi) pushl %eax pushl $0 pushl $0 pushl $0 call crc32@PLT movl 20(%edi), %edx movl %eax, 48(%esi) movl $113, 4(%edi) addl $16, %esp movl %edx, -56(%ebp) jmp .L243 .L364: movl 8(%ebp), %ecx movl 28(%ecx), %eax subl $12, %esp pushl %eax movl %eax, -40(%ebp) call _tr_flush_bits movl -40(%ebp), %edx movl 8(%ebp), %ecx movl 20(%edx), %esi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %esi jbe .L246 movl %eax, %esi .L246: testl %esi, %esi jne .L365 movl 20(%edi), %ecx movl %ecx, -56(%ebp) .L339: movl 12(%edi), %edx jmp .L245 .L365: pushl %eax pushl %esi movl -40(%ebp), %edx pushl 16(%edx) movl 8(%ebp), %ecx pushl 12(%ecx) call memcpy@PLT movl 8(%ebp), %eax movl -40(%ebp), %ecx subl %esi, 16(%eax) movl 20(%ecx), %edx addl %esi, 12(%eax) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%eax) testl %edx, %edx movl %edx, 20(%ecx) jne .L332 movl 8(%ecx), %esi movl 20(%edi), %eax movl %esi, 16(%ecx) movl %eax, -56(%ebp) jmp .L339 .L332: movl 20(%edi), %eax movl %eax, -56(%ebp) jmp .L339 .p2align 2,,3 .L244: movl $113, 4(%edi) jmp .L243 .L351: movl 28(%edi), %esi movl 36(%esi), %edx testl %edx, %edx je .L228 movl -56(%ebp), %ecx movl %ecx, -64(%ebp) .L229: movl -56(%ebp), %edx cmpl 12(%edi), %edx je .L366 .L232: movl 32(%edi), %ecx movl 36(%esi), %edx movzbl (%ecx,%edx), %esi incl %ecx movl %ecx, 32(%edi) movl 8(%edi), %eax movl %esi, %edx movl -56(%ebp), %ecx movb %dl, (%ecx,%eax) movl 20(%edi), %eax incl %eax testl %esi, %esi movl %eax, 20(%edi) je .L367 movl %eax, -56(%ebp) movl 28(%edi), %esi jmp .L229 .L367: movl %eax, -56(%ebp) .L230: movl 28(%edi), %ecx movl 44(%ecx), %edx testl %edx, %edx je .L240 movl -64(%ebp), %eax cmpl %eax, -56(%ebp) ja .L368 .L240: testl %esi, %esi jne .L330 .L228: movl $103, 4(%edi) movl $103, %eax jmp .L227 .L330: movl 4(%edi), %eax jmp .L227 .L368: subl %eax, -56(%ebp) pushl %edx pushl -56(%ebp) movl 8(%edi), %ecx addl %ecx, %eax pushl %eax movl 8(%ebp), %edx pushl 48(%edx) call crc32@PLT movl 8(%ebp), %ecx movl %eax, 48(%ecx) movl 20(%edi), %eax addl $16, %esp movl %eax, -56(%ebp) jmp .L240 .p2align 2,,3 .L366: movl 44(%esi), %ecx testl %ecx, %ecx je .L233 movl -64(%ebp), %ecx cmpl %ecx, %edx ja .L369 .L233: movl 8(%ebp), %eax movl 28(%eax), %esi subl $12, %esp pushl %esi movl %esi, -36(%ebp) call _tr_flush_bits movl -36(%ebp), %edx movl 8(%ebp), %ecx movl 20(%edx), %esi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %esi jbe .L234 movl %eax, %esi .L234: testl %esi, %esi jne .L370 .L236: movl 20(%edi), %eax cmpl 12(%edi), %eax movl %eax, -56(%ebp) movl %eax, -64(%ebp) je .L337 movl 28(%edi), %esi jmp .L232 .L337: movl $1, %esi jmp .L230 .L370: pushl %eax pushl %esi movl -36(%ebp), %edx pushl 16(%edx) movl 8(%ebp), %ecx pushl 12(%ecx) call memcpy@PLT movl 8(%ebp), %eax movl -36(%ebp), %ecx subl %esi, 16(%eax) movl 20(%ecx), %edx addl %esi, 12(%eax) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%eax) testl %edx, %edx movl %edx, 20(%ecx) jne .L236 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L236 .L369: subl %ecx, %edx pushl %eax pushl %edx movl 8(%edi), %eax addl %eax, %ecx pushl %ecx movl 8(%ebp), %edx pushl 48(%edx) call crc32@PLT movl 8(%ebp), %esi movl %eax, 48(%esi) addl $16, %esp jmp .L233 .L350: movl 28(%edi), %esi movl 28(%esi), %edx testl %edx, %edx je .L212 movl -56(%ebp), %eax movl %eax, -64(%ebp) .L213: movl -56(%ebp), %eax cmpl 12(%edi), %eax je .L371 .L216: movl 32(%edi), %ecx movl 28(%esi), %edx movzbl (%ecx,%edx), %esi incl %ecx movl %ecx, 32(%edi) movl 8(%edi), %eax movl %esi, %edx movl -56(%ebp), %ecx movb %dl, (%ecx,%eax) movl 20(%edi), %eax incl %eax testl %esi, %esi movl %eax, 20(%edi) je .L372 movl %eax, -56(%ebp) movl 28(%edi), %esi jmp .L213 .L372: movl %eax, -56(%ebp) .L214: movl 28(%edi), %ecx movl 44(%ecx), %edx testl %edx, %edx je .L224 movl -64(%ebp), %eax cmpl %eax, -56(%ebp) ja .L373 .L224: testl %esi, %esi jne .L327 movl $0, 32(%edi) .L212: movl $91, 4(%edi) movl $91, %eax jmp .L211 .L327: movl 4(%edi), %eax jmp .L211 .L373: subl %eax, -56(%ebp) pushl %edx pushl -56(%ebp) movl 8(%edi), %ecx addl %ecx, %eax pushl %eax movl 8(%ebp), %edx pushl 48(%edx) call crc32@PLT movl 8(%ebp), %ecx movl %eax, 48(%ecx) movl 20(%edi), %eax addl $16, %esp movl %eax, -56(%ebp) jmp .L224 .p2align 2,,3 .L371: movl 44(%esi), %ecx testl %ecx, %ecx je .L217 movl -64(%ebp), %edx cmpl %edx, %eax ja .L374 .L217: movl 8(%ebp), %esi movl 28(%esi), %ecx subl $12, %esp pushl %ecx movl %ecx, -32(%ebp) call _tr_flush_bits movl -32(%ebp), %eax movl 8(%ebp), %edx movl 20(%eax), %esi movl 16(%edx), %eax addl $16, %esp cmpl %eax, %esi jbe .L218 movl %eax, %esi .L218: testl %esi, %esi jne .L375 .L220: movl 20(%edi), %edx cmpl 12(%edi), %edx movl %edx, -56(%ebp) movl %edx, -64(%ebp) je .L336 movl 28(%edi), %esi jmp .L216 .L336: movl $1, %esi jmp .L214 .L375: pushl %eax pushl %esi movl -32(%ebp), %ecx pushl 16(%ecx) movl 8(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl 8(%ebp), %edx movl -32(%ebp), %eax subl %esi, 16(%edx) movl 20(%eax), %ecx addl %esi, 12(%edx) subl %esi, %ecx addl $16, %esp addl %esi, 16(%eax) addl %esi, 20(%edx) testl %ecx, %ecx movl %ecx, 20(%eax) jne .L220 movl 8(%eax), %esi movl %esi, 16(%eax) jmp .L220 .L374: subl %edx, %eax pushl %ecx pushl %eax movl 8(%edi), %esi addl %esi, %edx pushl %edx movl 8(%ebp), %esi pushl 48(%esi) call crc32@PLT movl %eax, 48(%esi) addl $16, %esp jmp .L217 .L349: movl 28(%edi), %esi movl 16(%esi), %eax testl %eax, %eax movl %esi, -24(%ebp) je .L196 movzwl 20(%esi), %ecx movl 20(%edi), %edx cmpl %ecx, 32(%edi) movl %edx, -56(%ebp) movl %edx, -20(%ebp) jae .L198 .L207: movl -56(%ebp), %edx cmpl 12(%edi), %edx je .L376 .L200: movl 16(%esi), %edx movl 32(%edi), %esi movb (%esi,%edx), %al movl 8(%edi), %ecx movl -56(%ebp), %esi movb %al, (%esi,%ecx) movl 20(%edi), %ecx movl 32(%edi), %edx incl %ecx incl %edx movl 28(%edi), %esi movl %ecx, 20(%edi) movl %edx, 32(%edi) movzwl 20(%esi), %eax cmpl %eax, %edx movl %esi, -24(%ebp) movl %ecx, -56(%ebp) jae .L198 movl %ecx, -56(%ebp) jmp .L207 .L198: movl 44(%esi), %ecx testl %ecx, %ecx je .L208 movl -20(%ebp), %ecx cmpl %ecx, -56(%ebp) ja .L377 .L208: movl 20(%esi), %edx cmpl %edx, 32(%edi) je .L378 movl 4(%edi), %eax jmp .L195 .L378: movl $0, 32(%edi) movl $73, 4(%edi) movl $73, %eax jmp .L195 .L377: subl %ecx, -56(%ebp) pushl %eax pushl -56(%ebp) movl 8(%edi), %eax addl %eax, %ecx pushl %ecx movl 8(%ebp), %ecx pushl 48(%ecx) call crc32@PLT movl 8(%ebp), %esi movl 20(%edi), %edx movl %eax, 48(%esi) addl $16, %esp movl %edx, -56(%ebp) movl 28(%edi), %esi jmp .L208 .p2align 2,,3 .L376: movl -24(%ebp), %eax movl 44(%eax), %esi testl %esi, %esi je .L201 movl -20(%ebp), %esi cmpl %esi, %edx ja .L379 .L201: movl 8(%ebp), %ecx movl 28(%ecx), %eax subl $12, %esp pushl %eax movl %eax, -28(%ebp) call _tr_flush_bits movl -28(%ebp), %edx movl 8(%ebp), %ecx movl 20(%edx), %esi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %esi jbe .L202 movl %eax, %esi .L202: testl %esi, %esi jne .L380 .L204: movl 20(%edi), %eax cmpl 12(%edi), %eax movl %eax, -56(%ebp) movl %eax, -20(%ebp) je .L322 movl 28(%edi), %esi jmp .L200 .L322: movl 28(%edi), %esi jmp .L198 .L380: pushl %eax pushl %esi movl -28(%ebp), %edx pushl 16(%edx) movl 8(%ebp), %ecx pushl 12(%ecx) call memcpy@PLT movl 8(%ebp), %eax movl -28(%ebp), %ecx subl %esi, 16(%eax) movl 20(%ecx), %edx addl %esi, 12(%eax) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%eax) testl %edx, %edx movl %edx, 20(%ecx) jne .L204 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L204 .L379: subl %esi, %edx pushl %eax pushl %edx movl 8(%edi), %edx addl %edx, %esi pushl %esi movl 8(%ebp), %ecx pushl 48(%ecx) call crc32@PLT movl 8(%ebp), %edx movl %eax, 48(%edx) addl $16, %esp jmp .L201 .L196: movl 20(%edi), %ecx movl $73, 4(%edi) movl $73, %eax movl %ecx, -56(%ebp) jmp .L195 .L348: cmpl $2, 24(%edi) je .L381 movl 48(%edi), %edx subl $8, %edx sall $12, %edx cmpl $1, 136(%edi) leal 2048(%edx), %esi jle .L382 .L184: xorl %eax, %eax .L185: sall $6, %eax movl 108(%edi), %ecx orl %eax, %esi testl %ecx, %ecx je .L190 orl $32, %esi .L190: movl $31, %edx movl %edx, %ecx movl %esi, %eax xorl %edx, %edx divl %ecx movl %esi, %ecx subl %edx, %ecx leal 31(%ecx), %esi movl %esi, %eax movl 20(%edi), %edx movl 8(%edi), %ecx shrl $8, %eax movl $113, 4(%edi) movb %al, (%edx,%ecx) movl 20(%edi), %edx incl %edx movl %esi, %ecx movl 8(%edi), %eax movl %edx, 20(%edi) movb %cl, (%edx,%eax) movl 20(%edi), %esi movl 108(%edi), %edx incl %esi testl %edx, %edx movl %esi, 20(%edi) je .L192 movl 8(%ebp), %ecx movl 48(%ecx), %edx movl %edx, %eax movl 8(%edi), %ecx shrl $24, %eax movb %al, (%esi,%ecx) movl 20(%edi), %esi movl 8(%edi), %ecx incl %esi shrl $16, %edx movl %esi, 20(%edi) movb %dl, (%esi,%ecx) movl 8(%ebp), %eax movzwl 48(%eax), %esi movl 20(%edi), %ecx movl %esi, %eax incl %ecx movl 8(%edi), %edx shrl $8, %eax movl %ecx, 20(%edi) movb %al, (%ecx,%edx) movl 20(%edi), %edx incl %edx movl 8(%edi), %eax movl %esi, %ecx movl %edx, 20(%edi) movb %cl, (%edx,%eax) incl 20(%edi) .L192: pushl %ecx pushl $0 pushl $0 pushl $0 call adler32@PLT movl 8(%ebp), %edx movl %eax, 48(%edx) addl $16, %esp movl 4(%edi), %eax jmp .L162 .L382: movl 132(%edi), %edx cmpl $1, %edx jle .L184 cmpl $5, %edx movl $1, %eax jle .L185 xorl %eax, %eax cmpl $6, %edx setne %al addl $2, %eax jmp .L185 .L381: pushl %eax pushl $0 pushl $0 pushl $0 call crc32@PLT movl 8(%ebp), %edx movl 20(%edi), %esi movl %eax, 48(%edx) movl 8(%edi), %eax movb $31, (%esi,%eax) movl 20(%edi), %esi incl %esi movl 8(%edi), %ecx movl %esi, 20(%edi) movb $139, (%esi,%ecx) movl 20(%edi), %ecx incl %ecx movl 8(%edi), %edx movl %ecx, 20(%edi) movb $8, (%ecx,%edx) movl 20(%edi), %eax movl 28(%edi), %edx leal 1(%eax), %ecx addl $16, %esp testl %edx, %edx movl %ecx, 20(%edi) jne .L164 movl 8(%edi), %esi movb $0, (%ecx,%esi) movl 20(%edi), %esi movl 8(%edi), %edx incl %esi movl %esi, 20(%edi) movb $0, (%esi,%edx) movl 20(%edi), %esi incl %esi movl 8(%edi), %ecx movl %esi, 20(%edi) movb $0, (%esi,%ecx) movl 20(%edi), %ecx incl %ecx movl 8(%edi), %edx movl %ecx, 20(%edi) movb $0, (%ecx,%edx) movl 20(%edi), %ecx incl %ecx movl 8(%edi), %esi movl %ecx, 20(%edi) movb $0, (%ecx,%esi) movl 20(%edi), %edx leal 1(%edx), %ecx addl $2, %edx movl %edx, 20(%edi) movl 132(%edi), %edx cmpl $9, %edx movl 8(%edi), %esi movb $2, %al je .L166 cmpl $1, 136(%edi) jle .L383 .L169: movb $4, %al .L166: movb %al, (%ecx,%esi) movl 8(%edi), %eax movl 20(%edi), %ecx movb $3, (%ecx,%eax) incl 20(%edi) movl $113, 4(%edi) movl $113, %eax jmp .L162 .L383: xorl %eax, %eax decl %edx jg .L166 jmp .L169 .p2align 2,,3 .L164: addl $2, %eax movl %eax, 20(%edi) xorl %eax, %eax cmpl $0, (%edx) setne %al cmpl $0, 44(%edx) movl 8(%edi), %esi je .L171 addl $2, %eax .L171: cmpl $0, 16(%edx) je .L172 addl $4, %eax .L172: cmpl $0, 28(%edx) je .L173 addl $8, %eax .L173: movl 36(%edx), %edx testl %edx, %edx je .L174 addl $16, %eax .L174: movb %al, (%ecx,%esi) movl 28(%edi), %eax movl 20(%edi), %esi movb 4(%eax), %cl movl 8(%edi), %edx movb %cl, (%esi,%edx) movl 28(%edi), %eax movl 20(%edi), %esi movl 4(%eax), %ecx incl %esi movl 8(%edi), %edx shrl $8, %ecx movl %esi, 20(%edi) movb %cl, (%esi,%edx) movl 20(%edi), %esi movl 28(%edi), %eax incl %esi movzwl 6(%eax), %ecx movl 8(%edi), %edx movl %esi, 20(%edi) movb %cl, (%esi,%edx) movl 20(%edi), %esi movl 28(%edi), %eax incl %esi movzbl 7(%eax), %ecx movl 8(%edi), %edx movl %esi, 20(%edi) movb %cl, (%esi,%edx) movl 20(%edi), %edx leal 1(%edx), %ecx addl $2, %edx movl %edx, 20(%edi) movl 132(%edi), %edx cmpl $9, %edx movl 8(%edi), %esi movb $2, %al je .L176 cmpl $1, 136(%edi) jle .L384 .L179: movb $4, %al .L176: movb %al, (%ecx,%esi) movl 28(%edi), %eax movl 20(%edi), %esi movb 12(%eax), %cl movl 8(%edi), %edx movb %cl, (%esi,%edx) movl 28(%edi), %esi movl 20(%edi), %ecx movl 16(%esi), %edx incl %ecx testl %edx, %edx movl %ecx, 20(%edi) je .L180 movb 20(%esi), %al movl 8(%edi), %edx movb %al, (%ecx,%edx) movl 20(%edi), %esi incl %esi movl %esi, 20(%edi) movl 28(%edi), %eax movl 20(%eax), %ecx movl 8(%edi), %edx shrl $8, %ecx movb %cl, (%esi,%edx) incl 20(%edi) movl 28(%edi), %esi .L180: movl 44(%esi), %edx testl %edx, %edx jne .L385 .L181: movl $0, 32(%edi) movl $69, 4(%edi) movl $69, %eax jmp .L162 .L385: pushl %eax pushl 20(%edi) pushl 8(%edi) movl 8(%ebp), %ecx pushl 48(%ecx) call crc32@PLT movl 8(%ebp), %esi movl %eax, 48(%esi) addl $16, %esp jmp .L181 .L384: xorl %eax, %eax decl %edx jg .L176 jmp .L179 .p2align 2,,3 .L347: cmpl $4, 12(%ebp) je .L158 .p2align 2,,3 .L159: movl z_errmsg@GOT(%ebx), %esi movl 16(%esi), %edx movl 8(%ebp), %edi movl %edx, 24(%edi) .p2align 2,,3 .L345: movl $-2, %eax jmp .L155 .size deflate, .-deflate # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateEnd .type deflateEnd, @function deflateEnd: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi movl 8(%ebp), %esi testl %esi, %esi je .L389 movl 28(%esi), %edx testl %edx, %edx movl %edx, %ecx jne .L388 .L389: movl $-2, %eax .L387: leal -8(%ebp), %esp popl %esi popl %edi leave ret .p2align 2,,3 .L388: movl 4(%edx), %edi cmpl $42, %edi je .L390 cmpl $69, %edi je .L390 cmpl $73, %edi je .L390 cmpl $91, %edi je .L390 cmpl $103, %edi je .L390 cmpl $113, %edi je .L390 cmpl $666, %edi movl $-2, %eax jne .L387 .p2align 2,,3 .L390: movl 8(%ecx), %eax testl %eax, %eax jne .L397 .L391: movl 68(%edx), %eax testl %eax, %eax jne .L398 .L392: movl 64(%edx), %eax testl %eax, %eax jne .L399 .L393: movl 56(%edx), %eax testl %eax, %eax jne .L400 .L394: subl $8, %esp pushl 28(%esi) pushl 40(%esi) call *36(%esi) xorl %edx, %edx addl $16, %esp cmpl $113, %edi setne %dl movl $0, 28(%esi) leal -3(%edx,%edx,2), %eax jmp .L387 .p2align 2,,3 .L400: subl $8, %esp pushl %eax pushl 40(%esi) call *36(%esi) addl $16, %esp jmp .L394 .p2align 2,,3 .L399: subl $8, %esp pushl %eax pushl 40(%esi) call *36(%esi) addl $16, %esp movl 28(%esi), %edx jmp .L393 .p2align 2,,3 .L398: subl $8, %esp pushl %eax pushl 40(%esi) call *36(%esi) addl $16, %esp movl 28(%esi), %edx jmp .L392 .p2align 2,,3 .L397: subl $8, %esp pushl %eax pushl 40(%esi) call *36(%esi) addl $16, %esp movl 28(%esi), %edx jmp .L391 .size deflateEnd, .-deflateEnd # ---------------------- .p2align 2,,3 # ---------------------- .globl deflateCopy .type deflateCopy, @function deflateCopy: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $12, %esp movl 12(%ebp), %esi call .L407 .L407: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L407], %ebx testl %esi, %esi je .L403 movl 8(%ebp), %edx testl %edx, %edx je .L403 movl 28(%esi), %edx testl %edx, %edx movl %edx, -20(%ebp) jne .L402 .L403: movl $-2, %eax .L401: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .p2align 2,,3 .L402: cld movl 8(%ebp), %edi movl $14, %ecx rep movsl pushl %eax pushl $5828 pushl $1 movl 8(%ebp), %esi pushl 40(%esi) call *32(%esi) movl %eax, -16(%ebp) movl -16(%ebp), %ecx addl $16, %esp testl %ecx, %ecx movl $-4, %eax je .L401 movl 8(%ebp), %esi movl -16(%ebp), %eax movl %eax, 28(%esi) cld movl %eax, %edi movl -20(%ebp), %esi movl $1457, %ecx rep movsl movl -16(%ebp), %edx movl 8(%ebp), %edi movl %edi, (%edx) pushl %esi pushl $2 pushl 44(%edx) pushl 40(%edi) call *32(%edi) addl $12, %esp movl -16(%ebp), %esi movl %eax, 56(%esi) pushl $2 movl 8(%ebp), %edi pushl 44(%esi) pushl 40(%edi) call *32(%edi) addl $12, %esp movl -16(%ebp), %ecx movl %eax, 64(%ecx) pushl $2 pushl 76(%ecx) pushl 40(%edi) call *32(%edi) addl $12, %esp movl -16(%ebp), %edx movl %eax, 68(%edx) pushl $4 pushl 5788(%edx) pushl 40(%edi) call *32(%edi) movl %eax, %esi movl -16(%ebp), %eax movl 56(%eax), %edx addl $16, %esp testl %edx, %edx movl %esi, 8(%eax) je .L406 movl 64(%eax), %edi testl %edi, %edi je .L406 movl 68(%eax), %ecx testl %ecx, %ecx je .L406 testl %esi, %esi je .L406 movl -16(%ebp), %eax movl 44(%eax), %edi sall $1, %edi pushl %ecx pushl %edi movl -20(%ebp), %ecx pushl 56(%ecx) pushl %edx call memcpy@PLT movl -16(%ebp), %edi movl 44(%edi), %edx addl $12, %esp sall $1, %edx pushl %edx movl -20(%ebp), %eax pushl 64(%eax) pushl 64(%edi) call memcpy@PLT movl -16(%ebp), %edi movl 76(%edi), %ecx addl $12, %esp sall $1, %ecx pushl %ecx movl -20(%ebp), %edx pushl 68(%edx) pushl 68(%edi) call memcpy@PLT addl $12, %esp movl -16(%ebp), %ecx pushl 12(%ecx) movl -20(%ebp), %eax pushl 8(%eax) pushl 8(%ecx) call memcpy@PLT movl -20(%ebp), %edx movl 16(%edx), %eax subl 8(%edx), %eax movl -16(%ebp), %edx movl 8(%edx), %ecx leal (%eax,%ecx), %edi movl %edi, 16(%edx) movl 5788(%edx), %edx movl %edx, %edi andl $-2, %edi leal (%edi,%esi), %eax movl -16(%ebp), %edi movl %eax, 5796(%edi) leal (%edx,%edx,2), %eax movl %edi, %edx addl $148, %edx movl %edx, 2840(%edi) addl $2292, %edx addl %eax, %ecx movl %edx, 2852(%edi) addl $244, %edx movl %ecx, 5784(%edi) movl %edx, 2864(%edi) xorl %eax, %eax jmp .L401 .p2align 2,,3 .L406: subl $12, %esp pushl 8(%ebp) call deflateEnd@PLT movl $-4, %eax jmp .L401 .size deflateCopy, .-deflateCopy # ---------------------- .p2align 2,,3 # ---------------------- .local lm_init .type lm_init, @function lm_init: pushl %ebp movl %esp, %ebp pushl %esi pushl %ebx movl 8(%ebp), %esi movl 44(%esi), %ecx movl 76(%esi), %eax movl 68(%esi), %edx sall $1, %ecx sall $1, %eax movl %ecx, 60(%esi) movw $0, -2(%eax,%edx) subl $2, %eax pushl %ecx pushl %eax pushl $0 call .L433 .L433: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L433], %ebx pushl %edx call memset@PLT movl 132(%esi), %edx leal (%edx,%edx,2), %eax leal configuration_table@GOTOFF(%ebx), %ecx sall $2, %eax movzwl 2(%ecx,%eax), %edx movl %edx, 128(%esi) movzwl (%ecx,%eax), %edx movl %edx, 140(%esi) movzwl 4(%ecx,%eax), %edx movl %edx, 144(%esi) movzwl 6(%ecx,%eax), %edx movl %edx, 124(%esi) movl $0, 108(%esi) movl $0, 92(%esi) movl $0, 116(%esi) movl $0, 5812(%esi) movl $2, 120(%esi) movl $2, 96(%esi) movl $0, 104(%esi) movl $0, 72(%esi) addl $16, %esp leal -8(%ebp), %esp popl %ebx popl %esi leave ret .size lm_init, .-lm_init # ---------------------- .p2align 2,,3 # ---------------------- .local fill_window .type fill_window, @function fill_window: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $60, %esp movl 8(%ebp), %edx movl 8(%ebp), %esi movl 44(%edx), %eax movl 116(%esi), %ecx call .L554 .L554: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L554], %ebx movl %eax, -20(%ebp) movl %ecx, -44(%ebp) .p2align 2,,3 .L455: movl 8(%ebp), %edx movl 60(%edx), %esi movl -44(%ebp), %ecx subl %ecx, %esi movl 8(%ebp), %ecx movl 108(%ecx), %edx subl %edx, %esi movl -20(%ebp), %edi movl %esi, -16(%ebp) leal -262(%eax,%edi), %esi cmpl %esi, %edx jae .L550 .L462: movl 8(%ebp), %eax movl (%eax), %edi movl 4(%edi), %edx testl %edx, %edx je .L456 movl 8(%ebp), %ecx movl 108(%ecx), %esi addl 56(%ecx), %esi movl 116(%ecx), %eax addl %eax, %esi cmpl -16(%ebp), %edx movl %esi, -24(%ebp) movl %eax, -44(%ebp) movl %edx, %esi jbe .L476 movl -16(%ebp), %esi .L476: xorl %eax, %eax testl %esi, %esi jne .L551 .L478: movl 8(%ebp), %esi movl -44(%ebp), %edi addl %eax, %edi movl 5812(%esi), %edx leal (%edx,%edi), %ecx cmpl $2, %ecx movl %edi, 116(%esi) movl %edx, -48(%ebp) jbe .L545 movl 8(%ebp), %ecx movl 108(%ecx), %esi subl %edx, %esi movl 56(%ecx), %edx movl %edx, -28(%ebp) movzbl (%esi,%edx), %eax movl 88(%ecx), %edx movl %edx, -32(%ebp) movl %eax, 72(%ecx) movb -32(%ebp), %cl sall %cl, %eax movl -28(%ebp), %ecx movzbl 1(%esi,%ecx), %edx xorl %edx, %eax movl 8(%ebp), %edx movl 84(%edx), %ecx movl -48(%ebp), %edx andl %ecx, %eax movl %ecx, -36(%ebp) testl %edx, %edx movl 8(%ebp), %ecx movl %eax, 72(%ecx) je .L546 movl %edi, -44(%ebp) movl 68(%ecx), %eax movl 64(%ecx), %edx movl 52(%ecx), %edi movl %eax, -60(%ebp) movl %edx, -40(%ebp) movl %edi, -52(%ebp) .p2align 2,,3 .L487: movl 8(%ebp), %edi movl 72(%edi), %eax movb -32(%ebp), %cl movl -28(%ebp), %edx sall %cl, %eax movzbl 2(%esi,%edx), %ecx xorl %ecx, %eax andl -36(%ebp), %eax movl 8(%ebp), %ecx movl %eax, 72(%ecx) movl -60(%ebp), %edx movl -52(%ebp), %ecx movw (%edx,%eax,2), %di andl %esi, %ecx movl -40(%ebp), %edx movw %di, (%edx,%ecx,2) movl -48(%ebp), %edx decl %edx movl -44(%ebp), %ecx movl -60(%ebp), %edi addl %edx, %ecx movw %si, (%edi,%eax,2) incl %esi movl 8(%ebp), %eax cmpl $2, %ecx movl %edx, 5812(%eax) jbe .L457 testl %edx, %edx movl %edx, -48(%ebp) jne .L487 .p2align 2,,3 .L457: cmpl $261, -44(%ebp) ja .L456 movl 8(%ebp), %eax movl (%eax), %edi movl 4(%edi), %edx testl %edx, %edx je .L456 movl 8(%ebp), %edi movl 44(%edi), %eax jmp .L455 .L456: movl 8(%ebp), %esi movl 5824(%esi), %edx movl 60(%esi), %ecx cmpl %ecx, %edx movl %esi, %edi jae .L454 movl 116(%esi), %esi addl 108(%edi), %esi cmpl %esi, %edx jae .L491 movl %ecx, %edi subl %esi, %edi cmpl $258, %edi jbe .L492 movl $258, %edi .L492: movl 8(%ebp), %eax movl 56(%eax), %ecx pushl %edx pushl %edi addl %esi, %ecx pushl $0 pushl %ecx call memset@PLT leal (%edi,%esi), %ecx movl 8(%ebp), %edx addl $16, %esp movl %ecx, 5824(%edx) .L454: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L491: leal 258(%esi), %edi cmpl %edi, %edx jae .L454 subl %edx, %esi movl %ecx, %eax leal 258(%esi), %edi subl %edx, %eax cmpl %eax, %edi jbe .L519 movl %eax, %edi .L519: movl 8(%ebp), %ecx addl 56(%ecx), %edx pushl %esi pushl %edi pushl $0 pushl %edx call memset@PLT movl 8(%ebp), %esi addl $16, %esp addl %edi, 5824(%esi) jmp .L454 .p2align 2,,3 .L546: movl %edi, -44(%ebp) jmp .L457 .p2align 2,,3 .L545: movl 8(%ebp), %ecx movl 116(%ecx), %esi movl %esi, -44(%ebp) jmp .L457 .L551: subl %esi, %edx movl %edx, 4(%edi) pushl %eax pushl %esi pushl (%edi) pushl -24(%ebp) call memcpy@PLT movl 28(%edi), %edx movl 24(%edx), %eax addl $16, %esp cmpl $1, %eax je .L552 cmpl $2, %eax je .L553 .L480: addl %esi, (%edi) addl %esi, 8(%edi) movl %esi, %eax movl 8(%ebp), %esi movl 116(%esi), %ecx movl %ecx, -44(%ebp) jmp .L478 .L553: pushl %eax pushl %esi pushl -24(%ebp) pushl 48(%edi) call crc32@PLT .L549: addl $16, %esp movl %eax, 48(%edi) jmp .L480 .L552: pushl %eax pushl %esi pushl -24(%ebp) pushl 48(%edi) call adler32@PLT jmp .L549 .L550: movl 56(%ecx), %esi pushl %ecx leal (%edi,%esi), %edx pushl %edi pushl %edx pushl %esi call memcpy@PLT movl 8(%ebp), %esi subl %edi, 112(%esi) subl %edi, 108(%esi) subl %edi, 92(%esi) movl 76(%esi), %ecx movl 68(%esi), %edi movl %edi, -60(%ebp) leal (%edi,%ecx,2), %edx addl $16, %esp .p2align 2,,3 .L463: subl $2, %edx movzwl (%edx), %eax xorl %esi, %esi cmpl -20(%ebp), %eax jb .L467 movl %eax, %esi subw -20(%ebp), %si .L467: decl %ecx movw %si, (%edx) jne .L463 movl 8(%ebp), %esi movl -20(%ebp), %ecx movl 64(%esi), %eax leal (%eax,%ecx,2), %edx .p2align 2,,3 .L469: subl $2, %edx movzwl (%edx), %eax xorl %esi, %esi cmpl -20(%ebp), %eax jb .L473 movl %eax, %esi subw -20(%ebp), %si .L473: decl %ecx movw %si, (%edx) jne .L469 movl -20(%ebp), %ecx addl %ecx, -16(%ebp) jmp .L462 .size fill_window, .-fill_window # ---------------------- .p2align 2,,3 # ---------------------- .local deflate_stored .type deflate_stored, @function deflate_stored: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $28, %esp movl 8(%ebp), %ecx movl 12(%ecx), %eax movl $65535, -16(%ebp) subl $5, %eax call .L605 .L605: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L605], %ebx cmpl %eax, -16(%ebp) jbe .L557 movl %eax, -16(%ebp) .p2align 2,,3 .L557: movl 8(%ebp), %ecx movl 116(%ecx), %edx cmpl $1, %edx jbe .L599 .L560: movl 8(%ebp), %esi movl 108(%esi), %eax addl %edx, %eax movl 92(%esi), %ecx movl -16(%ebp), %edi testl %eax, %eax movl %eax, 108(%esi) movl $0, 116(%esi) leal (%edi,%ecx), %edx je .L564 cmpl %edx, %eax jb .L563 .L564: subl %edx, %eax movl 8(%ebp), %esi movl %eax, 116(%esi) movl %edx, 108(%esi) xorl %eax, %eax subl %ecx, %edx pushl $0 testl %ecx, %ecx pushl %edx js .L566 movl 56(%esi), %eax addl %ecx, %eax .L566: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %esi movl 108(%esi), %edi movl %edi, 92(%esi) movl (%esi), %edi movl 28(%edi), %eax movl %eax, (%esp) movl %eax, -20(%ebp) call _tr_flush_bits movl -20(%ebp), %ecx movl 20(%ecx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L567 movl %eax, %esi .L567: testl %esi, %esi jne .L600 .L569: movl 8(%ebp), %esi movl (%esi), %edx movl 16(%edx), %edi testl %edi, %edi je .L598 movl 92(%esi), %ecx .L563: movl 8(%ebp), %edi movl 108(%edi), %edx movl %edi, %esi movl 44(%edi), %edi subl %ecx, %edx subl $262, %edi cmpl %edi, %edx jb .L557 pushl $0 xorl %eax, %eax testl %ecx, %ecx pushl %edx js .L574 movl 56(%esi), %eax addl %ecx, %eax .L574: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %esi movl (%esi), %edi movl 108(%esi), %edx movl 28(%edi), %eax movl %edx, 92(%esi) movl %eax, -24(%ebp) movl %eax, (%esp) call _tr_flush_bits movl -24(%ebp), %ecx movl 20(%ecx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L575 movl %eax, %esi .L575: testl %esi, %esi jne .L601 .L577: movl 8(%ebp), %eax movl (%eax), %edi movl 16(%edi), %edx testl %edx, %edx jne .L557 .L598: xorl %eax, %eax .L555: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L601: pushl %eax pushl %esi movl -24(%ebp), %ecx pushl 16(%ecx) pushl 12(%edi) call memcpy@PLT movl -24(%ebp), %ecx subl %esi, 16(%edi) addl %esi, 12(%edi) addl %esi, 20(%edi) movl 20(%ecx), %edi subl %esi, %edi addl $16, %esp addl %esi, 16(%ecx) testl %edi, %edi movl %edi, 20(%ecx) jne .L577 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L577 .p2align 2,,3 .L600: pushl %edx pushl %esi movl -20(%ebp), %ecx pushl 16(%ecx) pushl 12(%edi) call memcpy@PLT movl -20(%ebp), %ecx subl %esi, 16(%edi) movl 20(%ecx), %edx addl %esi, 12(%edi) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%edi) testl %edx, %edx movl %edx, 20(%ecx) jne .L569 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L569 .p2align 2,,3 .L599: subl $12, %esp pushl %ecx call fill_window movl 8(%ebp), %eax movl 116(%eax), %edx addl $16, %esp testl %edx, %edx jne .L560 movl 12(%ebp), %esi xorl %eax, %eax testl %esi, %esi je .L555 testl %edx, %edx jne .L560 movl 8(%ebp), %eax cmpl $4, 12(%ebp) movl $0, 5812(%eax) je .L602 movl 8(%ebp), %esi movl 108(%esi), %eax movl 92(%esi), %edx cmpl %edx, %eax jle .L588 subl %edx, %eax pushl $0 pushl %eax xorl %eax, %eax testl %edx, %edx js .L590 movl 56(%esi), %eax addl %edx, %eax .L590: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %esi movl 108(%esi), %edi movl %edi, 92(%esi) movl (%esi), %edi movl 28(%edi), %edx movl %edx, (%esp) movl %edx, -32(%ebp) call _tr_flush_bits movl -32(%ebp), %ecx movl 20(%ecx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L591 movl %eax, %esi .L591: testl %esi, %esi jne .L603 .L593: movl 8(%ebp), %edx movl (%edx), %edi movl 16(%edi), %ecx testl %ecx, %ecx je .L598 .L588: movl $1, %eax jmp .L555 .L603: pushl %eax pushl %esi movl -32(%ebp), %eax pushl 16(%eax) pushl 12(%edi) call memcpy@PLT movl -32(%ebp), %ecx subl %esi, 16(%edi) movl 20(%ecx), %edx addl %esi, 12(%edi) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%edi) testl %edx, %edx movl %edx, 20(%ecx) jne .L593 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L593 .L602: pushl $1 movl 92(%eax), %edx movl 108(%eax), %esi subl %edx, %esi movl %eax, %edi xorl %eax, %eax testl %edx, %edx pushl %esi js .L582 movl 56(%edi), %eax addl %edx, %eax .L582: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %ecx movl 108(%ecx), %esi movl (%ecx), %edi movl %esi, 92(%ecx) movl 28(%edi), %edx movl %edx, (%esp) movl %edx, -28(%ebp) call _tr_flush_bits movl -28(%ebp), %ecx movl 20(%ecx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L583 movl %eax, %esi .L583: testl %esi, %esi jne .L604 .L585: movl 8(%ebp), %eax movl (%eax), %esi movl 16(%esi), %edi testl %edi, %edi setne %dl movzbl %dl, %eax addl $2, %eax jmp .L555 .L604: pushl %eax pushl %esi movl -28(%ebp), %eax pushl 16(%eax) pushl 12(%edi) call memcpy@PLT movl -28(%ebp), %ecx subl %esi, 16(%edi) addl %esi, 12(%edi) addl %esi, 20(%edi) movl 20(%ecx), %edi subl %esi, %edi addl $16, %esp addl %esi, 16(%ecx) testl %edi, %edi movl %edi, 20(%ecx) jne .L585 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L585 .size deflate_stored, .-deflate_stored # ---------------------- .p2align 2,,3 # ---------------------- .local deflate_fast .type deflate_fast, @function deflate_fast: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $60, %esp call .L659 .L659: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L659], %ebx .p2align 2,,3 .L607: movl 8(%ebp), %eax movl 116(%eax), %edx cmpl $261, %edx jbe .L653 .L610: xorl %ecx, %ecx cmpl $2, %edx jbe .L613 movl 8(%ebp), %esi movl 72(%esi), %edx movl 88(%esi), %ecx movl 56(%esi), %eax sall %cl, %edx movl 108(%esi), %ecx movzbl 2(%ecx,%eax), %edi xorl %edi, %edx movl %esi, %edi andl 84(%esi), %edx movl 68(%edi), %edi movzwl (%edi,%edx,2), %eax andl 52(%esi), %ecx movl %edx, 72(%esi) movl 64(%esi), %esi movw %ax, (%esi,%ecx,2) movl 8(%ebp), %esi movl %eax, %ecx movw 108(%esi), %ax movw %ax, (%edi,%edx,2) .L613: testl %ecx, %ecx je .L614 movl 8(%ebp), %edi movl 108(%edi), %edx movl 44(%edi), %esi subl %ecx, %edx subl $262, %esi cmpl %esi, %edx jbe .L654 .L614: movl 8(%ebp), %eax cmpl $2, 96(%eax) jbe .L615 movw 108(%eax), %si subw 112(%eax), %si movl 5792(%eax), %ecx movb 96(%eax), %dl movl %eax, %edi movl 5796(%eax), %eax movw %si, (%eax,%ecx,2) subl $3, %edx movl 5784(%edi), %eax movb %dl, (%ecx,%eax) movzbl %dl, %eax incl 5792(%edi) decl %esi movzbl _length_code@GOTOFF(%eax,%ebx), %ecx incw 1176(%edi,%ecx,4) cmpw $255, %si ja .L616 movzwl %si, %edi movzbl _dist_code@GOTOFF(%edi,%ebx), %eax .L651: movl 8(%ebp), %esi leal 2432(,%eax,4), %edx incw 8(%edx,%esi) movl 5788(%esi), %edi decl %edi cmpl %edi, 5792(%esi) sete %cl movzbl %cl, %esi movl 8(%ebp), %ecx movl 116(%ecx), %edx movl 96(%ecx), %eax subl %eax, %edx cmpl 128(%ecx), %eax movl %esi, -16(%ebp) movl %edx, 116(%ecx) ja .L618 cmpl $2, %edx jbe .L618 decl %eax movl 88(%ecx), %edi movl %eax, 96(%ecx) movl 56(%ecx), %eax movl %edi, -36(%ebp) movl %eax, -44(%ebp) movl 64(%ecx), %edi movl 84(%ecx), %edx movl 52(%ecx), %esi movl 8(%ebp), %eax movl %edi, -48(%ebp) movl %edx, -32(%ebp) movl %esi, -40(%ebp) movl 68(%eax), %edi .p2align 2,,3 .L619: movl 8(%ebp), %ecx movl 108(%ecx), %edx movl %edx, -60(%ebp) incl %edx movl %edx, -52(%ebp) movl 8(%ebp), %esi movl %edx, 108(%esi) movl 72(%esi), %eax movl -52(%ebp), %edx movb -36(%ebp), %cl movl -44(%ebp), %esi sall %cl, %eax movzbl 2(%edx,%esi), %ecx xorl %ecx, %eax movl -40(%ebp), %esi andl -32(%ebp), %eax movl 8(%ebp), %ecx andl %esi, -52(%ebp) movl -52(%ebp), %esi movl %eax, 72(%ecx) movl -48(%ebp), %edx movw (%edi,%eax,2), %cx movw %cx, (%edx,%esi,2) movl 8(%ebp), %esi movw 108(%esi), %cx movw %cx, (%edi,%eax,2) movl 96(%esi), %ecx decl %ecx testl %ecx, %ecx movl %ecx, 96(%esi) jne .L619 movl -60(%ebp), %edi addl $2, %edi movl %edi, 108(%esi) .p2align 2,,3 .L624: movl -16(%ebp), %esi testl %esi, %esi je .L607 pushl $0 movl 8(%ebp), %edi movl 92(%edi), %edx movl 108(%edi), %ecx subl %edx, %ecx xorl %eax, %eax testl %edx, %edx pushl %ecx js .L627 movl 56(%edi), %eax addl %edx, %eax .L627: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %esi movl 108(%esi), %edi movl %edi, 92(%esi) movl (%esi), %edi movl 28(%edi), %eax movl %eax, (%esp) movl %eax, -20(%ebp) call _tr_flush_bits movl -20(%ebp), %edx movl 20(%edx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L628 movl %eax, %esi .L628: testl %esi, %esi jne .L655 .L630: movl 8(%ebp), %eax movl (%eax), %edx movl 16(%edx), %edi testl %edi, %edi jne .L607 .L652: xorl %eax, %eax .L606: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L655: pushl %eax pushl %esi movl -20(%ebp), %ecx pushl 16(%ecx) pushl 12(%edi) call memcpy@PLT movl -20(%ebp), %ecx subl %esi, 16(%edi) movl 20(%ecx), %edx addl %esi, 12(%edi) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%edi) testl %edx, %edx movl %edx, 20(%ecx) jne .L630 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L630 .p2align 2,,3 .L618: movl 8(%ebp), %edi movl 108(%edi), %edx addl %eax, %edx movl %edx, 108(%edi) movl $0, 96(%edi) movl 56(%edi), %esi movzbl (%edx,%esi), %eax movl %eax, 72(%edi) movl 88(%edi), %ecx sall %cl, %eax movzbl 1(%edx,%esi), %ecx xorl %ecx, %eax andl 84(%edi), %eax movl %eax, 72(%edi) jmp .L624 .p2align 2,,3 .L616: shrw $7, %si movzwl %si, %edx movzbl _dist_code@GOTOFF+256(%edx,%ebx), %eax jmp .L651 .p2align 2,,3 .L615: movl 8(%ebp), %edx movl 108(%edx), %ecx movl 56(%edx), %edi movl %edx, %esi movb (%ecx,%edi), %dl movl %esi, %edi movl 5796(%edi), %ecx movl 5792(%esi), %esi movw $0, (%ecx,%esi,2) movl 5784(%edi), %ecx movb %dl, (%esi,%ecx) incl 5792(%edi) movzbl %dl, %eax incw 148(%edi,%eax,4) movl 5788(%edi), %ecx decl %ecx cmpl %ecx, 5792(%edi) sete %dl movzbl %dl, %esi movl %esi, -16(%ebp) decl 116(%edi) incl 108(%edi) jmp .L624 .p2align 2,,3 .L654: subl $8, %esp pushl %ecx pushl %edi call longest_match movl %eax, 96(%edi) addl $16, %esp jmp .L614 .p2align 2,,3 .L653: subl $12, %esp pushl %eax call fill_window movl 8(%ebp), %eax movl 116(%eax), %edx addl $16, %esp cmpl $261, %edx ja .L611 movl 12(%ebp), %esi xorl %eax, %eax testl %esi, %esi je .L606 .L611: testl %edx, %edx jne .L610 movl 8(%ebp), %ecx movl 108(%ecx), %eax cmpl $2, %eax movl %eax, %edx jbe .L633 movl $2, %edx .L633: movl 8(%ebp), %ecx cmpl $4, 12(%ebp) movl %edx, 5812(%ecx) je .L656 movl 8(%ebp), %esi movl 5792(%esi), %ecx testl %ecx, %ecx je .L642 pushl $0 movl 92(%esi), %edx subl %edx, %eax pushl %eax xorl %eax, %eax testl %edx, %edx js .L644 movl 56(%esi), %eax addl %edx, %eax .L644: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %edx movl 108(%edx), %edi movl %edi, 92(%edx) movl (%edx), %edi movl 28(%edi), %esi movl %esi, (%esp) movl %esi, -28(%ebp) call _tr_flush_bits movl -28(%ebp), %edx movl 20(%edx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L645 movl %eax, %esi .L645: testl %esi, %esi jne .L657 .L647: movl 8(%ebp), %eax movl (%eax), %edx movl 16(%edx), %edi testl %edi, %edi je .L652 .L642: movl $1, %eax jmp .L606 .L657: pushl %eax pushl %esi movl -28(%ebp), %edx pushl 16(%edx) pushl 12(%edi) call memcpy@PLT movl -28(%ebp), %edx subl %esi, 16(%edi) movl 20(%edx), %ecx addl %esi, 12(%edi) subl %esi, %ecx addl $16, %esp addl %esi, 16(%edx) addl %esi, 20(%edi) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L647 movl 8(%edx), %esi movl %esi, 16(%edx) jmp .L647 .L656: pushl $1 movl 92(%ecx), %edx subl %edx, %eax pushl %eax xorl %eax, %eax testl %edx, %edx js .L636 movl 56(%ecx), %eax addl %edx, %eax .L636: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %edx movl 108(%edx), %edi movl %edi, 92(%edx) movl (%edx), %edi movl 28(%edi), %esi movl %esi, (%esp) movl %esi, -24(%ebp) call _tr_flush_bits movl -24(%ebp), %eax movl 20(%eax), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L637 movl %eax, %esi .L637: testl %esi, %esi jne .L658 .L639: movl 8(%ebp), %eax movl (%eax), %esi movl 16(%esi), %edi testl %edi, %edi setne %dl movzbl %dl, %eax addl $2, %eax jmp .L606 .L658: pushl %eax pushl %esi movl -24(%ebp), %eax pushl 16(%eax) pushl 12(%edi) call memcpy@PLT movl -24(%ebp), %ecx subl %esi, 16(%edi) addl %esi, 12(%edi) addl %esi, 16(%ecx) movl %ecx, %edx movl 20(%ecx), %ecx subl %esi, %ecx addl $16, %esp addl %esi, 20(%edi) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L639 movl 8(%edx), %esi movl %esi, 16(%edx) jmp .L639 .size deflate_fast, .-deflate_fast # ---------------------- .p2align 2,,3 # ---------------------- .local deflate_slow .type deflate_slow, @function deflate_slow: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $44, %esp call .L734 .L734: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L734], %ebx .p2align 2,,3 .L661: movl 8(%ebp), %eax movl 116(%eax), %edx cmpl $261, %edx jbe .L724 .L664: xorl %ecx, %ecx cmpl $2, %edx jbe .L716 movl 8(%ebp), %esi movl 108(%esi), %edi movl 72(%esi), %edx movl 88(%esi), %ecx movl 56(%esi), %eax movl %edi, -40(%ebp) sall %cl, %edx movzbl 2(%edi,%eax), %ecx xorl %ecx, %edx andl 84(%esi), %edx andl 52(%esi), %edi movl 64(%esi), %ecx movl %edx, 72(%esi) movl 68(%esi), %esi movzwl (%esi,%edx,2), %eax movw %ax, (%ecx,%edi,2) movl 8(%ebp), %edi movl %eax, %ecx movw 108(%edi), %ax movw %ax, (%esi,%edx,2) .L667: movl 8(%ebp), %esi movl 96(%esi), %edx movl 112(%esi), %edi testl %ecx, %ecx movl %edx, 120(%esi) movl %edi, 100(%esi) movl $2, 96(%esi) je .L668 cmpl 128(%esi), %edx jae .L668 movl -40(%ebp), %eax movl 44(%esi), %edi subl %ecx, %eax subl $262, %edi cmpl %edi, %eax jbe .L725 .L668: movl 8(%ebp), %edi movl 120(%edi), %eax cmpl $2, %eax jbe .L671 cmpl %eax, 96(%edi) jbe .L726 .L671: movl 8(%ebp), %edi movl 104(%edi), %eax testl %eax, %eax jne .L727 movl -40(%ebp), %esi movl 8(%ebp), %ecx incl %esi movl $1, 104(%ecx) movl %esi, 108(%ecx) decl 116(%ecx) jmp .L661 .L727: movl 56(%edi), %edx addl %edx, -40(%ebp) movl 5792(%edi), %esi movl 5796(%edi), %ecx movl -40(%ebp), %eax movb -1(%eax), %dl movw $0, (%ecx,%esi,2) movl 5784(%edi), %ecx movb %dl, (%esi,%ecx) incl 5792(%edi) movzbl %dl, %ecx incw 148(%edi,%ecx,4) movl 5788(%edi), %edx decl %edx cmpl %edx, 5792(%edi) jne .L689 pushl $0 movl 92(%edi), %edx movl 108(%edi), %esi subl %edx, %esi xorl %eax, %eax testl %edx, %edx pushl %esi js .L691 movl 56(%edi), %eax addl %edx, %eax .L691: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %ecx movl 108(%ecx), %edi movl %edi, 92(%ecx) movl (%ecx), %edi movl 28(%edi), %edx movl %edx, (%esp) movl %edx, -28(%ebp) call _tr_flush_bits movl -28(%ebp), %ecx movl 20(%ecx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L692 movl %eax, %esi .L692: testl %esi, %esi jne .L728 .L689: movl 8(%ebp), %edx incl 108(%edx) decl 116(%edx) movl (%edx), %eax .L723: movl 16(%eax), %edi testl %edi, %edi jne .L661 .L722: xorl %eax, %eax .L660: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L728: pushl %edx pushl %esi movl -28(%ebp), %eax pushl 16(%eax) pushl 12(%edi) call memcpy@PLT movl -28(%ebp), %ecx subl %esi, 16(%edi) addl %esi, 12(%edi) addl %esi, 16(%ecx) movl %ecx, %edx movl 20(%ecx), %ecx subl %esi, %ecx addl $16, %esp addl %esi, 20(%edi) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L689 movl 8(%edx), %esi movl %esi, 16(%edx) jmp .L689 .p2align 2,,3 .L726: movl 116(%edi), %esi addl %esi, -40(%ebp) movw 108(%edi), %dx movl -40(%ebp), %ecx subw 100(%edi), %dx movl 8(%ebp), %eax subl $3, %ecx movl 5792(%eax), %esi movl %ecx, -20(%ebp) movl 5796(%eax), %eax movb 120(%edi), %cl leal -1(%edx), %edi movw %di, (%eax,%esi,2) movl 8(%ebp), %edi movl 5784(%edi), %eax subl $3, %ecx movb %cl, (%esi,%eax) movzbl %cl, %eax incl 5792(%edi) movl 8(%ebp), %esi leal -2(%edx), %edi movzbl _length_code@GOTOFF(%eax,%ebx), %edx incw 1176(%esi,%edx,4) cmpw $255, %di ja .L672 movzwl %di, %edx movzbl _dist_code@GOTOFF(%edx,%ebx), %eax .L721: movl 8(%ebp), %edi leal 2432(,%eax,4), %ecx incw 8(%ecx,%edi) movl 5788(%edi), %esi decl %esi cmpl %esi, 5792(%edi) sete %dl movl 120(%edi), %esi movzbl %dl, %ecx movl 116(%edi), %edx subl %esi, %edx incl %edx subl $2, %esi movl %ecx, -16(%ebp) movl %edx, 116(%edi) movl %esi, 120(%edi) .p2align 2,,3 .L674: movl 8(%ebp), %esi movl 108(%esi), %edi incl %edi cmpl -20(%ebp), %edi movl %edi, 108(%esi) ja .L676 movl 72(%esi), %edx movl 88(%esi), %ecx movl 56(%esi), %eax sall %cl, %edx movzbl 2(%edi,%eax), %ecx xorl %ecx, %edx movl %esi, %eax andl 84(%esi), %edx movl 68(%eax), %ecx andl 52(%esi), %edi movw (%ecx,%edx,2), %ax movl %edx, 72(%esi) movl 64(%esi), %esi movw %ax, (%esi,%edi,2) movl 8(%ebp), %eax movw 108(%eax), %di movw %di, (%ecx,%edx,2) .L676: movl 8(%ebp), %edi movl 120(%edi), %edx decl %edx testl %edx, %edx movl %edx, 120(%edi) jne .L674 movl 108(%edi), %eax movl -16(%ebp), %esi incl %eax testl %esi, %esi movl $0, 104(%edi) movl $2, 96(%edi) movl %eax, 108(%edi) je .L661 pushl $0 movl 92(%edi), %edx subl %edx, %eax pushl %eax xorl %eax, %eax testl %edx, %edx js .L681 movl 56(%edi), %eax addl %edx, %eax .L681: pushl %eax pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %esi movl 108(%esi), %edi movl %edi, 92(%esi) movl (%esi), %edi movl 28(%edi), %eax movl %eax, (%esp) movl %eax, -24(%ebp) call _tr_flush_bits movl -24(%ebp), %ecx movl 20(%ecx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L682 movl %eax, %esi .L682: testl %esi, %esi jne .L729 .L684: movl 8(%ebp), %edi movl (%edi), %eax jmp .L723 .L729: pushl %eax pushl %esi movl -24(%ebp), %ecx pushl 16(%ecx) pushl 12(%edi) call memcpy@PLT movl -24(%ebp), %ecx subl %esi, 16(%edi) movl 20(%ecx), %edx addl %esi, 12(%edi) subl %esi, %edx addl $16, %esp addl %esi, 16(%ecx) addl %esi, 20(%edi) testl %edx, %edx movl %edx, 20(%ecx) jne .L684 movl 8(%ecx), %esi movl %esi, 16(%ecx) jmp .L684 .p2align 2,,3 .L672: shrw $7, %di movzwl %di, %ecx movzbl _dist_code@GOTOFF+256(%ecx,%ebx), %eax jmp .L721 .L725: subl $8, %esp pushl %ecx pushl %esi call longest_match addl $16, %esp cmpl $5, %eax movl %eax, 96(%esi) ja .L717 cmpl $1, 136(%esi) je .L718 cmpl $3, %eax je .L730 movl 8(%ebp), %edi movl 108(%edi), %ecx movl %ecx, -40(%ebp) jmp .L668 .L730: movl 108(%esi), %edx movl %edx, %ecx subl 112(%esi), %ecx cmpl $4096, %ecx movl %edx, -40(%ebp) jbe .L668 .L670: movl 8(%ebp), %eax movl $2, 96(%eax) jmp .L668 .L718: movl 8(%ebp), %edi movl 108(%edi), %esi movl %esi, -40(%ebp) jmp .L670 .L717: movl 8(%ebp), %esi movl 108(%esi), %edx movl %edx, -40(%ebp) jmp .L668 .p2align 2,,3 .L716: movl 8(%ebp), %edi movl 108(%edi), %edx movl %edx, -40(%ebp) jmp .L667 .p2align 2,,3 .L724: subl $12, %esp pushl %eax call fill_window movl 8(%ebp), %eax movl 116(%eax), %edx addl $16, %esp cmpl $261, %edx ja .L665 movl 12(%ebp), %esi xorl %eax, %eax testl %esi, %esi je .L660 .L665: testl %edx, %edx jne .L664 movl 8(%ebp), %edi movl 104(%edi), %edx testl %edx, %edx je .L698 movl 108(%edi), %esi addl 56(%edi), %esi movb -1(%esi), %dl movl 5796(%edi), %ecx movl 5792(%edi), %esi movw $0, (%ecx,%esi,2) movl 5784(%edi), %ecx movb %dl, (%esi,%ecx) incl 5792(%edi) movzbl %dl, %eax incw 148(%edi,%eax,4) movl $0, 104(%edi) .L698: movl 8(%ebp), %edi movl 108(%edi), %eax cmpl $2, %eax movl %eax, -40(%ebp) jbe .L699 movl $2, %eax .L699: movl 8(%ebp), %edx cmpl $4, 12(%ebp) movl %eax, 5812(%edx) je .L731 movl 8(%ebp), %esi movl 5792(%esi), %ecx testl %ecx, %ecx je .L708 pushl $0 movl 92(%esi), %eax subl %eax, -40(%ebp) xorl %edx, %edx testl %eax, %eax pushl -40(%ebp) js .L710 movl 56(%esi), %edx addl %eax, %edx .L710: pushl %edx pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %edx movl 108(%edx), %edi movl %edi, 92(%edx) movl (%edx), %edi movl 28(%edi), %esi movl %esi, (%esp) movl %esi, -36(%ebp) call _tr_flush_bits movl -36(%ebp), %edx movl 20(%edx), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L711 movl %eax, %esi .L711: testl %esi, %esi jne .L732 .L713: movl 8(%ebp), %eax movl (%eax), %edx movl 16(%edx), %edi testl %edi, %edi je .L722 .L708: movl $1, %eax jmp .L660 .L732: pushl %eax pushl %esi movl -36(%ebp), %edx pushl 16(%edx) pushl 12(%edi) call memcpy@PLT movl -36(%ebp), %edx subl %esi, 16(%edi) movl 20(%edx), %ecx addl %esi, 12(%edi) subl %esi, %ecx addl $16, %esp addl %esi, 16(%edx) addl %esi, 20(%edi) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L713 movl 8(%edx), %esi movl %esi, 16(%edx) jmp .L713 .L731: pushl $1 movl 92(%edx), %eax subl %eax, -40(%ebp) xorl %edx, %edx testl %eax, %eax pushl -40(%ebp) js .L702 movl 8(%ebp), %esi movl 56(%esi), %edx addl %eax, %edx .L702: pushl %edx pushl 8(%ebp) call _tr_flush_block movl 8(%ebp), %ecx movl 108(%ecx), %edi movl %edi, 92(%ecx) movl (%ecx), %edi movl 28(%edi), %edx movl %edx, (%esp) movl %edx, -32(%ebp) call _tr_flush_bits movl -32(%ebp), %eax movl 20(%eax), %esi movl 16(%edi), %eax addl $16, %esp cmpl %eax, %esi jbe .L703 movl %eax, %esi .L703: testl %esi, %esi jne .L733 .L705: movl 8(%ebp), %eax movl (%eax), %esi movl 16(%esi), %edi testl %edi, %edi setne %dl movzbl %dl, %eax addl $2, %eax jmp .L660 .L733: pushl %eax pushl %esi movl -32(%ebp), %eax pushl 16(%eax) pushl 12(%edi) call memcpy@PLT movl -32(%ebp), %ecx subl %esi, 16(%edi) addl %esi, 12(%edi) addl %esi, 16(%ecx) movl %ecx, %edx movl 20(%ecx), %ecx subl %esi, %ecx addl $16, %esp addl %esi, 20(%edi) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L705 movl 8(%edx), %esi movl %esi, 16(%edx) jmp .L705 .size deflate_slow, .-deflate_slow # ---------------------- .p2align 2,,3 # ---------------------- .local deflate_rle .type deflate_rle, @function deflate_rle: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $28, %esp call .L786 .L786: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L786], %ebx movl 8(%ebp), %esi .p2align 2,,3 .L736: movl 116(%esi), %edx cmpl $258, %edx jbe .L780 .L739: cmpl $2, %edx movl $0, 96(%esi) jbe .L742 movl 108(%esi), %eax testl %eax, %eax je .L742 movl 56(%esi), %edi addl %eax, %edi movzbl -1(%edi), %ecx movl %ecx, -16(%ebp) movzbl (%edi), %eax cmpl %eax, -16(%ebp) movl %edi, %ecx je .L781 .L742: cmpl $2, 96(%esi) jbe .L750 movl 5792(%esi), %edi movb 96(%esi), %dl movl 5796(%esi), %ecx movw $1, (%ecx,%edi,2) subl $3, %edx movl 5784(%esi), %ecx movb %dl, (%edi,%ecx) movzbl %dl, %eax incl 5792(%esi) movzbl _length_code@GOTOFF(%eax,%ebx), %edi incw 1176(%esi,%edi,4) movzbl _dist_code@GOTOFF(%ebx), %edx incw 2440(%esi,%edx,4) movl 5788(%esi), %ecx decl %ecx movl 96(%esi), %edi xorl %edx, %edx cmpl %ecx, 5792(%esi) sete %dl movl $0, 96(%esi) subl %edi, 116(%esi) addl %edi, 108(%esi) .L753: testl %edx, %edx je .L736 pushl $0 movl 92(%esi), %edx movl 108(%esi), %edi subl %edx, %edi xorl %eax, %eax testl %edx, %edx pushl %edi js .L756 movl 56(%esi), %eax addl %edx, %eax .L756: pushl %eax pushl %esi call _tr_flush_block movl (%esi), %ecx movl 108(%esi), %edx movl 28(%ecx), %edi movl %edx, 92(%esi) movl %ecx, -20(%ebp) movl %edi, (%esp) movl %edi, -24(%ebp) call _tr_flush_bits movl -24(%ebp), %eax movl -20(%ebp), %ecx movl 20(%eax), %edi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %edi jbe .L757 movl %eax, %edi .L757: testl %edi, %edi jne .L782 .L759: movl (%esi), %edx movl 16(%edx), %ecx testl %ecx, %ecx jne .L736 .L779: xorl %eax, %eax .L735: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L782: pushl %eax pushl %edi movl -24(%ebp), %edx pushl 16(%edx) movl -20(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl -20(%ebp), %ecx movl -24(%ebp), %edx subl %edi, 16(%ecx) addl %edi, 12(%ecx) addl %edi, 20(%ecx) movl 20(%edx), %ecx subl %edi, %ecx addl $16, %esp addl %edi, 16(%edx) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L759 movl 8(%edx), %edi movl %edi, 16(%edx) jmp .L759 .p2align 2,,3 .L750: movl 108(%esi), %ecx movl 56(%esi), %edi movb (%ecx,%edi), %dl movl 5792(%esi), %edi movl 5796(%esi), %ecx movw $0, (%ecx,%edi,2) movl 5784(%esi), %ecx movb %dl, (%edi,%ecx) incl 5792(%esi) movzbl %dl, %eax incw 148(%esi,%eax,4) movl 5788(%esi), %edi decl %edi xorl %edx, %edx cmpl %edi, 5792(%esi) sete %dl decl 116(%esi) incl 108(%esi) jmp .L753 .L781: incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L742 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L742 addl $258, %edi .L744: incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 incl %ecx movzbl (%ecx), %eax cmpl %eax, -16(%ebp) jne .L745 cmpl %edi, %ecx jb .L744 .L745: subl %ecx, %edi movl $258, %ecx subl %edi, %ecx cmpl %edx, %ecx movl %ecx, 96(%esi) jbe .L742 movl %edx, 96(%esi) jmp .L742 .p2align 2,,3 .L780: subl $12, %esp pushl %esi call fill_window movl 116(%esi), %edx addl $16, %esp cmpl $258, %edx ja .L740 movl 12(%ebp), %edi xorl %eax, %eax testl %edi, %edi je .L735 .L740: testl %edx, %edx jne .L739 cmpl $4, 12(%ebp) movl $0, 5812(%esi) je .L783 movl 5792(%esi), %edi testl %edi, %edi je .L770 pushl $0 movl 92(%esi), %edx movl 108(%esi), %ecx subl %edx, %ecx xorl %eax, %eax testl %edx, %edx pushl %ecx js .L772 movl 56(%esi), %eax addl %edx, %eax .L772: pushl %eax pushl %esi call _tr_flush_block movl (%esi), %ecx movl 108(%esi), %edx movl 28(%ecx), %edi movl %edx, 92(%esi) movl %ecx, -36(%ebp) movl %edi, (%esp) movl %edi, -40(%ebp) call _tr_flush_bits movl -40(%ebp), %edx movl -36(%ebp), %ecx movl 20(%edx), %edi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %edi jbe .L773 movl %eax, %edi .L773: testl %edi, %edi jne .L784 .L775: movl (%esi), %edx movl 16(%edx), %ecx testl %ecx, %ecx je .L779 .L770: movl $1, %eax jmp .L735 .L784: pushl %eax pushl %edi movl -40(%ebp), %edx pushl 16(%edx) movl -36(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl -36(%ebp), %ecx movl -40(%ebp), %edx subl %edi, 16(%ecx) addl %edi, 12(%ecx) addl %edi, 20(%ecx) movl 20(%edx), %ecx subl %edi, %ecx addl $16, %esp addl %edi, 16(%edx) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L775 movl 8(%edx), %edi movl %edi, 16(%edx) jmp .L775 .L783: pushl $1 movl 92(%esi), %edx movl 108(%esi), %edi subl %edx, %edi xorl %eax, %eax testl %edx, %edx pushl %edi js .L764 movl 56(%esi), %eax addl %edx, %eax .L764: pushl %eax pushl %esi call _tr_flush_block movl (%esi), %ecx movl 108(%esi), %edx movl 28(%ecx), %edi movl %edx, 92(%esi) movl %ecx, -28(%ebp) movl %edi, (%esp) movl %edi, -32(%ebp) call _tr_flush_bits movl -32(%ebp), %edx movl -28(%ebp), %ecx movl 20(%edx), %edi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %edi jbe .L765 movl %eax, %edi .L765: testl %edi, %edi jne .L785 .L767: movl (%esi), %edx movl 16(%edx), %esi testl %esi, %esi setne %cl movzbl %cl, %eax addl $2, %eax jmp .L735 .L785: pushl %eax pushl %edi movl -32(%ebp), %edx pushl 16(%edx) movl -28(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl -28(%ebp), %ecx movl -32(%ebp), %edx subl %edi, 16(%ecx) addl %edi, 12(%ecx) addl %edi, 20(%ecx) movl 20(%edx), %ecx subl %edi, %ecx addl $16, %esp addl %edi, 16(%edx) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L767 movl 8(%edx), %edi movl %edi, 16(%edx) jmp .L767 .size deflate_rle, .-deflate_rle # ---------------------- .p2align 2,,3 # ---------------------- .local deflate_huff .type deflate_huff, @function deflate_huff: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi pushl %ebx subl $28, %esp call .L824 .L824: popl %ebx addl $_GLOBAL_OFFSET_TABLE_+[.-.L824], %ebx movl 8(%ebp), %esi .p2align 2,,3 .L788: movl 116(%esi), %eax testl %eax, %eax je .L819 .L791: movl 108(%esi), %ecx movl 56(%esi), %edi movl $0, 96(%esi) movb (%ecx,%edi), %dl movl 5792(%esi), %edi movl 5796(%esi), %ecx movw $0, (%ecx,%edi,2) movl 5784(%esi), %ecx movb %dl, (%edi,%ecx) incl 5792(%esi) movzbl %dl, %edi incw 148(%esi,%edi,4) movl 5788(%esi), %edx decl %edx cmpl %edx, 5792(%esi) sete %al movl 108(%esi), %edx incl %edx decl 116(%esi) testb $1, %al movl %edx, 108(%esi) je .L788 pushl $0 movl 92(%esi), %eax subl %eax, %edx pushl %edx xorl %edx, %edx testl %eax, %eax js .L796 movl 56(%esi), %edx addl %eax, %edx .L796: pushl %edx pushl %esi call _tr_flush_block movl (%esi), %ecx movl 108(%esi), %edx movl 28(%ecx), %edi movl %edx, 92(%esi) movl %ecx, -16(%ebp) movl %edi, (%esp) movl %edi, -20(%ebp) call _tr_flush_bits movl -20(%ebp), %edx movl -16(%ebp), %ecx movl 20(%edx), %edi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %edi jbe .L797 movl %eax, %edi .L797: testl %edi, %edi jne .L820 .L799: movl (%esi), %edx movl 16(%edx), %ecx testl %ecx, %ecx jne .L788 .L818: xorl %eax, %eax .L787: leal -12(%ebp), %esp popl %ebx popl %esi popl %edi leave ret .L820: pushl %eax pushl %edi movl -20(%ebp), %edx pushl 16(%edx) movl -16(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl -16(%ebp), %ecx movl -20(%ebp), %edx subl %edi, 16(%ecx) addl %edi, 12(%ecx) addl %edi, 20(%ecx) movl 20(%edx), %ecx subl %edi, %ecx addl $16, %esp addl %edi, 16(%edx) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L799 movl 8(%edx), %edi movl %edi, 16(%edx) jmp .L799 .p2align 2,,3 .L819: subl $12, %esp pushl %esi call fill_window movl 116(%esi), %eax addl $16, %esp testl %eax, %eax jne .L791 movl 12(%ebp), %ecx xorl %eax, %eax testl %ecx, %ecx je .L787 cmpl $4, 12(%ebp) movl $0, 5812(%esi) je .L821 movl 5792(%esi), %edi testl %edi, %edi je .L810 pushl $0 movl 92(%esi), %edx movl 108(%esi), %ecx subl %edx, %ecx xorl %eax, %eax testl %edx, %edx pushl %ecx js .L812 movl 56(%esi), %eax addl %edx, %eax .L812: pushl %eax pushl %esi call _tr_flush_block movl (%esi), %ecx movl 108(%esi), %edx movl 28(%ecx), %edi movl %edx, 92(%esi) movl %ecx, -32(%ebp) movl %edi, (%esp) movl %edi, -36(%ebp) call _tr_flush_bits movl -36(%ebp), %edx movl -32(%ebp), %ecx movl 20(%edx), %edi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %edi jbe .L813 movl %eax, %edi .L813: testl %edi, %edi jne .L822 .L815: movl (%esi), %edx movl 16(%edx), %ecx testl %ecx, %ecx je .L818 .L810: movl $1, %eax jmp .L787 .L822: pushl %eax pushl %edi movl -36(%ebp), %edx pushl 16(%edx) movl -32(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl -32(%ebp), %ecx movl -36(%ebp), %edx subl %edi, 16(%ecx) addl %edi, 12(%ecx) addl %edi, 20(%ecx) movl 20(%edx), %ecx subl %edi, %ecx addl $16, %esp addl %edi, 16(%edx) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L815 movl 8(%edx), %edi movl %edi, 16(%edx) jmp .L815 .L821: pushl $1 movl 92(%esi), %edx movl 108(%esi), %edi subl %edx, %edi xorl %eax, %eax testl %edx, %edx pushl %edi js .L804 movl 56(%esi), %eax addl %edx, %eax .L804: pushl %eax pushl %esi call _tr_flush_block movl (%esi), %ecx movl 108(%esi), %edx movl 28(%ecx), %edi movl %edx, 92(%esi) movl %ecx, -24(%ebp) movl %edi, (%esp) movl %edi, -28(%ebp) call _tr_flush_bits movl -28(%ebp), %edx movl -24(%ebp), %ecx movl 20(%edx), %edi movl 16(%ecx), %eax addl $16, %esp cmpl %eax, %edi jbe .L805 movl %eax, %edi .L805: testl %edi, %edi jne .L823 .L807: movl (%esi), %edx movl 16(%edx), %esi testl %esi, %esi setne %cl movzbl %cl, %eax addl $2, %eax jmp .L787 .L823: pushl %eax pushl %edi movl -28(%ebp), %edx pushl 16(%edx) movl -24(%ebp), %eax pushl 12(%eax) call memcpy@PLT movl -24(%ebp), %ecx movl -28(%ebp), %edx subl %edi, 16(%ecx) addl %edi, 12(%ecx) addl %edi, 20(%ecx) movl 20(%edx), %ecx subl %edi, %ecx addl $16, %esp addl %edi, 16(%edx) testl %ecx, %ecx movl %ecx, 20(%edx) jne .L807 movl 8(%edx), %edi movl %edi, 16(%edx) jmp .L807 .size deflate_huff, .-deflate_huff # ---------------------- .p2align 2,,3 # ---------------------- .local longest_match .type longest_match, @function longest_match: pushl %ebp movl %esp, %ebp pushl %edi pushl %esi subl $40, %esp movl 8(%ebp), %esi movl 56(%esi), %eax movl 8(%ebp), %esi movl %eax, -16(%ebp) movl 120(%esi), %eax movl 8(%ebp), %edi movl %eax, -20(%ebp) movl 144(%esi), %eax movl 124(%edi), %edx movl %eax, -24(%ebp) movl 8(%ebp), %eax movl %edx, -12(%ebp) movl 108(%esi), %edx movl 44(%eax), %esi movl -16(%ebp), %edi leal -262(%esi), %eax addl %edx, %edi cmpl %eax, %edx movl 12(%ebp), %ecx jbe .L435 movl %edx, %eax subl %esi, %eax addl $262, %eax movl %eax, -28(%ebp) .L436: movl 8(%ebp), %esi movl 64(%esi), %eax movl %eax, -32(%ebp) movl 8(%ebp), %eax movl 52(%eax), %esi movl %esi, -36(%ebp) movl -16(%ebp), %esi leal 258(%edx,%esi), %eax movl %eax, -40(%ebp) movl -20(%ebp), %eax leal (%eax,%edi), %esi movb -1(%esi), %al movb %al, -41(%ebp) movb (%esi), %dl movb %dl, -42(%ebp) movl -20(%ebp), %esi movl 8(%ebp), %edx cmpl 140(%edx), %esi jb .L437 shrl $2, -12(%ebp) .L437: movl 8(%ebp), %esi movl 116(%esi), %edx cmpl %edx, -24(%ebp) movl %edx, -48(%ebp) jbe .L439 movl %edx, -24(%ebp) .p2align 2,,3 .L439: movl -16(%ebp), %edx addl %ecx, %edx movb -42(%ebp), %al movl -20(%ebp), %esi cmpb %al, (%esi,%edx) je .L937 .L441: movl -36(%ebp), %esi andl %ecx, %esi movl -32(%ebp), %edx movzwl (%edx,%esi,2), %ecx cmpl -28(%ebp), %ecx jbe .L440 decl -12(%ebp) jne .L439 .L440: movl -20(%ebp), %eax cmpl -48(%ebp), %eax jbe .L434 movl -48(%ebp), %eax .L434: addl $40, %esp popl %esi popl %edi leave ret .p2align 2,,3 .L937: movb -41(%ebp), %al cmpb %al, -1(%esi,%edx) jne .L441 movb (%edi), %al cmpb %al, (%edx) jne .L441 incl %edx movb 1(%edi), %al cmpb %al, (%edx) jne .L441 addl $2, %edi incl %edx .L444: incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 incl %edx incl %edi movb (%edx), %al cmpb %al, (%edi) jne .L445 cmpl -40(%ebp), %edi jb .L444 .L445: movl -40(%ebp), %esi subl %edi, %esi movl $258, %edx subl %esi, %edx movl -40(%ebp), %edi subl $258, %edi cmpl -20(%ebp), %edx jle .L441 movl -24(%ebp), %esi movl 8(%ebp), %eax cmpl %esi, %edx movl %ecx, 112(%eax) movl %edx, -20(%ebp) jge .L440 leal (%edx,%edi), %esi movb -1(%esi), %al movb %al, -41(%ebp) movb (%esi), %dl movb %dl, -42(%ebp) jmp .L441 .p2align 2,,3 .L435: movl $0, -28(%ebp) jmp .L436 .size longest_match, .-longest_match # ---------------------- .ident "GCC: (GNU) 3.2.3 20030502 (Red Hat Linux 3.2.3-59)" .section .note.GNU-stack,"",@progbits
copyright zengfr site:http://github.com/zengfr/romhack 006080 tst.b ($53,A6) 006084 ble $60e0 [123p+ 53, enemy+53] 01302C move.b ($a,A0), ($53,A6) 013032 tst.w (A0) [123p+ 53, enemy+53, etc+53, item+53] 0142BE tst.b ($53,A0) 0142C2 beq $142d8 [123p+ 53, enemy+53, item+53] 01439C bset #$7, ($53,A0) 0143A2 btst #$5, ($25,A0) [123p+ 53, enemy+53, item+53] 014494 tst.b ($53,A0) 014498 beq $144ae [123p+ 53, enemy+53, etc+53, item+53] 01463E bset #$7, ($53,A0) 014644 btst #$5, ($25,A0) [123p+ 53, enemy+53, item+53] 014EE8 tst.b ($53,A0) [123p+ 56, enemy+56, item+56] 014EEC beq $14f06 [123p+ 53, enemy+53, item+53] 014EF0 btst #$7, ($53,A0) 014EF6 bne $14f92 [123p+ 53, enemy+53] 092E64 tst.b ($53,A6) 092E68 beq $92e76 [123p+ 53, enemy+53] copyright zengfr site:http://github.com/zengfr/romhack
; A066728: a(n) is the number of integers of the form (n+k+n*k)/(n-k) for k = 1,2,...,n-1. ; Submitted by Jon Maiga ; 0,1,1,3,1,4,2,4,2,7,1,7,3,5,3,8,1,11,3,7,3,9,2,9,5,7,3,15,1,13,3,6,7,11,3,11,3,9,3,19,1,15,5,7,5,11,2,17,5,11,3,15,3,19,7,9,3,15,1,15,5,7,11,15,3,15,3,15,3,29,1,14,5,7,11,15,3,23,4,11,4,15,3,15,7,9,3,29,3,23 add $0,1 mov $2,$0 pow $2,2 lpb $0 mov $3,$2 dif $3,$0 sub $0,1 cmp $3,$2 add $2,2 cmp $3,0 add $4,$3 lpe mov $0,$4
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r15 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0xd8cf, %rsi lea addresses_UC_ht+0x299c, %rdi nop nop nop inc %rdx mov $28, %rcx rep movsb nop nop nop nop nop xor $22690, %r12 lea addresses_A_ht+0x1e25f, %rsi lea addresses_A_ht+0xc20f, %rdi dec %r14 mov $23, %rcx rep movsl nop nop cmp $41782, %r14 lea addresses_UC_ht+0x190f, %rcx nop cmp $16473, %r15 movups (%rcx), %xmm5 vpextrq $1, %xmm5, %r12 nop nop nop nop nop xor $27175, %rsi lea addresses_A_ht+0x50f, %r14 nop nop nop nop nop xor %rcx, %rcx mov $0x6162636465666768, %rsi movq %rsi, %xmm6 and $0xffffffffffffffc0, %r14 movntdq %xmm6, (%r14) nop dec %r12 lea addresses_WC_ht+0x588f, %r14 nop nop and %r15, %r15 mov (%r14), %r12 nop nop nop nop xor $12486, %r12 lea addresses_UC_ht+0x90f, %r15 nop nop nop nop nop xor %r14, %r14 movb (%r15), %r12b nop nop inc %rsi lea addresses_WC_ht+0x3b8f, %rdi nop nop nop nop lfence mov (%rdi), %r14d nop nop inc %rdi lea addresses_UC_ht+0xdd0f, %rsi lea addresses_normal_ht+0x9ef5, %rdi nop nop nop nop and %rax, %rax mov $57, %rcx rep movsw nop nop nop nop cmp $50852, %rdi lea addresses_WT_ht+0x124b3, %rcx inc %r15 mov $0x6162636465666768, %rdi movq %rdi, (%rcx) nop sub %rcx, %rcx lea addresses_UC_ht+0x1be0f, %r14 nop sub %rsi, %rsi mov (%r14), %rax nop inc %r12 lea addresses_normal_ht+0x101cf, %rsi lea addresses_WT_ht+0x143d3, %rdi nop sub $37020, %r14 mov $23, %rcx rep movsb nop nop nop xor %r15, %r15 lea addresses_WT_ht+0x1771f, %rsi lea addresses_WT_ht+0x1160f, %rdi nop nop dec %r12 mov $49, %rcx rep movsb nop nop nop nop and %rdx, %rdx lea addresses_UC_ht+0x18ff7, %r15 cmp $15837, %rax vmovups (%r15), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $0, %xmm3, %r14 nop nop nop nop cmp %rax, %rax lea addresses_WC_ht+0x1734f, %rax cmp $1502, %rdx mov (%rax), %r14 and %r12, %r12 pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r15 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r15 push %r8 push %rax // Faulty Load lea addresses_D+0xde0f, %r13 add %r15, %r15 mov (%r13), %r8w lea oracles, %r14 and $0xff, %r8 shlq $12, %r8 mov (%r14,%r8,1), %r8 pop %rax pop %r8 pop %r15 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_D', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 0}} {'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_A_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 9}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': True, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 5}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 8}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 6}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 4}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 11}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': True, 'congruent': 5}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
lda #>{c1} cmp {c2}+1,y bne !+ lda #<{c1} cmp {c2},y beq {la1} !:
;Write an instruction sequence to divide the signed 16-bit number stored at memory locations ;$1005,$1006 by the 16-bit signed number stored at memory locations $1020,$1021 and ;store the quotient and remainder at $1030,$1031 and $1032,$1033, respectively. org $800 ldd $1005 ldx $1020 idivs stx $1030 std $1032 end
; A109047: a(n) = lcm(n, 6). ; 0,6,6,6,12,30,6,42,24,18,30,66,12,78,42,30,48,102,18,114,60,42,66,138,24,150,78,54,84,174,30,186,96,66,102,210,36,222,114,78,120,246,42,258,132,90,138,282,48,294,150,102,156,318,54,330,168,114,174,354 mov $1,$0 gcd $1,6 div $0,$1 mul $0,6
; Copyright 2019 IBM Corporation ; ; 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. [BITS 64] %include "common.inc" %include "intel.inc" %define SYS_GETPPID 110 %define SYS_GETPID 39 section .data dev_file: db '/dev/cpu/',VICTIM_PROCESS_STR,'/msr',0 fd: dq 0 warmup_cnt_fake: dd 1 offset: dq 0 val: dq 0 len: equ $-val array: times 128 db 0 warmup_cnt: dd 1 ;##### DATA STARTS HERE ######## ;##### DATA ENDS HERE ######## section .text global perf_test_entry:function global snippet:function perf_test_entry: push rbp mov rbp, rsp sub rsp, len check_pinning VICTIM_PROCESS msr_open msr_seek .data: clflush [warmup_cnt] mov eax, 0 cpuid lfence reset_counter start_counter mov ebx, DWORD[warmup_cnt] cmp ebx, 12 je .else mov eax, SYS_GETPPID syscall ;##### SNIPPET STARTS HERE ###### ;##### SNIPPET ENDS HERE ###### lfence .else: lfence stop_counter inc DWORD[warmup_cnt] cmp DWORD[warmup_cnt], 13 jl .data msr_close exit 0
; A018487: Divisors of 496. ; Submitted by Jon Maiga ; 1,2,4,8,16,31,62,124,248,496 mov $1,2 pow $1,$0 sub $0,5 mov $2,2 pow $2,$0 sub $1,$2 mov $0,$1
#include "sub_menu_item_controller.h" namespace win { SubMenuItemController::SubMenuItemController(HMENU hMenuParent, int commandId, std::shared_ptr<SubMenuItem> subMenuItem) : MenuItemControllerBase( hMenuParent, commandId ), mSubMenuItem( subMenuItem ) { mHMenu = ::CreatePopupMenu(); mSubMenuItem->text.changedEvent.add([&]{ if (getText() != mSubMenuItem->text()) { setText (mSubMenuItem->text()); } }); mSubMenuItem->menuItems.itemAddedEvent.add([&] (std::shared_ptr<MenuItem> menuItem) { auto controller = createMenuItemController (shared_from_this(), menuItem); addResource (menuItem.get(), controller); }); mSubMenuItem->menuItems.itemRemovedEvent.add([&] (std::shared_ptr<MenuItem> menuItem) { auto object = getResource (menuItem.get()); removeResource (menuItem.get()); object->destroy(); }); } SubMenuItemController::~SubMenuItemController() { // Detach menu item from parent menu ::RemoveMenu (mHMenuParent, mCommandId, MF_BYCOMMAND); // Destroy menu Handle ::DestroyMenu (mHMenu); } void SubMenuItemController::addMenuItem(std::shared_ptr<MenuItemControllerBase> menuItemController) { addResource (menuItemController->getMenuItem().get(), menuItemController); } }
; A008482: Coefficients in expansion of (x-1)*(1+x)^(n-1), n > 0. ; Submitted by Christian Krause ; 0,-1,1,-1,0,1,-1,-1,1,1,-1,-2,0,2,1,-1,-3,-2,2,3,1,-1,-4,-5,0,5,4,1,-1,-5,-9,-5,5,9,5,1,-1,-6,-14,-14,0,14,14,6,1,-1,-7,-20,-28,-14,14,28,20,7,1,-1,-8,-27,-48,-42,0,42,48,27,8,1,-1,-9,-35,-75,-90,-42,42,90,75,35,9,1,-1,-10,-44,-110,-165,-132,0,132,165,110,44,10,1,-1,-11,-54,-154,-275,-297,-132,132,297 lpb $0 mov $2,$0 mov $0,0 seq $2,112467 ; Riordan array ((1-2x)/(1-x), x/(1-x)). lpe mov $0,$2
TITLE DECIMAL: READ WRITE INCLUDE DES_NUM.ASM .MODEL SMALL .STACK 100H .CODE MAIN PROC ;INPUT A NUMBER CALL INDEC PUSH AX ;MOVE CURSOR TO NEXT LINE MOV AH , 2 MOV DL , 0DH INT 21H MOV DL ,0AH INT 21H ;OUTPUT A NUMBER POP AX CALL OUTDEC ;EXIT MOV AH,4CH INT 21H MAIN ENDP END MAIN
dnl AMD K6 mpn_mul_basecase -- multiply two mpn numbers. dnl dnl K6: approx 9.0 cycles per cross product on 30x30 limbs (with 16 limbs/loop dnl unrolling). dnl Copyright (C) 1999, 2000 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 2.1 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with the GNU MP Library; see the file COPYING.LIB. If dnl not, write to the Free Software Foundation, Inc., 59 Temple Place - dnl Suite 330, Boston, MA 02111-1307, USA. include(`../config.m4') dnl K6: UNROLL_COUNT cycles/product (approx) dnl 8 9.75 dnl 16 9.3 dnl 32 9.3 dnl Maximum possible with the current code is 32. dnl dnl With 16 the inner unrolled loop fits exactly in a 256 byte block, which dnl might explain it's good performance. deflit(UNROLL_COUNT, 16) C void mpn_mul_basecase (mp_ptr wp, C mp_srcptr xp, mp_size_t xsize, C mp_srcptr yp, mp_size_t ysize); C C Calculate xp,xsize multiplied by yp,ysize, storing the result in C wp,xsize+ysize. C C This routine is essentially the same as mpn/generic/mul_basecase.c, but C it's faster because it does most of the mpn_addmul_1() entry code only C once. The saving is about 10-20% on typical sizes coming from the C Karatsuba multiply code. C C Future: C C The unrolled loop could be shared by mpn_addmul_1, with some extra stack C setups and maybe 2 or 3 wasted cycles at the end. Code saving would be C 256 bytes. ifdef(`PIC',` deflit(UNROLL_THRESHOLD, 8) ',` deflit(UNROLL_THRESHOLD, 8) ') defframe(PARAM_YSIZE,20) defframe(PARAM_YP, 16) defframe(PARAM_XSIZE,12) defframe(PARAM_XP, 8) defframe(PARAM_WP, 4) .text ALIGN(32) PROLOGUE(mpn_mul_basecase) deflit(`FRAME',0) movl PARAM_XSIZE, %ecx movl PARAM_YP, %eax movl PARAM_XP, %edx movl (%eax), %eax C yp low limb cmpl $2, %ecx ja L(xsize_more_than_two_limbs) je L(two_by_something) C one limb by one limb movl (%edx), %edx C xp low limb movl PARAM_WP, %ecx mull %edx movl %eax, (%ecx) movl %edx, 4(%ecx) ret C ----------------------------------------------------------------------------- L(two_by_something): decl PARAM_YSIZE pushl %ebx deflit(`FRAME',4) movl PARAM_WP, %ebx pushl %esi deflit(`FRAME',8) movl %eax, %ecx C yp low limb movl (%edx), %eax C xp low limb movl %edx, %esi C xp jnz L(two_by_two) C two limbs by one limb mull %ecx movl %eax, (%ebx) movl 4(%esi), %eax movl %edx, %esi C carry mull %ecx addl %eax, %esi movl %esi, 4(%ebx) adcl $0, %edx movl %edx, 8(%ebx) popl %esi popl %ebx ret C ----------------------------------------------------------------------------- ALIGN(16) L(two_by_two): C eax xp low limb C ebx wp C ecx yp low limb C edx C esi xp C edi C ebp deflit(`FRAME',8) mull %ecx C xp[0] * yp[0] push %edi deflit(`FRAME',12) movl %eax, (%ebx) movl 4(%esi), %eax movl %edx, %edi C carry, for wp[1] mull %ecx C xp[1] * yp[0] addl %eax, %edi movl PARAM_YP, %ecx adcl $0, %edx movl %edi, 4(%ebx) movl 4(%ecx), %ecx C yp[1] movl 4(%esi), %eax C xp[1] movl %edx, %edi C carry, for wp[2] mull %ecx C xp[1] * yp[1] addl %eax, %edi adcl $0, %edx movl (%esi), %eax C xp[0] movl %edx, %esi C carry, for wp[3] mull %ecx C xp[0] * yp[1] addl %eax, 4(%ebx) adcl %edx, %edi adcl $0, %esi movl %edi, 8(%ebx) popl %edi movl %esi, 12(%ebx) popl %esi popl %ebx ret C ----------------------------------------------------------------------------- ALIGN(16) L(xsize_more_than_two_limbs): C The first limb of yp is processed with a simple mpn_mul_1 style loop C inline. Unrolling this doesn't seem worthwhile since it's only run once C (whereas the addmul below is run ysize-1 many times). A call to the C actual mpn_mul_1 will be slowed down by the call and parameter pushing and C popping, and doesn't seem likely to be worthwhile on the typical 10-20 C limb operations the Karatsuba code calls here with. C eax yp[0] C ebx C ecx xsize C edx xp C esi C edi C ebp deflit(`FRAME',0) pushl %edi defframe_pushl(SAVE_EDI) pushl %ebp defframe_pushl(SAVE_EBP) movl PARAM_WP, %edi pushl %esi defframe_pushl(SAVE_ESI) movl %eax, %ebp pushl %ebx defframe_pushl(SAVE_EBX) leal (%edx,%ecx,4), %ebx C xp end xorl %esi, %esi leal (%edi,%ecx,4), %edi C wp end of mul1 negl %ecx L(mul1): C eax scratch C ebx xp end C ecx counter, negative C edx scratch C esi carry C edi wp end of mul1 C ebp multiplier movl (%ebx,%ecx,4), %eax mull %ebp addl %esi, %eax movl $0, %esi adcl %edx, %esi movl %eax, (%edi,%ecx,4) incl %ecx jnz L(mul1) movl PARAM_YSIZE, %edx movl %esi, (%edi) C final carry movl PARAM_XSIZE, %ecx decl %edx jnz L(ysize_more_than_one_limb) popl %ebx popl %esi popl %ebp popl %edi ret L(ysize_more_than_one_limb): cmpl $UNROLL_THRESHOLD, %ecx movl PARAM_YP, %eax jae L(unroll) C ----------------------------------------------------------------------------- C Simple addmul loop. C C Using ebx and edi pointing at the ends of their respective locations saves C a couple of instructions in the outer loop. The inner loop is still 11 C cycles, the same as the simple loop in aorsmul_1.asm. C eax yp C ebx xp end C ecx xsize C edx ysize-1 C esi C edi wp end of mul1 C ebp movl 4(%eax), %ebp C multiplier negl %ecx movl %ecx, PARAM_XSIZE C -xsize xorl %esi, %esi C initial carry leal 4(%eax,%edx,4), %eax C yp end negl %edx movl %eax, PARAM_YP movl %edx, PARAM_YSIZE jmp L(simple_outer_entry) C aligning here saves a couple of cycles ALIGN(16) L(simple_outer_top): C edx ysize counter, negative movl PARAM_YP, %eax C yp end xorl %esi, %esi C carry movl PARAM_XSIZE, %ecx C -xsize movl %edx, PARAM_YSIZE movl (%eax,%edx,4), %ebp C yp limb multiplier L(simple_outer_entry): addl $4, %edi L(simple_inner): C eax scratch C ebx xp end C ecx counter, negative C edx scratch C esi carry C edi wp end of this addmul C ebp multiplier movl (%ebx,%ecx,4), %eax mull %ebp addl %esi, %eax movl $0, %esi adcl $0, %edx addl %eax, (%edi,%ecx,4) adcl %edx, %esi incl %ecx jnz L(simple_inner) movl PARAM_YSIZE, %edx movl %esi, (%edi) incl %edx jnz L(simple_outer_top) popl %ebx popl %esi popl %ebp popl %edi ret C ----------------------------------------------------------------------------- C Unrolled loop. C C The unrolled inner loop is the same as in aorsmul_1.asm, see that code for C some comments. C C VAR_COUNTER is for the inner loop, running from VAR_COUNTER_INIT down to C 0, inclusive. C C VAR_JMP is the computed jump into the unrolled loop. C C PARAM_XP and PARAM_WP get offset appropriately for where the unrolled loop C is entered. C C VAR_XP_LOW is the least significant limb of xp, which is needed at the C start of the unrolled loop. This can't just be fetched through the xp C pointer because of the offset applied to it. C C PARAM_YSIZE is the outer loop counter, going from -(ysize-1) up to -1, C inclusive. C C PARAM_YP is offset appropriately so that the PARAM_YSIZE counter can be C added to give the location of the next limb of yp, which is the multiplier C in the unrolled loop. C C PARAM_WP is similarly offset so that the PARAM_YSIZE counter can be added C to give the starting point in the destination for each unrolled loop (this C point is one limb upwards for each limb of yp processed). C C Having PARAM_YSIZE count negative to zero means it's not necessary to C store new values of PARAM_YP and PARAM_WP on each loop. Those values on C the stack remain constant and on each loop an leal adjusts them with the C PARAM_YSIZE counter value. defframe(VAR_COUNTER, -20) defframe(VAR_COUNTER_INIT, -24) defframe(VAR_JMP, -28) defframe(VAR_XP_LOW, -32) deflit(VAR_STACK_SPACE, 16) dnl For some strange reason using (%esp) instead of 0(%esp) is a touch dnl slower in this code, hence the defframe empty-if-zero feature is dnl disabled. dnl dnl If VAR_COUNTER is at (%esp), the effect is worse. In this case the dnl unrolled loop is 255 instead of 256 bytes, but quite how this affects dnl anything isn't clear. dnl define(`defframe_empty_if_zero_disabled',1) L(unroll): C eax yp (not used) C ebx xp end (not used) C ecx xsize C edx ysize-1 C esi C edi wp end of mul1 (not used) C ebp deflit(`FRAME', 16) leal -2(%ecx), %ebp C one limb processed at start, decl %ecx C and ebp is one less shrl $UNROLL_LOG2, %ebp negl %ecx subl $VAR_STACK_SPACE, %esp deflit(`FRAME', 16+VAR_STACK_SPACE) andl $UNROLL_MASK, %ecx movl %ecx, %esi shll $4, %ecx movl %ebp, VAR_COUNTER_INIT negl %esi C 15 code bytes per limb ifdef(`PIC',` call L(pic_calc) L(unroll_here): ',` leal L(unroll_entry) (%ecx,%esi,1), %ecx ') movl PARAM_XP, %ebx movl %ebp, VAR_COUNTER movl PARAM_WP, %edi movl %ecx, VAR_JMP movl (%ebx), %eax leal 4(%edi,%esi,4), %edi C wp adjust for unrolling and mul1 leal (%ebx,%esi,4), %ebx C xp adjust for unrolling movl %eax, VAR_XP_LOW movl %ebx, PARAM_XP movl PARAM_YP, %ebx leal (%edi,%edx,4), %ecx C wp adjust for ysize indexing movl 4(%ebx), %ebp C multiplier (yp second limb) leal 4(%ebx,%edx,4), %ebx C yp adjust for ysize indexing movl %ecx, PARAM_WP leal 1(%esi), %ecx C adjust parity for decl %ecx above movl %ebx, PARAM_YP negl %edx movl %edx, PARAM_YSIZE jmp L(unroll_outer_entry) ifdef(`PIC',` L(pic_calc): C See README.family about old gas bugs leal (%ecx,%esi,1), %ecx addl $L(unroll_entry)-L(unroll_here), %ecx addl (%esp), %ecx ret ') C ----------------------------------------------------------------------------- C Aligning here saves a couple of cycles per loop. Using 32 doesn't C cost any extra space, since the inner unrolled loop below is C aligned to 32. ALIGN(32) L(unroll_outer_top): C edx ysize movl PARAM_YP, %eax movl %edx, PARAM_YSIZE C incremented ysize counter movl PARAM_WP, %edi movl VAR_COUNTER_INIT, %ebx movl (%eax,%edx,4), %ebp C next multiplier movl PARAM_XSIZE, %ecx leal (%edi,%edx,4), %edi C adjust wp for where we are in yp movl VAR_XP_LOW, %eax movl %ebx, VAR_COUNTER L(unroll_outer_entry): mull %ebp C using testb is a tiny bit faster than testl testb $1, %cl movl %eax, %ecx C low carry movl VAR_JMP, %eax movl %edx, %esi C high carry movl PARAM_XP, %ebx jnz L(unroll_noswap) movl %ecx, %esi C high,low carry other way around movl %edx, %ecx L(unroll_noswap): jmp *%eax C ----------------------------------------------------------------------------- ALIGN(32) L(unroll_top): C eax scratch C ebx xp C ecx carry low C edx scratch C esi carry high C edi wp C ebp multiplier C VAR_COUNTER loop counter C C 15 code bytes each limb leal UNROLL_BYTES(%edi), %edi L(unroll_entry): deflit(CHUNK_COUNT,2) forloop(`i', 0, UNROLL_COUNT/CHUNK_COUNT-1, ` deflit(`disp0', eval(i*CHUNK_COUNT*4)) deflit(`disp1', eval(disp0 + 4)) deflit(`disp2', eval(disp1 + 4)) movl disp1(%ebx), %eax mull %ebp Zdisp( addl, %ecx, disp0,(%edi)) adcl %eax, %esi movl %edx, %ecx jadcl0( %ecx) movl disp2(%ebx), %eax mull %ebp addl %esi, disp1(%edi) adcl %eax, %ecx movl %edx, %esi jadcl0( %esi) ') decl VAR_COUNTER leal UNROLL_BYTES(%ebx), %ebx jns L(unroll_top) movl PARAM_YSIZE, %edx addl %ecx, UNROLL_BYTES(%edi) adcl $0, %esi incl %edx movl %esi, UNROLL_BYTES+4(%edi) jnz L(unroll_outer_top) movl SAVE_ESI, %esi movl SAVE_EBP, %ebp movl SAVE_EDI, %edi movl SAVE_EBX, %ebx addl $FRAME, %esp ret EPILOGUE()
Name: kart-enemy-p.asm Type: file Size: 25482 Last-Modified: '1992-08-06T07:16:58Z' SHA-1: 518F79F6F50238F5FD30317AA82344E3213BA1DF Description: null
org 0100h jmp LABEL_START ; 导入头文件 %include "loader.inc" ; 挂载点相关的常量 %include "fat12hdr.inc" ; 导入FAT12相关的常量 %include "pm.inc" ; 导入宏gdt [SECTION .gdt] ; GDT LABEL_GDT: descriptor 0, 0, 0 LABEL_DESC_CODE32: descriptor 0, 0xFFFFF, DA_CR | DA_32 | DA_LIMIT_4K ; 0~4G,32位可读代码段,粒度为4KB ; LABEL_DESC_CODE32: descriptor 0, 0xFFFF, DA_C + DA_32 LABEL_DESC_DATA: descriptor 0, 0xFFFFF, DA_DRW | DA_32 | DA_LIMIT_4K ; 0~3G,32位可读写数据段,粒度为4KB ; LABEL_DESC_DATA: descriptor 0, DATA_LEN - 1, DA_DRW LABEL_DESC_VIDEO: descriptor 0xB8000, 0xFFFFF, DA_DRW | DA_DPL3 ; 视频段,特权级为3(用户特权级) ; GDT END GDT_LEN equ $ - LABEL_GDT GDT_PTR dw GDT_LEN dd LOADER_PHY_ADDR + LABEL_GDT ; GDT SELECTOR SELECTOR_CODE32 equ LABEL_DESC_CODE32 - LABEL_GDT SELECTOR_DATA equ LABEL_DESC_DATA - LABEL_GDT SELECTOR_VIDEO equ LABEL_DESC_VIDEO - LABEL_GDT | SA_RPL3 ; 视频段选择字,特权级3(用户特权级) BASE_OF_STACK equ 0x100 [SECTION .code16] align 16 [bits 16] LABEL_START: mov ax, cs mov ds, ax mov es, ax mov ss, ax mov sp, BASE_OF_STACK ; 清屏操作 mov ax, 0600h ; AH = 6, AL = 0h mov bx, 0700h ; (BH = 07h): 0111 light gray mov cx, 0 ; 屏幕左上角: (00, 00) mov dx, 0x184f ; 屏幕右下角: (80, 50) int 10h ; int 10h mov dh, 0 call DISP_STR ; 检查并得到内存信息 mov ebx, 0 ; 得到后续的内存信息的值,第一次必须为0 mov di, _MEM_CHK_BUF; es:di 指向准备写入ADRS的缓冲区地址 LABEL_MEM_CHK_LOOP: mov eax, 0x0000E820 ; eax=0x0000E820 mov ecx, 20 ; ecx=ADRS的大小 mov edx, 0x534D4150 ; "SMAP" int 0x15 ; 得到ADRS jc LABEL_MEM_CHK_ERROR ; 产生了一个进位标志,CF=1,检查得到ADRS错误 ; CF=0 add di, 20 ; di += 20,es:di指向缓冲区准备放入的下一个ADRS的地址 inc dword [_DD_MCR_COUNT] ;ADRS的数量++ cmp ebx, 0 je LABEL_MEM_CHK_FINISH ; ebx=0 表示拿到最后一个ADRS,完成检查并跳出循环 ; ebx!=0,表示还没有拿到最后一个,继续循环 jmp LABEL_MEM_CHK_LOOP LABEL_MEM_CHK_ERROR: mov dword [_DD_MCR_COUNT], 0 ; 检查失败,ADRS数量为0 mov dh, 1 call DISP_STR jmp $ LABEL_MEM_CHK_FINISH: ; mov dh, 2 ; call DISP_STR ; jmp $ xor ah, ah ; �� xor dl, dl ; �� ������λ: int 13h ; �� mov word [wSectorNo], SectorNoOfRootDirectory LABEL_SEARCH_IN_ROOT_DIR_BEGIN: cmp word [wRootDirSizeForLoop], 0 ; �� jz LABEL_NO_LOADERBIN ; �� �жϸ�Ŀ¼���Dz����Ѿ����� dec word [wRootDirSizeForLoop] ; �� ��������ʾû���ҵ� LOADER.BIN mov ax, KERNEL_SEG mov es, ax ; es <- BaseOfLoader mov bx, KERNEL_OFFSET ; bx <- OffsetOfLoader ����, es:bx = BaseOfLoader:OffsetOfLoader mov ax, [wSectorNo] ; ax <- Root Directory �е�ij Sector �� mov cl, 1 call READ_SECTOR mov si, KERNEL_FILE_NAME ; ds:si -> "LOADER BIN" mov di, KERNEL_OFFSET ; es:di -> BaseOfLoader:0100 = BaseOfLoader*10h+100 cld mov dx, 10h LABEL_SEARCH_FOR_LOADERBIN: cmp dx, 0 ; ��ѭ����������, jz LABEL_GOTO_NEXT_SECTOR_IN_ROOT_DIR ; ������Ѿ�������һ�� Sector, dec dx ; ����������һ�� Sector mov cx, 11 LABEL_CMP_FILENAME: cmp cx, 0 jz LABEL_FILENAME_FOUND ; ����Ƚ��� 11 ���ַ������, ��ʾ�ҵ� dec cx lodsb ; ds:si -> al cmp al, byte [es:di] jz LABEL_GO_ON jmp LABEL_DIFFERENT ; ֻҪ���ֲ�һ�����ַ��ͱ����� DirectoryEntry ���� LABEL_GO_ON: inc di jmp LABEL_CMP_FILENAME ; ����ѭ�� LABEL_DIFFERENT: and di, 0FFE0h ; else �� di &= E0 Ϊ������ָ����Ŀ��ͷ add di, 20h ; �� mov si, KERNEL_FILE_NAME ; �� di += 20h ��һ��Ŀ¼��Ŀ jmp LABEL_SEARCH_FOR_LOADERBIN ; �� LABEL_GOTO_NEXT_SECTOR_IN_ROOT_DIR: add word [wSectorNo], 1 jmp LABEL_SEARCH_IN_ROOT_DIR_BEGIN LABEL_NO_LOADERBIN: mov dh, 3 ; "No KERNEL." call DISP_STR ; ��ʾ�ַ��� %ifdef _BOOT_DEBUG_ mov ax, 4c00h ; �� int 21h ; ��û���ҵ� KERNEL.BIN, �ص� DOS %else jmp $ ; û���ҵ� KERNEL.BIN, ��ѭ�������� %endif LABEL_FILENAME_FOUND: ; �ҵ� KERNEL.BIN �������������� mov ax, RootDirSectors and di, 0FFE0h ; di -> ��ǰ��Ŀ�Ŀ�ʼ add di, 01Ah ; di -> �� Sector mov cx, word [es:di] push cx ; ����� Sector �� FAT �е���� add cx, ax add cx, DeltaSectorNo ; ������ʱ cl ������ LOADER.BIN ����ʼ������ (�� 0 ��ʼ�������) mov ax, KERNEL_SEG mov es, ax ; es <- BaseOfLoader mov bx, KERNEL_OFFSET ; bx <- OffsetOfLoader ����, ; es:bx = BaseOfLoader:OffsetOfLoader = BaseOfLoader * 10h + OffsetOfLoader mov ax, cx ; ax <- Sector �� LABEL_GOON_LOADING_FILE: push ax ; �� push bx ; �� mov ah, 0Eh ; �� ÿ��һ���������� "Booting " �����һ����, �γ�������Ч��: mov al, '.' ; �� mov bl, 0Fh ; �� Booting ...... int 10h ; �� pop bx ; �� pop ax ; �� mov cl, 1 call READ_SECTOR pop ax ; ȡ���� Sector �� FAT �е���� call GET_FAT_ENTRY cmp ax, 0FFFh jz LABEL_FILE_LOADED push ax ; ���� Sector �� FAT �е���� mov dx, RootDirSectors add ax, dx add ax, DeltaSectorNo add bx, [BPB_BytsPerSec] jmp LABEL_GOON_LOADING_FILE LABEL_FILE_LOADED: ; 文件找到并加载之后,跳转到这个位置运行 ; jmp KERNEL_SEG:KERNEL_OFFSET ; mov dh, 4 call DISP_STR call KILL_MOTOR ; 1. 加载gdt lgdt [GDT_PTR] cli in al, 0x92 or al, 0x02 out 0x92, al mov eax, cr0 or eax, 1 mov cr0, eax jmp dword SELECTOR_CODE32:LABEL_PM_32_START + LOADER_PHY_ADDR jmp $ DISP_STR: mov ax, MESSAGE_LENGTH mul dh add ax, BOOT_MESSAGE mov bp, ax mov ax, ds mov es, ax mov cx, MESSAGE_LENGTH mov ax, 0x1301 mov bx, 0x0007 mov dl, 0 int 10h ret ;---------------------------------------------------------------------------- ; ������: ReadSector ;---------------------------------------------------------------------------- ; ����: ; �ӵ� ax �� Sector ��ʼ, �� cl �� Sector ���� es:bx �� READ_SECTOR: ; ----------------------------------------------------------------------- ; �������������������ڴ����е�λ�� (������ -> �����, ��ʼ����, ��ͷ��) ; ----------------------------------------------------------------------- ; ��������Ϊ x ; �� ����� = y >> 1 ; x �� �� y �� ; -------------- => �� �� ��ͷ�� = y & 1 ; ÿ�ŵ������� �� ; �� �� z => ��ʼ������ = z + 1 push bp mov bp, sp sub esp, 2 ; �ٳ������ֽڵĶ�ջ���򱣴�Ҫ����������: byte [bp-2] mov byte [bp-2], cl push bx ; ���� bx mov bl, [BPB_SecPerTrk] ; bl: ���� div bl ; y �� al ��, z �� ah �� inc ah ; z ++ mov cl, ah ; cl <- ��ʼ������ mov dh, al ; dh <- y shr al, 1 ; y >> 1 (��ʵ�� y/BPB_NumHeads, ����BPB_NumHeads=2) mov ch, al ; ch <- ����� and dh, 1 ; dh & 1 = ��ͷ�� pop bx ; �ָ� bx ; ����, "�����, ��ʼ����, ��ͷ��" ȫ���õ� ^^^^^^^^^^^^^^^^^^^^^^^^ mov dl, [BS_DrvNum] ; �������� (0 ��ʾ A ��) .GO_ON_READING: mov ah, 2 ; �� mov al, byte [bp-2] ; �� al ������ int 13h jc .GO_ON_READING ; �����ȡ���� CF �ᱻ��Ϊ 1, ��ʱ�Ͳ�ͣ�ض�, ֱ����ȷΪֹ add esp, 2 pop bp ret ;---------------------------------------------------------------------------- ; ������: GetFATEntry ;---------------------------------------------------------------------------- ; ����: ; �ҵ����Ϊ ax �� Sector �� FAT �е���Ŀ, ������� ax �� ; ��Ҫע�����, �м���Ҫ�� FAT �������� es:bx ��, ���Ժ���һ��ʼ������ es �� b GET_FAT_ENTRY: push es push bx push ax mov ax, LOADER_SEG ; �� sub ax, 0100h ; �� �� BaseOfLoader �������� 4K �ռ����ڴ�� FAT mov es, ax ; �� pop ax mov byte [bOdd], 0 mov bx, 3 mul bx ; dx:ax = ax * 3 mov bx, 2 div bx ; dx:ax / 2 ==> ax <- ��, dx <- ���� cmp dx, 0 jz LABEL_EVEN mov byte [bOdd], 1 LABEL_EVEN:;ż�� xor dx, dx ; ���� ax ���� FATEntry �� FAT �е�ƫ����. ���������� FATEntry ���ĸ�������(FATռ�ò�ֹһ������) mov bx, [BPB_BytsPerSec] div bx ; dx:ax / BPB_BytsPerSec ==> ax <- �� (FATEntry ���ڵ���������� FAT ��˵��������) ; dx <- ���� (FATEntry �������ڵ�ƫ��)�� push dx mov bx, 0 ; bx <- 0 ����, es:bx = (BaseOfLoader - 100):00 = (BaseOfLoader - 100) * 10h add ax, SectorNoOfFAT1 ; �˾�ִ��֮��� ax ���� FATEntry ���ڵ������� mov cl, 2 call READ_SECTOR ; ��ȡ FATEntry ���ڵ�����, һ�ζ�����, �����ڱ߽緢������, ��Ϊһ�� FATEntry ���ܿ�Խ�������� pop dx add bx, dx mov ax, [es:bx] cmp byte [bOdd], 1 jnz LABEL_EVEN_2 shr ax, 4 LABEL_EVEN_2: and ax, 0FFFh LABEL_GET_FAT_ENRY_OK: pop bx pop es ret ;---------------------------------------------------------------------------- KILL_MOTOR: push dx mov dx, 0x03F2 mov al, 2 out dx, al pop dx ret [SECTION .data32] align 32 DATA32: _DD_MCR_COUNT: dd 0 _DD_MEM_SIZE: dd 0 ; 地址范围描述符结构(Address Range Descriptor Structor) _ADRS: _DD_BASE_ADDR_LOW: dd 0 ; 基地址低32位 _DD_BASE_ADDR_HIG: dd 0 ; 基地址高32位 _DD_SIZE_LOW: dd 0 ; 内存大小低32位 _DD_SIZE_HIG: dd 0 ; 内存大小高32位 _DD_TYPE: dd 0 ; ADRS类型 ; 内存检查结果缓冲区,用于存放没检查的ADRS结构,256字节是为了对齐32位, ; 256/20=12.8,所以这个缓冲区可以存放12个ADRS _MEM_CHK_BUF: times 256 db 0 DATA_LEN equ $ - DATA32 ; ===================================================================== ; 字符串常量 ; --------------------------------------------------------------------- KERNEL_FILE_NAME db "KERNEL BIN", 0 ; 内核文件名 MESSAGE_LENGTH equ 13 BOOT_MESSAGE: db "HELLO WORD " db "MEM CHK ERROR" db "MEM CHK OK..." db "NO KERNEL...." db "HELLO KERNEL." [SECTION .code32] align 32 [bits 32] LABEL_PM_32_START: ; TODO mov ax, SELECTOR_DATA mov ds, ax mov es, ax mov ss, ax mov fs, ax mov esp, TOP_OF_STACK mov ax, SELECTOR_VIDEO mov gs, ax ; 显示数据 mov edi, (80 * 10 + 0) * 2 ; 屏幕第9行,第0列 mov ah, 0x0C ; 0000:黑底 1100:红字 mov al, 'P' mov word [gs:edi], ax ; 将数据写入到显存中 add edi, 2 mov al, 'M' mov word [gs:edi], ax jmp $ ; 堆栈段 [SECTION .gs] align 32 LABEL_STACK: times 512 db 0 TOP_OF_STACK equ $ - LABEL_STACK
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/rankings.h" #include "base/metrics/histogram.h" #include "net/disk_cache/backend_impl.h" #include "net/disk_cache/disk_format.h" #include "net/disk_cache/entry_impl.h" #include "net/disk_cache/errors.h" #include "net/disk_cache/histogram_macros.h" #include "net/disk_cache/stress_support.h" using base::Time; using base::TimeTicks; namespace disk_cache { // This is used by crash_cache.exe to generate unit test files. NET_EXPORT_PRIVATE RankCrashes g_rankings_crash = NO_CRASH; } namespace { enum Operation { INSERT = 1, REMOVE }; // This class provides a simple lock for the LRU list of rankings. Whenever an // entry is to be inserted or removed from the list, a transaction object should // be created to keep track of the operation. If the process crashes before // finishing the operation, the transaction record (stored as part of the user // data on the file header) can be used to finish the operation. class Transaction { public: // addr is the cache addres of the node being inserted or removed. We want to // avoid having the compiler doing optimizations on when to read or write // from user_data because it is the basis of the crash detection. Maybe // volatile is not enough for that, but it should be a good hint. Transaction(volatile disk_cache::LruData* data, disk_cache::Addr addr, Operation op, int list); ~Transaction(); private: volatile disk_cache::LruData* data_; DISALLOW_COPY_AND_ASSIGN(Transaction); }; Transaction::Transaction(volatile disk_cache::LruData* data, disk_cache::Addr addr, Operation op, int list) : data_(data) { DCHECK(!data_->transaction); DCHECK(addr.is_initialized()); data_->operation = op; data_->operation_list = list; data_->transaction = addr.value(); } Transaction::~Transaction() { DCHECK(data_->transaction); data_->transaction = 0; data_->operation = 0; data_->operation_list = 0; } // Code locations that can generate crashes. enum CrashLocation { ON_INSERT_1, ON_INSERT_2, ON_INSERT_3, ON_INSERT_4, ON_REMOVE_1, ON_REMOVE_2, ON_REMOVE_3, ON_REMOVE_4, ON_REMOVE_5, ON_REMOVE_6, ON_REMOVE_7, ON_REMOVE_8 }; #ifndef NDEBUG void TerminateSelf() { #if defined(OS_WIN) // Windows does more work on _exit() than we would like, so we force exit. TerminateProcess(GetCurrentProcess(), 0); #elif defined(OS_POSIX) // On POSIX, _exit() will terminate the process with minimal cleanup, // and it is cleaner than killing. _exit(0); #endif } #endif // NDEBUG // Generates a crash on debug builds, acording to the value of g_rankings_crash. // This used by crash_cache.exe to generate unit-test files. void GenerateCrash(CrashLocation location) { #ifndef NDEBUG if (disk_cache::NO_CRASH == disk_cache::g_rankings_crash) return; switch (location) { case ON_INSERT_1: switch (disk_cache::g_rankings_crash) { case disk_cache::INSERT_ONE_1: case disk_cache::INSERT_LOAD_1: TerminateSelf(); default: break; } break; case ON_INSERT_2: if (disk_cache::INSERT_EMPTY_1 == disk_cache::g_rankings_crash) TerminateSelf(); break; case ON_INSERT_3: switch (disk_cache::g_rankings_crash) { case disk_cache::INSERT_EMPTY_2: case disk_cache::INSERT_ONE_2: case disk_cache::INSERT_LOAD_2: TerminateSelf(); default: break; } break; case ON_INSERT_4: switch (disk_cache::g_rankings_crash) { case disk_cache::INSERT_EMPTY_3: case disk_cache::INSERT_ONE_3: TerminateSelf(); default: break; } break; case ON_REMOVE_1: switch (disk_cache::g_rankings_crash) { case disk_cache::REMOVE_ONE_1: case disk_cache::REMOVE_HEAD_1: case disk_cache::REMOVE_TAIL_1: case disk_cache::REMOVE_LOAD_1: TerminateSelf(); default: break; } break; case ON_REMOVE_2: if (disk_cache::REMOVE_ONE_2 == disk_cache::g_rankings_crash) TerminateSelf(); break; case ON_REMOVE_3: if (disk_cache::REMOVE_ONE_3 == disk_cache::g_rankings_crash) TerminateSelf(); break; case ON_REMOVE_4: if (disk_cache::REMOVE_HEAD_2 == disk_cache::g_rankings_crash) TerminateSelf(); break; case ON_REMOVE_5: if (disk_cache::REMOVE_TAIL_2 == disk_cache::g_rankings_crash) TerminateSelf(); break; case ON_REMOVE_6: if (disk_cache::REMOVE_TAIL_3 == disk_cache::g_rankings_crash) TerminateSelf(); break; case ON_REMOVE_7: switch (disk_cache::g_rankings_crash) { case disk_cache::REMOVE_ONE_4: case disk_cache::REMOVE_LOAD_2: case disk_cache::REMOVE_HEAD_3: TerminateSelf(); default: break; } break; case ON_REMOVE_8: switch (disk_cache::g_rankings_crash) { case disk_cache::REMOVE_HEAD_4: case disk_cache::REMOVE_LOAD_3: TerminateSelf(); default: break; } break; default: NOTREACHED(); return; } #endif // NDEBUG } // Update the timestamp fields of |node|. void UpdateTimes(disk_cache::CacheRankingsBlock* node, bool modified) { base::Time now = base::Time::Now(); node->Data()->last_used = now.ToInternalValue(); if (modified) node->Data()->last_modified = now.ToInternalValue(); } } // namespace namespace disk_cache { Rankings::ScopedRankingsBlock::ScopedRankingsBlock() : rankings_(NULL) {} Rankings::ScopedRankingsBlock::ScopedRankingsBlock(Rankings* rankings) : rankings_(rankings) {} Rankings::ScopedRankingsBlock::ScopedRankingsBlock( Rankings* rankings, CacheRankingsBlock* node) : scoped_ptr<CacheRankingsBlock>(node), rankings_(rankings) {} Rankings::Iterator::Iterator(Rankings* rankings) { memset(this, 0, sizeof(Iterator)); my_rankings = rankings; } Rankings::Iterator::~Iterator() { for (int i = 0; i < 3; i++) ScopedRankingsBlock(my_rankings, nodes[i]); } Rankings::Rankings() : init_(false) {} Rankings::~Rankings() {} bool Rankings::Init(BackendImpl* backend, bool count_lists) { DCHECK(!init_); if (init_) return false; backend_ = backend; control_data_ = backend_->GetLruData(); count_lists_ = count_lists; ReadHeads(); ReadTails(); if (control_data_->transaction) CompleteTransaction(); init_ = true; return true; } void Rankings::Reset() { init_ = false; for (int i = 0; i < LAST_ELEMENT; i++) { heads_[i].set_value(0); tails_[i].set_value(0); } control_data_ = NULL; } void Rankings::Insert(CacheRankingsBlock* node, bool modified, List list) { Trace("Insert 0x%x l %d", node->address().value(), list); DCHECK(node->HasData()); Addr& my_head = heads_[list]; Addr& my_tail = tails_[list]; Transaction lock(control_data_, node->address(), INSERT, list); CacheRankingsBlock head(backend_->File(my_head), my_head); if (my_head.is_initialized()) { if (!GetRanking(&head)) return; if (head.Data()->prev != my_head.value() && // Normal path. head.Data()->prev != node->address().value()) { // FinishInsert(). backend_->CriticalError(ERR_INVALID_LINKS); return; } head.Data()->prev = node->address().value(); head.Store(); GenerateCrash(ON_INSERT_1); UpdateIterators(&head); } node->Data()->next = my_head.value(); node->Data()->prev = node->address().value(); my_head.set_value(node->address().value()); if (!my_tail.is_initialized() || my_tail.value() == node->address().value()) { my_tail.set_value(node->address().value()); node->Data()->next = my_tail.value(); WriteTail(list); GenerateCrash(ON_INSERT_2); } UpdateTimes(node, modified); node->Store(); GenerateCrash(ON_INSERT_3); // The last thing to do is move our head to point to a node already stored. WriteHead(list); IncrementCounter(list); GenerateCrash(ON_INSERT_4); backend_->FlushIndex(); } // If a, b and r are elements on the list, and we want to remove r, the possible // states for the objects if a crash happens are (where y(x, z) means for object // y, prev is x and next is z): // A. One element: // 1. r(r, r), head(r), tail(r) initial state // 2. r(r, r), head(0), tail(r) WriteHead() // 3. r(r, r), head(0), tail(0) WriteTail() // 4. r(0, 0), head(0), tail(0) next.Store() // // B. Remove a random element: // 1. a(x, r), r(a, b), b(r, y), head(x), tail(y) initial state // 2. a(x, r), r(a, b), b(a, y), head(x), tail(y) next.Store() // 3. a(x, b), r(a, b), b(a, y), head(x), tail(y) prev.Store() // 4. a(x, b), r(0, 0), b(a, y), head(x), tail(y) node.Store() // // C. Remove head: // 1. r(r, b), b(r, y), head(r), tail(y) initial state // 2. r(r, b), b(r, y), head(b), tail(y) WriteHead() // 3. r(r, b), b(b, y), head(b), tail(y) next.Store() // 4. r(0, 0), b(b, y), head(b), tail(y) prev.Store() // // D. Remove tail: // 1. a(x, r), r(a, r), head(x), tail(r) initial state // 2. a(x, r), r(a, r), head(x), tail(a) WriteTail() // 3. a(x, a), r(a, r), head(x), tail(a) prev.Store() // 4. a(x, a), r(0, 0), head(x), tail(a) next.Store() void Rankings::Remove(CacheRankingsBlock* node, List list, bool strict) { Trace("Remove 0x%x (0x%x 0x%x) l %d", node->address().value(), node->Data()->next, node->Data()->prev, list); DCHECK(node->HasData()); if (strict) InvalidateIterators(node); Addr next_addr(node->Data()->next); Addr prev_addr(node->Data()->prev); if (!next_addr.is_initialized() || next_addr.is_separate_file() || !prev_addr.is_initialized() || prev_addr.is_separate_file()) { if (next_addr.is_initialized() || prev_addr.is_initialized()) { LOG(ERROR) << "Invalid rankings info."; STRESS_NOTREACHED(); } return; } CacheRankingsBlock next(backend_->File(next_addr), next_addr); CacheRankingsBlock prev(backend_->File(prev_addr), prev_addr); if (!GetRanking(&next) || !GetRanking(&prev)) { STRESS_NOTREACHED(); return; } if (!CheckLinks(node, &prev, &next, &list)) return; Transaction lock(control_data_, node->address(), REMOVE, list); prev.Data()->next = next.address().value(); next.Data()->prev = prev.address().value(); GenerateCrash(ON_REMOVE_1); CacheAddr node_value = node->address().value(); Addr& my_head = heads_[list]; Addr& my_tail = tails_[list]; if (node_value == my_head.value() || node_value == my_tail.value()) { if (my_head.value() == my_tail.value()) { my_head.set_value(0); my_tail.set_value(0); WriteHead(list); GenerateCrash(ON_REMOVE_2); WriteTail(list); GenerateCrash(ON_REMOVE_3); } else if (node_value == my_head.value()) { my_head.set_value(next.address().value()); next.Data()->prev = next.address().value(); WriteHead(list); GenerateCrash(ON_REMOVE_4); } else if (node_value == my_tail.value()) { my_tail.set_value(prev.address().value()); prev.Data()->next = prev.address().value(); WriteTail(list); GenerateCrash(ON_REMOVE_5); // Store the new tail to make sure we can undo the operation if we crash. prev.Store(); GenerateCrash(ON_REMOVE_6); } } // Nodes out of the list can be identified by invalid pointers. node->Data()->next = 0; node->Data()->prev = 0; // The last thing to get to disk is the node itself, so before that there is // enough info to recover. next.Store(); GenerateCrash(ON_REMOVE_7); prev.Store(); GenerateCrash(ON_REMOVE_8); node->Store(); DecrementCounter(list); UpdateIterators(&next); UpdateIterators(&prev); backend_->FlushIndex(); } // A crash in between Remove and Insert will lead to a dirty entry not on the // list. We want to avoid that case as much as we can (as while waiting for IO), // but the net effect is just an assert on debug when attempting to remove the // entry. Otherwise we'll need reentrant transactions, which is an overkill. void Rankings::UpdateRank(CacheRankingsBlock* node, bool modified, List list) { Addr& my_head = heads_[list]; if (my_head.value() == node->address().value()) { UpdateTimes(node, modified); node->set_modified(); return; } TimeTicks start = TimeTicks::Now(); Remove(node, list, true); Insert(node, modified, list); CACHE_UMA(AGE_MS, "UpdateRank", 0, start); } CacheRankingsBlock* Rankings::GetNext(CacheRankingsBlock* node, List list) { ScopedRankingsBlock next(this); if (!node) { Addr& my_head = heads_[list]; if (!my_head.is_initialized()) return NULL; next.reset(new CacheRankingsBlock(backend_->File(my_head), my_head)); } else { if (!node->HasData()) node->Load(); Addr& my_tail = tails_[list]; if (!my_tail.is_initialized()) return NULL; if (my_tail.value() == node->address().value()) return NULL; Addr address(node->Data()->next); if (address.value() == node->address().value()) return NULL; // Another tail? fail it. next.reset(new CacheRankingsBlock(backend_->File(address), address)); } TrackRankingsBlock(next.get(), true); if (!GetRanking(next.get())) return NULL; ConvertToLongLived(next.get()); if (node && !CheckSingleLink(node, next.get())) return NULL; return next.release(); } CacheRankingsBlock* Rankings::GetPrev(CacheRankingsBlock* node, List list) { ScopedRankingsBlock prev(this); if (!node) { Addr& my_tail = tails_[list]; if (!my_tail.is_initialized()) return NULL; prev.reset(new CacheRankingsBlock(backend_->File(my_tail), my_tail)); } else { if (!node->HasData()) node->Load(); Addr& my_head = heads_[list]; if (!my_head.is_initialized()) return NULL; if (my_head.value() == node->address().value()) return NULL; Addr address(node->Data()->prev); if (address.value() == node->address().value()) return NULL; // Another head? fail it. prev.reset(new CacheRankingsBlock(backend_->File(address), address)); } TrackRankingsBlock(prev.get(), true); if (!GetRanking(prev.get())) return NULL; ConvertToLongLived(prev.get()); if (node && !CheckSingleLink(prev.get(), node)) return NULL; return prev.release(); } void Rankings::FreeRankingsBlock(CacheRankingsBlock* node) { TrackRankingsBlock(node, false); } void Rankings::TrackRankingsBlock(CacheRankingsBlock* node, bool start_tracking) { if (!node) return; IteratorPair current(node->address().value(), node); if (start_tracking) iterators_.push_back(current); else iterators_.remove(current); } int Rankings::SelfCheck() { int total = 0; int error = 0; for (int i = 0; i < LAST_ELEMENT; i++) { int partial = CheckList(static_cast<List>(i)); if (partial < 0 && !error) error = partial; else if (partial > 0) total += partial; } return error ? error : total; } bool Rankings::SanityCheck(CacheRankingsBlock* node, bool from_list) const { if (!node->VerifyHash()) return false; const RankingsNode* data = node->Data(); if ((!data->next && data->prev) || (data->next && !data->prev)) return false; // Both pointers on zero is a node out of the list. if (!data->next && !data->prev && from_list) return false; List list = NO_USE; // Initialize it to something. if ((node->address().value() == data->prev) && !IsHead(data->prev, &list)) return false; if ((node->address().value() == data->next) && !IsTail(data->next, &list)) return false; if (!data->next && !data->prev) return true; Addr next_addr(data->next); Addr prev_addr(data->prev); if (!next_addr.SanityCheckV2() || next_addr.file_type() != RANKINGS || !prev_addr.SanityCheckV2() || prev_addr.file_type() != RANKINGS) return false; return true; } bool Rankings::DataSanityCheck(CacheRankingsBlock* node, bool from_list) const { const RankingsNode* data = node->Data(); if (!data->contents) return false; // It may have never been inserted. if (from_list && (!data->last_used || !data->last_modified)) return false; return true; } void Rankings::SetContents(CacheRankingsBlock* node, CacheAddr address) { node->Data()->contents = address; node->Store(); } void Rankings::ReadHeads() { for (int i = 0; i < LAST_ELEMENT; i++) heads_[i] = Addr(control_data_->heads[i]); } void Rankings::ReadTails() { for (int i = 0; i < LAST_ELEMENT; i++) tails_[i] = Addr(control_data_->tails[i]); } void Rankings::WriteHead(List list) { control_data_->heads[list] = heads_[list].value(); } void Rankings::WriteTail(List list) { control_data_->tails[list] = tails_[list].value(); } bool Rankings::GetRanking(CacheRankingsBlock* rankings) { if (!rankings->address().is_initialized()) return false; TimeTicks start = TimeTicks::Now(); if (!rankings->Load()) return false; if (!SanityCheck(rankings, true)) { backend_->CriticalError(ERR_INVALID_LINKS); return false; } backend_->OnEvent(Stats::OPEN_RANKINGS); // Note that if the cache is in read_only mode, open entries are not marked // as dirty, except when an entry is doomed. We have to look for open entries. if (!backend_->read_only() && !rankings->Data()->dirty) return true; EntryImpl* entry = backend_->GetOpenEntry(rankings); if (!entry) { if (backend_->read_only()) return true; // We cannot trust this entry, but we cannot initiate a cleanup from this // point (we may be in the middle of a cleanup already). The entry will be // deleted when detected from a regular open/create path. rankings->Data()->dirty = backend_->GetCurrentEntryId() - 1; if (!rankings->Data()->dirty) rankings->Data()->dirty--; return true; } // Note that we should not leave this module without deleting rankings first. rankings->SetData(entry->rankings()->Data()); CACHE_UMA(AGE_MS, "GetRankings", 0, start); return true; } void Rankings::ConvertToLongLived(CacheRankingsBlock* rankings) { if (rankings->own_data()) return; // We cannot return a shared node because we are not keeping a reference // to the entry that owns the buffer. Make this node a copy of the one that // we have, and let the iterator logic update it when the entry changes. CacheRankingsBlock temp(NULL, Addr(0)); *temp.Data() = *rankings->Data(); rankings->StopSharingData(); *rankings->Data() = *temp.Data(); } void Rankings::CompleteTransaction() { Addr node_addr(static_cast<CacheAddr>(control_data_->transaction)); if (!node_addr.is_initialized() || node_addr.is_separate_file()) { NOTREACHED(); LOG(ERROR) << "Invalid rankings info."; return; } Trace("CompleteTransaction 0x%x", node_addr.value()); CacheRankingsBlock node(backend_->File(node_addr), node_addr); if (!node.Load()) return; node.Store(); Addr& my_head = heads_[control_data_->operation_list]; Addr& my_tail = tails_[control_data_->operation_list]; // We want to leave the node inside the list. The entry must me marked as // dirty, and will be removed later. Otherwise, we'll get assertions when // attempting to remove the dirty entry. if (INSERT == control_data_->operation) { Trace("FinishInsert h:0x%x t:0x%x", my_head.value(), my_tail.value()); FinishInsert(&node); } else if (REMOVE == control_data_->operation) { Trace("RevertRemove h:0x%x t:0x%x", my_head.value(), my_tail.value()); RevertRemove(&node); } else { NOTREACHED(); LOG(ERROR) << "Invalid operation to recover."; } } void Rankings::FinishInsert(CacheRankingsBlock* node) { control_data_->transaction = 0; control_data_->operation = 0; Addr& my_head = heads_[control_data_->operation_list]; Addr& my_tail = tails_[control_data_->operation_list]; if (my_head.value() != node->address().value()) { if (my_tail.value() == node->address().value()) { // This part will be skipped by the logic of Insert. node->Data()->next = my_tail.value(); } Insert(node, true, static_cast<List>(control_data_->operation_list)); } // Tell the backend about this entry. backend_->RecoveredEntry(node); } void Rankings::RevertRemove(CacheRankingsBlock* node) { Addr next_addr(node->Data()->next); Addr prev_addr(node->Data()->prev); if (!next_addr.is_initialized() || !prev_addr.is_initialized()) { // The operation actually finished. Nothing to do. control_data_->transaction = 0; return; } if (next_addr.is_separate_file() || prev_addr.is_separate_file()) { NOTREACHED(); LOG(WARNING) << "Invalid rankings info."; control_data_->transaction = 0; return; } CacheRankingsBlock next(backend_->File(next_addr), next_addr); CacheRankingsBlock prev(backend_->File(prev_addr), prev_addr); if (!next.Load() || !prev.Load()) return; CacheAddr node_value = node->address().value(); DCHECK(prev.Data()->next == node_value || prev.Data()->next == prev_addr.value() || prev.Data()->next == next.address().value()); DCHECK(next.Data()->prev == node_value || next.Data()->prev == next_addr.value() || next.Data()->prev == prev.address().value()); if (node_value != prev_addr.value()) prev.Data()->next = node_value; if (node_value != next_addr.value()) next.Data()->prev = node_value; List my_list = static_cast<List>(control_data_->operation_list); Addr& my_head = heads_[my_list]; Addr& my_tail = tails_[my_list]; if (!my_head.is_initialized() || !my_tail.is_initialized()) { my_head.set_value(node_value); my_tail.set_value(node_value); WriteHead(my_list); WriteTail(my_list); } else if (my_head.value() == next.address().value()) { my_head.set_value(node_value); prev.Data()->next = next.address().value(); WriteHead(my_list); } else if (my_tail.value() == prev.address().value()) { my_tail.set_value(node_value); next.Data()->prev = prev.address().value(); WriteTail(my_list); } next.Store(); prev.Store(); control_data_->transaction = 0; control_data_->operation = 0; backend_->FlushIndex(); } bool Rankings::CheckLinks(CacheRankingsBlock* node, CacheRankingsBlock* prev, CacheRankingsBlock* next, List* list) { CacheAddr node_addr = node->address().value(); if (prev->Data()->next == node_addr && next->Data()->prev == node_addr) { // A regular linked node. return true; } Trace("CheckLinks 0x%x (0x%x 0x%x)", node_addr, prev->Data()->next, next->Data()->prev); if (node_addr != prev->address().value() && node_addr != next->address().value() && prev->Data()->next == next->address().value() && next->Data()->prev == prev->address().value()) { // The list is actually ok, node is wrong. Trace("node 0x%x out of list %d", node_addr, list); node->Data()->next = 0; node->Data()->prev = 0; node->Store(); return false; } if (prev->Data()->next == node_addr || next->Data()->prev == node_addr) { // Only one link is weird, lets double check. if (prev->Data()->next != node_addr && IsHead(node_addr, list)) return true; if (next->Data()->prev != node_addr && IsTail(node_addr, list)) return true; } LOG(ERROR) << "Inconsistent LRU."; STRESS_NOTREACHED(); backend_->CriticalError(ERR_INVALID_LINKS); return false; } bool Rankings::CheckSingleLink(CacheRankingsBlock* prev, CacheRankingsBlock* next) { if (prev->Data()->next != next->address().value() || next->Data()->prev != prev->address().value()) { LOG(ERROR) << "Inconsistent LRU."; backend_->CriticalError(ERR_INVALID_LINKS); return false; } return true; } int Rankings::CheckList(List list) { Addr last1, last2; int head_items; int rv = CheckListSection(list, last1, last2, true, // Head to tail. &last1, &last2, &head_items); if (rv == ERR_NO_ERROR) return head_items; return rv; } // Note that the returned error codes assume a forward walk (from head to tail) // so they have to be adjusted accordingly by the caller. We use two stop values // to be able to detect a corrupt node at the end that is not linked going back. int Rankings::CheckListSection(List list, Addr end1, Addr end2, bool forward, Addr* last, Addr* second_last, int* num_items) { Addr current = forward ? heads_[list] : tails_[list]; *last = *second_last = current; *num_items = 0; if (!current.is_initialized()) return ERR_NO_ERROR; if (!current.SanityCheckForRankings()) return ERR_INVALID_HEAD; scoped_ptr<CacheRankingsBlock> node; Addr prev_addr(current); do { node.reset(new CacheRankingsBlock(backend_->File(current), current)); node->Load(); if (!SanityCheck(node.get(), true)) return ERR_INVALID_ENTRY; CacheAddr next = forward ? node->Data()->next : node->Data()->prev; CacheAddr prev = forward ? node->Data()->prev : node->Data()->next; if (prev != prev_addr.value()) return ERR_INVALID_PREV; Addr next_addr(next); if (!next_addr.SanityCheckForRankings()) return ERR_INVALID_NEXT; prev_addr = current; current = next_addr; *second_last = *last; *last = current; (*num_items)++; if (next_addr == prev_addr) { Addr last = forward ? tails_[list] : heads_[list]; if (next_addr == last) return ERR_NO_ERROR; return ERR_INVALID_TAIL; } } while (current != end1 && current != end2); return ERR_NO_ERROR; } bool Rankings::IsHead(CacheAddr addr, List* list) const { for (int i = 0; i < LAST_ELEMENT; i++) { if (addr == heads_[i].value()) { if (*list != i) Trace("Changing list %d to %d", *list, i); *list = static_cast<List>(i); return true; } } return false; } bool Rankings::IsTail(CacheAddr addr, List* list) const { for (int i = 0; i < LAST_ELEMENT; i++) { if (addr == tails_[i].value()) { if (*list != i) Trace("Changing list %d to %d", *list, i); *list = static_cast<List>(i); return true; } } return false; } // We expect to have just a few iterators at any given time, maybe two or three, // But we could have more than one pointing at the same mode. We walk the list // of cache iterators and update all that are pointing to the given node. void Rankings::UpdateIterators(CacheRankingsBlock* node) { CacheAddr address = node->address().value(); for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end(); ++it) { if (it->first == address && it->second->HasData()) { CacheRankingsBlock* other = it->second; *other->Data() = *node->Data(); } } } void Rankings::InvalidateIterators(CacheRankingsBlock* node) { CacheAddr address = node->address().value(); for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end(); ++it) { if (it->first == address) { DLOG(INFO) << "Invalidating iterator at 0x" << std::hex << address; it->second->Discard(); } } } void Rankings::IncrementCounter(List list) { if (!count_lists_) return; DCHECK(control_data_->sizes[list] < kint32max); if (control_data_->sizes[list] < kint32max) control_data_->sizes[list]++; } void Rankings::DecrementCounter(List list) { if (!count_lists_) return; DCHECK(control_data_->sizes[list] > 0); if (control_data_->sizes[list] > 0) control_data_->sizes[list]--; } } // namespace disk_cache
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: Kernel Library FILE: Graphics/graphicsCreateBitmap.asm AUTHOR: Jim DeFrisco, 5/23/90 ROUTINES: Name Description ---- ----------- CreateBitmap Allocate memory for a bitmap structure GetBitmap Grab a portion of the screen REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 5/23/90 Initial revision DESCRIPTION: This is where the guts of GrCreateBitmap ended up $Id: graphicsBitmapCreate.asm,v 1.1 97/04/05 01:13:18 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GraphicsAllocBitmap segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrCreateBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Allocate memory for a bitmap and associate it with a window CALLED BY: GLOBAL PASS: al - BMType record bx - VM file handle cx - width of bitmap to allocate dx - height of bitmap to allocate di:si - OD for object to get MSG_META_EXPOSED for the bitmap (for process/thread, use di to pass handle) RETURN: ax - VM block handle of bitmap (bx.ax = HugeArray handle) di - gstate handle Note: Fatal error if the unsupported bitmap format is passed in. DESTROYED: nothing PSEUDO CODE/STRATEGY: allocate and initialize huge array for a bitmap; alloc gstate and window; clear bitmap; KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 08/89 Initial version Jim 10/89 Moved most to KLib Jon 06/91 Fixed to properly handle BMC_OD flag Jim 1/92 Completely re-written for 2.0 mg 12/00 Moved bitmap creation into GrCreateBitmapRaw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GCB_frame struct GCB_width word ? ; width of bitmap, pixels GCB_height word ? ; height of bitmap, scan lines GCB_format word ? ; BMFormat enum GCB_bmHan word ? ; handle of allocated bitmap block GCB_vmHan word ? ; VM file handle GCB_optr dword ? ; optr GCB_frame ends GrCreateBitmap proc far uses bx,cx,dx,si,ds,es GCBframe local GCB_frame .enter ; save all the passed parameters mov {byte} GCBframe.GCB_format, al mov GCBframe.GCB_vmHan, bx mov GCBframe.GCB_width, cx mov GCBframe.GCB_height, dx ; store OD passed. mov GCBframe.GCB_optr.low, si mov GCBframe.GCB_optr.high, di ; create the huge array as requested and initialize ; its header to match the passed parameters. call GrCreateBitmapRaw mov GCBframe.GCB_bmHan, ax ; save block handle to return ; allocate a window/gstate and link the bitmap to it. push bp ; we're gonna mess this up good clr ax ; push some bogus parameters push ax ; LayerID push ax ; current process owns it mov ax, GDDT_MEMORY_VIDEO ; get video driver call GeodeGetDefaultDriver push ax ; get video driver handle clr ax push ax ; passing a rectangular window push ax mov cx, GCBframe.GCB_height ; pass bitmap size dec cx push cx mov cx, GCBframe.GCB_width ; pass rectangular win bounds dec cx push cx push ax ; origin at 0,0 push ax mov ah, mask WCF_TRANSPARENT ; no background color clr cx ; no OD for METHOD_?_ENTER mov dx, cx mov di, GCBframe.GCB_optr.high mov bp, GCBframe.GCB_optr.low mov si, mask WPF_ROOT or mask WPF_INIT_EXCLUDED or \ mask WPF_CREATE_GSTATE call WinOpen ; finally, the call pop bp ; lock down the window and enter the bitmap HugeArray handle call MemPLock ; lock the window mov ds, ax ; ds -> window mov ax, GCBframe.GCB_vmHan ; store VM file handle mov ds:[W_bitmap].segment, ax mov ax, GCBframe.GCB_bmHan ; return bitmap handle mov ds:[W_bitmap].offset, ax call MemUnlockV ; release window structure ; before we leave, we should make it so we can draw to the ; bitmap. call GrBeginUpdate ; mask region will be whole call GrEndUpdate ; also, clear the bugger. call GrClearBitmap ; clear data portion ; if there is a mask there, clear that as well. test {byte} GCBframe.GCB_format, mask BMT_MASK jnz initMask done: .leave ret ; the bitmap has a mask. Initialize it to all zeroes. initMask: push ax clr dx mov ax, mask BM_EDIT_MASK call GrSetBitmapMode call GrClearBitmap clr ax call GrSetBitmapMode pop ax jmp done GrCreateBitmap endp bitsAndPlanes label word word 0101h ; BMF_MONO word 0401h ; BMF_4BIT word 0801h ; BMF_8BIT word 0803h ; BMF_24BIT word 0104h ; BMF_4CMYK word 0104h ; BMF_3CMY nColorTable label byte byte 1,4,8,24,4,4 ; #bits of color COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrCreateBitmapRaw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Allocate memory for a bitmap CALLED BY: GLOBAL PASS: al - BMType record bx - VM file handle cx - width of bitmap to allocate dx - height of bitmap to allocate RETURN: ax - VM block handle of bitmap (bx.ax = HugeArray handle) Note: Fatal error if the unsupported bitmap format is passed in. DESTROYED: nothing PSEUDO CODE/STRATEGY: determine huge array size; allocate huge array for a bitmap; initialize bitmap block; The format of the bitmap block is as follows: +- +-------------------------------+ this | | Complex Bitmap Header | size CBitmap part | +-------------------------------+ is in | | BitmapMode flags (1 word) | the | +-------------------------------+ Huge | | Device Info Block | size VideoDriverInfo Array | +-------------------------------+ header | | 1-scan-line buff for vidmem | size depends on width | +-------------------------------+ | | [optional palette space] | either 16 or 256 3-byte +- +-------------------------------+ entries | | | Data Buffer | | | +-------------------------------+ For internal use only: there is an EditableBitmap structure that can be used to access fields in this HugeArray directory block. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- mg 12/00 Extracted code from GrCreateBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GCBR_frame struct GCBR_width word ? ; width of bitmap, pixels GCBR_bwidth word ? ; byte width of bitmap GCBR_sBuffer word ? ; size of buffer in header GCBR_height word ? ; height of bitmap, scan lines GCBR_format word ? ; BMFormat enum GCBR_bmHan word ? ; handle of allocated bitmap block GCBR_vmHan word ? ; VM file handle GCBR_frame ends GrCreateBitmapRaw proc far uses bx,cx,dx,si,di,ds,es GCBRframe local GCBR_frame .enter ; First of all, check for the supported format. If the format ; is not support, we quit. ; push ax andnf al, mask BMT_FORMAT ;al = BMFormat call IsFormatSupported ;carry clr = supported pop ax ERROR_C GRAPHICS_BAD_BITMAP_FORMAT ;unsupported format ; save all the passed parameters mov {byte} GCBRframe.GCBR_format, al mov GCBRframe.GCBR_vmHan, bx mov GCBRframe.GCBR_width, cx EC < tst cx ; can't have zero size> EC < ERROR_Z GRAPHICS_CANT_CREATE_ZERO_SIZED_BITMAP > mov GCBRframe.GCBR_height, dx EC < tst dx ; can't have zero size> EC < ERROR_Z GRAPHICS_CANT_CREATE_ZERO_SIZED_BITMAP > ; calculate the line size (in bytes) call CalcLineSize ; ax = #bytes/scan line mov GCBRframe.GCBR_bwidth, ax ; save line size ; allocate the HugeArray mov di, ax ; we need one a 1-scan buffer mov cx, ax ; #bytes per element shl dx, 1 ; dual purpose buffer is the ; greater of 2*(bitmap height) ; and size of one scan line cmp di, dx ; use the greater ja haveBufferSize mov di, dx ; 2*height is larger... haveBufferSize: mov GCBRframe.GCBR_sBuffer, di ; save this size mov bx, GCBRframe.GCBR_vmHan ; get vm file handle add di, size EditableBitmap ; we might need to allocate some room for a palette. Check ; that out now before we size the header... mov al, {byte} GCBRframe.GCBR_format ; get format bits test al, mask BMT_PALETTE ; check for palette request jz allocHugeArray ; no, allocate the array ; OK, we're adding a palette. Check the size that we need, ; and only do it for 4 and 8-bit/pixel bitmaps. add di, size Palette + (16*size RGBValue) ; add space and al, mask BMT_FORMAT ; isolate bits/pixel cmp al, BMF_4BIT ; if 4-bit, we're done je allocHugeArray ; else assume it's 8-bit add di, 240 * size RGBValue ; so we need 256 altogether cmp al, BMF_8BIT ; make sure it's 8-bit... je allocHugeArray ; if not, then something is bad sub di, size Palette + (256*size RGBValue) and {byte} GCBRframe.GCBR_format, not mask BMT_PALETTE allocHugeArray: call HugeArrayCreate ; di = huge array block handle mov GCBRframe.GCBR_bmHan, di ; save block handle to return ; while we have everything set up, allocate the scan line elem push bp ; save frame pointer mov cx, GCBRframe.GCBR_height ; alloc this many scan lines clr bp ; no init data call HugeArrayAppend ; allocate new elements EC < call ECCheckHugeArrayFar > call HugeArrayCompressBlocks ; take out the extra space EC < call ECCheckHugeArrayFar > ; lock down the directory block, so we can start initializing ; the Complex Bitmap header and the VideoDriverInfo struct call HugeArrayLockDir ; ax -> block mov ds, ax ; ds -> HugeArray dir block mov cx, bp ; cx = mem handle pop bp ; restore frame pointer clr ax ; inti some fields there... mov ds:[EB_flags], ax ; assume edit data, dispersed ; dither mov ds:[EB_color], ax ; no color correction table mov si, offset EB_bm ; ds:si -> CBitmap struct mov ax, GCBRframe.GCBR_width ; get parameters for new bitmap mov ds:[si].B_width, ax mov ax, GCBRframe.GCBR_height mov ds:[si].B_height, ax mov al, {byte} GCBRframe.GCBR_format or al, mask BMT_HUGE or mask BMT_COMPLEX mov ds:[si].B_type, al mov ds:[si].B_compact, BMC_UNCOMPACTED ; no compaction here clr ax ; don't make sense for Huge bm mov ds:[si].CB_numScans, ax mov ds:[si].CB_startScan, ax mov ds:[si].CB_data, ax ; don't need for HugeArray ver mov ds:[si].CB_palette, ax ; assume no palette mov ds:[si].CB_devInfo, offset EB_device - offset EB_bm ; now we check to see if we need to initialize the Palette. segmov es, ds, ax ; es -> Bitmap test {byte} GCBRframe.GCBR_format, mask BMT_PALETTE jz initDeviceInfo ; initialize the palette ; OK, we're gonna initialize a palette. We need to fill in ; two things, the number of entries, and the palette contents mov di, GCBRframe.GCBR_sBuffer ; construct pointer to Palette add di, (size EditableBitmap) - (size HugeArrayDirectory) mov ds:[si].CB_palette, di ; store offset to Palette add di, size HugeArrayDirectory ; construct real offset mov al, ds:[si].B_type ; get bitmap format and al, mask BMT_FORMAT ; isolate color info mov cx, 16 ; assume 4-bit device cmp al, BMF_4BIT ; is it 4-bit ? je initBitmap ; yes, continue mov cx, 256 cmp al, BMF_8BIT je initBitmap mov cx, 2 ; if not 4 | 8-bit, must be mono initBitmap: LoadVarSeg ds, ax ; ds -> idata mov es:[di],cx ; set size of palette add di, size Palette ; set pointer past palette size mov si, offset defaultPalette ; ds:si -> default palette mov ax, cx ; calc #bytes to move shl cx, 1 ; 3 bytes/entry add cx, ax ; cx = #bytes to move shr cx, 1 ; calc #words (will be even) rep movsw ; now init the device info table. First get the address of ; the mem driver strategy routine initDeviceInfo: mov di, offset EB_bm ; es:di -> bitmap mov ax, 72 ; init bitmap resolution mov es:[di].CB_xres, ax mov es:[di].CB_yres, ax mov dx, GCBRframe.GCBR_bwidth call AllocBitmapInitDeviceInfo segmov ds, es, ax ; es -> Bitmap ; we're done with the HugeArray initialization, so close it call HugeArrayDirty call HugeArrayUnlockDir ; release the directory block mov ax, GCBRframe.GCBR_bmHan ; return bitmap handle .leave ret GrCreateBitmapRaw endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% IsFormatSupported %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Check if the passed bitmap format is supported. CALLED BY: GrCreateBitmap() PASS: al = BMFormat RETURN: carry = clear (supported) = set (not supported) DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- CL 11/ 2/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ IsFormatSupported proc near uses bx, ds, si, di .enter ; ; Get the default VidMem Driver handle. ; push ax mov ax, GDDT_MEMORY_VIDEO call GeodeGetDefaultDriver ;ax = GeodeHandle tst ax ;no default driver? jz noDriver mov_tr bx, ax ;bx = GeodeHandle call GeodeInfoDriver ;ds:si = info block ; ; If carry clear, then the bitmap format is supported. Otherwise, ; it is not supported. ; pop ax ;al = BMFormat mov di, VID_ESC_CHECK_IF_FORMAT_IS_SUPPORTED call ds:[si].DIS_strategy ;carry set or clr done: .leave ret noDriver: pop ax stc jmp done IsFormatSupported endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrEditBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Associate a previously created bitmap with a Window and GState CALLED BY: GLOBAL PASS: bx - VM file handle containing bitmap ax - VM block handle of first block in bitmap (the directory block of the associated HugeArray) di:si - OD for object to get MSG_META_EXPOSED for the bitmap (for process/thread, use di to pass handle) RETURN: di - GState handle to use when drawing to bitmap DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 6/18/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrEditBitmap proc far uses ds, bp, ax, bx, cx, dx, si .enter ; lock down the bitmap header and extract some interesting ; information. push di, si ; save OD for EXPOSEDs mov di, ax ; bx:di -> HugeArray call HugeArrayLockDir ; lock directory block mov ds, ax ; ds -> EditableBitmap ; while we're here, we should do a little error checking, just ; to make sure that we have what we think we have. EC < test ds:[EB_bm].CB_simple.B_type, mask BMT_COMPLEX > EC < ERROR_Z GRAPHICS_EDIT_BITMAP_NEEDS_HUGE_BITMAP > EC < tst ds:[EB_bm].CB_devInfo ; if zero, bail > EC < ERROR_Z GRAPHICS_EDIT_BITMAP_NEEDS_HUGE_BITMAP > EC < cmp ds:[EB_bm].CB_simple.B_compact, BMC_UNCOMPACTED > EC < ERROR_NE GRAPHICS_CANT_DO_THIS_WITH_COMPACTED_BITMAP > ; load up height and width of bitmap so we can use it to ; size the window mov cx, ds:[EB_bm].CB_simple.B_width mov dx, ds:[EB_bm].CB_simple.B_height ; that's all we need, so release the HugeArray dir block call HugeArrayUnlockDir ; allocate a window/gstate and link the bitmap to it. ; at this point, regs should be: ; bx:di - VM file/block handle of bitmap ; cx,dx - width, height pop si, bp ; restore EXPOSE OD push bx, di ; save VM block handle clr ax ; push some bogus parameters push ax ; LayerID push ax ; current process owns it mov ax, GDDT_MEMORY_VIDEO ; get video driver call GeodeGetDefaultDriver push ax ; get video driver handle clr ax push ax ; passing a rectangular window push ax dec dx ; one less for bottom coord push dx dec cx ; one less for right side coord push cx push ax ; origin at 0,0 push ax mov ah, mask WCF_TRANSPARENT ; no background color clr cx ; no OD for METHOD_?_ENTER mov dx, cx mov di, si ; setup EXPOSED OD in di:bp mov si, mask WPF_ROOT or mask WPF_INIT_EXCLUDED or \ mask WPF_CREATE_GSTATE call WinOpen ; finally, the call pop si, dx ; restore VM block handle ; lock down the window and enter the bitmap HugeArray handle call MemPLock ; lock the window mov ds, ax ; ds -> window xchg si, bx ; bx = VM file han, si=win han mov ds:[W_bitmap].segment, bx mov ds:[W_bitmap].offset, dx xchg si, bx ; bx = window handle call MemUnlockV ; release window structure ; before we leave, we should make it so we can draw to the ; bitmap. call GrBeginUpdate ; mask region will be whole call GrEndUpdate ; get the current resolution, so we can properly set the window ; scale factor mov si, bx ; si = window handle call GrGetBitmapRes ; get the current resolution cmp ax, DEF_BITMAP_RES ; if 72 dpi, done. jne setScale cmp bx, DEF_BITMAP_RES je done setScale: push di ; save GState handle mov di, si ; di = window handle push ax ; save new x res mov dx, bx ; do y first mov bx, DEF_BITMAP_RES ; divide by default resolution clr cx, ax ; no fractions call GrSDivWWFixed ; dxcx = y scale to apply mov ax, dx ; axcx = y scale factor pop dx ; restore new x res mov bx, DEF_BITMAP_RES ; divide by default res pushwwf axcx ; save y scale factor clr cx, ax ; no fractions call GrSDivWWFixed ; dxcx = x scale factor popwwf bxax ; bxax = y scale factor mov si, WIF_DONT_INVALIDATE call WinApplyScale pop di ; restore GState handle done: .leave ret GrEditBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrDestroyBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Free the bitmap, disassociate with window CALLED BY: GLOBAL PASS: di - gstate handle (as returned by GrCreateBitmap) al - flags controlling destruction: BMD_KILL_DATA - kill bitmap data too BMD_LEAVE_DATA - leave bitmap data alone RETURN: nothing DESTROYED: di PSEUDO CODE/STRATEGY: free window and gstate, perhaps bitmap as well KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 08/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrDestroyBitmap proc far uses ax, ds, bx haHandle local dword .enter ; do some error checking on passed flags EC < cmp al, BMD_LEAVE_DATA > EC < ERROR_A GRAPHICS_BAD_FLAGS_RESERVED_MUST_BE_0 > clr haHandle.segment ; we'll use this to determine ; if we need to kill bitmap push ax ; save flag ; get the bitmap handle. We need to kill the window anyway mov bx, di ; bx = gstate handle call MemLock ; lock gstate mov ds, ax mov ax, ds:[GS_window] ; get window handle call MemUnlock ; release gstate mov bx, ax ; load up window handle call MemPLock ; lock the window mov ds, ax ; ds -> Window mov ax, ds:[W_bitmap].offset ; get block handle mov haHandle.offset, ax mov ax, ds:[W_bitmap].segment mov haHandle.segment, ax call MemUnlockV ; release window ; kill the window and gstate call WinClose ; kill window and gstate ; free the bitmap last, since WinClose wants to use it pop ax ; restore flag cmp al, BMD_LEAVE_DATA ; if we are to leave it alone je done mov bx, haHandle.segment ; load up VM file handle tst bx ; if zero, nothing to do jz done mov di, haHandle.offset ; get VM block handle call HugeArrayDestroy ; kill bitmap done: .leave ret GrDestroyBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrSetBitmapMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set mode bits for an editable bitmap CALLED BY: GLOBAL PASS: di - GState handle, as returned by GrCreateBitmap ax - BitmapMode record, including bits: BM_EDIT_MASK - to have subsequent drawing operations affect the mask instead of the picture data BM_CLUSTERED_DITHER - to use a clustered dither for writing operations - only works for BMF_MONO bitmaps dx - ColorTransfer handle (0 if none supplied) RETURN: carry set if GState not pointing at a bitmap, else ax - flags actually set. This will be the same as what was passed, typically. If the bitmap has no mask, and the BM_EDIT_MASK bit was set, then the bit will be cleared in the return value. DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: If the bitmap doesn't have a mask, then calling this function with the BM_EDIT_MASK bit set will have no effect. REVISION HISTORY: Name Date Description ---- ---- ----------- jim 2/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrSetBitmapMode proc far uses ds, bx, di .enter EC < test ax,not (mask BM_EDIT_MASK or mask BM_CLUSTERED_DITHER)> EC < ERROR_NZ GRAPHICS_BAD_BITMAP_MODE > push ax ; save flag call LockHugeBitmap ; ds -> HugeBitmap pop ax ; restore flag jc done ; bail if error test ax, mask BM_EDIT_MASK ; if editing mask, make sure jz storeFlags ; there is one. test ds:[EB_bm].CB_simple.B_type, mask BMT_MASK jnz storeFlags ; all ok and ax, not (mask BM_EDIT_MASK) ; no mask, so clear bit. storeFlags: mov ds:[EB_flags], ax ; store flags mov ds:[EB_color], dx ; store flags call HugeArrayDirty call HugeArrayUnlockDir ; clear the flags clc done: .leave ret GrSetBitmapMode endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrGetBitmapMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set mode bits for an editable bitmap CALLED BY: GLOBAL PASS: di - GState handle, as returned by GrCreateBitmap RETURN: carry set if GState not pointing at a bitmap, else ax - BitmapMode record, including bits: BM_EDIT_MASK - to have subsequent drawing operations affect the mask instead of the picture data BM_CLUSTERED_DITHER - to use a clustered dither for writing operations - only works for BMF_MONO bitmaps DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 2/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrGetBitmapMode proc far uses ds, bx, di .enter call LockHugeBitmap ; ds -> HugeBitmap jc done mov ax, ds:[EB_flags] ; store flags call HugeArrayUnlockDir ; clear the flags clc done: .leave ret GrGetBitmapMode endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrClearBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Clear out content of a bitmap CALLED BY: GLOBAL PASS: di - gstate allocated by GrCreateState RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: The part of the bitmap actually cleared (set to white) depends on the bitmap mode. For the normal mode, the data portion of the bitmap is cleared, and the masks are left alone. If the bitmap is in BM_EDIT_MASK mode, then the mask is cleared and the data portion is left alone. NOTE: The value written into the data portion of the bitmap depends on the color format of the bitmap. Since "white" is zero for monochrome bitmaps, the value 0x00 is written to all bytes. For other color formats, white is 0xff, so that value is written. KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 01/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrClearBitmap proc far uses ax, cx, dx, es, bx, ds, di, si clearValue local word .enter ; first lock the block, then fire away call LockHugeBitmap ; ds -> HugeBitmap jc done mov si, offset EB_bm mov cx, ds:[si].B_height mov dx, ds:[si].B_width ; dx = element size mov ah, ds:[si].B_type ; get type mov al, {byte} ds:[EB_flags] ; mov si, ds:[HAD_size] ; get size of element EC < tst si ; if zero, bad news > EC < ERROR_Z GRAPHICS_CANT_DO_THIS_WITH_COMPACTED_BITMAP > call HugeArrayUnlockDir ; release bitmap block test ah, mask BMT_MASK ; is there a mask ? jnz haveMask ; there's a mask clr dx ; offset into scan calcClearValue: mov ss:clearValue, 0xffff ; assume white and ah, mask BMT_FORMAT ; isolate color format cmp ah, BMF_MONO je clearZero cmp ah, BMF_4CMYK jb setScanOffset clearZero: mov ss:clearValue, 0x0000 setScanOffset: mov ax, dx ; ax = offset into elem ; for each element in the array, clear it. clearArrayCommon: push cx, si, ax ; save loop count clr ax, dx call HugeArrayLock ; ds:si -> element pop cx, dx, ax ; dx = elem size elemLoop: push cx, dx, ax ; save loop count mov cx, dx ; cx = byte count segmov es, ds, di mov di, si ; es:di -> element add di, ax mov ax, ss:clearValue rep stosb call HugeArrayDirty ; mark block as dirty call HugeArrayNext ; ds:si -> next element pop cx, dx, ax loop elemLoop ; unlock the final block call HugeArrayUnlock clc done: .leave ret ; if there's a mask, then we either have to clear it, or clear ; what's after it. Either way, we need to calculate how ; big the mask is. haveMask: add dx, 7 ; pad to nearest byte shr dx, 1 shr dx, 1 shr dx, 1 test al, mask BM_EDIT_MASK ; if editing the mask jz clearData mov si, dx ; set size to mask size mov ss:clearValue, 0x0000 clr ax jmp clearArrayCommon ; we're not in EDIT_MASK mode, so clear the data part clearData: sub si, dx ; si = #bytes to clear jmp calcClearValue GrClearBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LockHugeBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Utility routine used by a few HugeBitmap routines CALLED BY: INTERNAL GrSetBitmapMode, GrGetBitmapMode PASS: di - GState handle allocated in GrCreateBitmap RETURN: carry clear if successful ds - pointing to locked HugeArray bitmap bx:di - VM file/block handle to bitmap carry set if error DESTROYED: ax (ds, bx, di also destroyed if carry set) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 2/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LockHugeBitmap proc near mov bx, di ; lock GState call MemLock ; ax -> GState jc done mov ds, ax ; ds -> GState mov ax, ds:[GS_window] ; get window handle call MemUnlock tst ax stc jz done mov_tr bx, ax ; lock window call MemPLock ; ax -> Window jc done mov ds, ax ; ds -> Window mov ax, ds:[W_bitmap].segment ; get VM file handle mov di, ds:[W_bitmap].offset ; get VM block handle call MemUnlockV ; release window tst ax stc jz done mov_tr bx, ax ; bx.di -> HugeBitmap call HugeArrayLockDir ; lock directory mov ds, ax ; ds -> HugeArray dir block clc done: ret LockHugeBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrGetPoint %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the color of a single pixel CALLED BY: GLOBAL PASS: di - GState ax, bx - coord of point (document coords) RETURN: ah - raw pixel value (except 24-bit devices) al - pixel color (red component) bl - pixel color (green component) bh - pixel color (blue component) DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: If the point is outside the window, BLACK is returned. REVISION HISTORY: Name Date Description ---- ---- ----------- jim 8/ 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrGetPoint proc far call EnterGraphics ; returns with ds->gState jc quickExit ; es->window ; make sure there is a window and it has a real clip region. tst ds:[GS_window] ; if no window, bail jz returnBlack test es:[W_grFlags], mask WGF_MASK_NULL ; see if null mask jnz returnBlack call GrTransCoordFar ; do coord translation ; if the coordinate is outside the window bounds, return BLACK cmp ax, es:[W_winRect].R_left ; check left/right jl returnBlack ; if out, say so cmp ax, es:[W_winRect].R_right jg returnBlack cmp bx, es:[W_winRect].R_top ; check top/bottom jl returnBlack ; if out, say so cmp bx, es:[W_winRect].R_bottom jg returnBlack mov di, DR_VID_GETPIXEL ; get some bits call es:[W_driverStrategy] ; get the value ; ; Store return values from GetPixel in EnterGraphics frame ; for return to our caller ; done: mov bp, sp mov ss:[bp].EG_ax, ax mov ss:[bp].EG_bx, bx jmp ExitGraphics ; graphical string open...don't do anything quickExit: mov ss:[bp].EG_ax, 0 ; just set return value to zero mov ss:[bp].EG_bx, 0 jmp ExitGraphicsGseg ; outside the window, return black returnBlack: clr ax, bx jmp done GrGetPoint endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrGetBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy a bitmap from the screen to system memory CALLED BY: GLOBAL PASS: di - handle to gstate ax - x coordinate of source rectangle (document units) bx - y coordinate of source rectangle (document units) cx - bitmap width (document units) dx - bitmap height (document units) RETURN: bx - handle to memory block allocated for bitmap - 0 if error allocating memory cx - width of bitmap copied (pixels) dx - height of bitmap copied (pixels) DESTROYED: nothing PSEUDO CODE/STRATEGY: copy as much of bitmap as can be copied in 64K; fix return values; KNOWN BUGS/SIDE EFFECTS/IDEAS: This function does NOT do any checking of the source rectangle to determine if/how it is clipped by other windows. This function will probably be useful for screen dumps, but may not be as useful for normal application use. One exception will be when it is used in conjunction with a memory driver, where it is unlikely that there will be any overlapping windows. REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrGetBitmap proc far call EnterGraphics ; returns with ds->gState jc quickExit ; es->window ; make sure there is a window too tst ds:[GS_window] ; if no window, bail jz done call GetBitmap ; let KLib do it ; ; Store return values from GetBitmap in EnterGraphics frame ; for return to our caller ; mov bp, sp mov ss:[bp].EG_cx, cx mov ss:[bp].EG_dx, dx mov ss:[bp].EG_bx, si done: jmp ExitGraphics ;------------------------------------------------------------------------ ; graphical segment open...don't do anything quickExit: jmp ExitGraphicsGseg GrGetBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy a bitmap from the screen to system memory CALLED BY: GLOBAL PASS: di - handle to gstate ax - x coordinate of source rectangle (document units) bx - y coordinate of source rectangle (document units) cx - bitmap width (document units) dx - bitmap height (document units) bp - offset of EnterGraphics frame on stack RETURN: si - handle to memory block allocated for bitmap - 0 if error allocating memory cx - width of bitmap copied (pixels) dx - height of bitmap copied (pixels) DESTROYED: nothing PSEUDO CODE/STRATEGY: copy as much of bitmap as can be copied in 64K; fix return values; KNOWN BUGS/SIDE EFFECTS/IDEAS: This function does NOT do any checking of the source rectangle to determine if/how it is clipped by other windows. This function will probably be useful for screen dumps, but may not be as useful for normal application use. One exception will be when it is used in conjunction with a memory driver, where it is unlikely that there will be any overlapping windows. This function does not work well when rotation is applied. REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 10/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GGB_local struct GGB_x dw ? ; x position of bitmap GGB_y dw ? ; y position of bitmap GGB_width dw ? ; width of bitmap GGB_height dw ? ; height of bitmap GGB_local ends GGB_loc equ [bp-size GGB_local] ; constant for MemAlloc flag: makes code look nicer GGB_MEM_FLAGS equ ((mask HAF_ZERO_INIT or mask HAF_LOCK) shl 8) or mask HF_SHARABLE or mask HF_SWAPABLE ;---------------------------------------------------------------------- ; complex transformation GGB_complex: xchg ax, cx ; translate the height and width xchg bx, dx ; too call GrTransCoordFar ; do translation sub ax, es:[W_winRect].R_left ; get win relative sub bx, es:[W_winRect].R_top xchg ax, cx ; get everything back where it xchg bx, dx ; was jmp short GGB_saveSize GetBitmap proc near ; allocate some local scratch ; mov bp, sp ; bp saved by EnterGraphics sub sp, size GGB_local ; translate coordinates and save for later call GrTransCoordFar ; translate point test es:[W_curTMatrix].TM_flags, TM_COMPLEX jnz GGB_complex ; if no scaling, all ok GGB_saveSize label near mov GGB_loc.GGB_x, ax ; store parms away first mov GGB_loc.GGB_y, bx mov GGB_loc.GGB_height, dx ; save dx since we trash it soon ; calculate the size of the block we need call GetBitSizeBlock ; dx:ax = size of block (int32) jc GGB_exit ; if nothing visible, just exit ; see if bytes needed are > 64K, if not -- allocate away tst dx ; see if high word is non-zero jnz GGB_huge ; yes, handle huge bitmaps mov si, ax ; save the size of the block mov cx, GGB_MEM_FLAGS ; set MemAlloc flags call MemAllocFar ; allocate memory for bitmap jc GGB_memError ; error allocating... ; everything copasetic, call the driver push bx ; save handle push ds ; save gstate segment push bp mov ds, ax ; set ds = segment of block mov ax, GGB_loc.GGB_x ; set the position mov bx, GGB_loc.GGB_y mov cx, GGB_loc.GGB_width ; set size mov dx, GGB_loc.GGB_height clr bp ; ds:bp -> empty block mov di, DR_VID_GETBITS ; get some bits call es:[W_driverStrategy] ; fill the buffer pop bp pop ds ; restore gstate segment pop bx ; restore memory handle call MemUnlock ; unlock the block before ret ; all done -- fixup return values, restore stack and leave GGB_exit: mov cx, GGB_loc.GGB_width ; get width mov dx, GGB_loc.GGB_height ; get height mov si, bx ; return handle too. mov sp, bp ; restore stack pointer ret ;------------------------------------------------------------------------ ; error allocating memory, just quit GGB_memError: clr bx ; set error return value jmp GGB_exit ; huge bitmap, just return for now, need to handle somehow GGB_huge: clr bx ; set error return value jmp GGB_exit GetBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetBitSizeBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Utility routine for GetBitmap to size the block required CALLED BY: INTERNAL GetBitmap PASS: see GetBitmap, above RETURN: carry - set if no part of bitmap is visible - clear for something to copy dx:ax - size of block to allocate (32-bits) DESTROYED: ax,cx,dx,si,di PSEUDO CODE/STRATEGY: restrict passed size to window bounds; calculate #bytes needed; KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 05/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetBitSizeBlock proc near ; first calc and save the maximum width and height. This ; allows calculating the actual width and height of the transfer mov dx, es:[W_winRect].R_right ; get right side of window sub dx, ax ; sub left side coord inc dx ; one more for width js GBSB_exit ; exit if nothing to copy cmp dx, cx ; use lesser of max and desired jg GGB_savMaxW ; skip the exchange xchg cx, dx GGB_savMaxW: mov GGB_loc.GGB_width, cx ; store width mov dx, es:[W_winRect].R_bottom ; get bottom side of window sub dx, bx ; sub top side coord inc dx ; one more for width js GBSB_exit ; exit if nothing to copy cmp dx, GGB_loc.GGB_height ; use lesser of max and desired jg GGB_savedHeight ; skip the exchange mov GGB_loc.GGB_height, dx ; need to calc how big a block to alloc. first get info ; about the device, then calc away GGB_savedHeight: mov di, DR_VID_INFO ; call driver to get ptr to call es:[W_driverStrategy] ; info table dx:si -> table push ds ; save gstate ptr mov ds, dx ; ds:si -> info block mov cx, GGB_loc.GGB_width ; retreive width of transfer mov al, ds:[si].VDI_bmFormat ; get format of buffer pop ds ; don't need pointer anymore call CalcLineSize ; calc #bytes/scan mov dx, GGB_loc.GGB_height mul dx ; dx:ax = #bytes needed add ax, size Bitmap ; add in some for header adc dx, 0 clc ; no error ret ;--------------------------------------------------------------------- ; nothing visible, exit GBSB_exit: stc ret GetBitSizeBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrCompactBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Compact a HugeBitmap CALLED BY: GLOBAL PASS: bx:ax - VM file:block handle containing bitmap dx - VM file for destination bitmap (may be the same as bx) RETURN: dx:cx - VM file:block handle of new compacted bitmap. DESTROYED: nothing PSEUDO CODE/STRATEGY: Create the destination HugeArray. For each scan line in the original bitmap Compact it and append it to the destination. KNOWN BUGS/SIDE EFFECTS/IDEAS: The resulting bitmap is *not* editable. That is, you cannot use GrEditBitmap to start drawing into the compacted bitmap. REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/13/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SENTINEL = 'D' or ('R' shl 8) GrCompactBitmap proc far uses es, ds, si, di, ax, bx oldBMfile local word oldBMblock local word newBMfile local word newBMblock local word scratchBlock local hptr scanSize local word EC <sentinelOffset local word > EC <uncompactOffset local word > .enter ; save away some info mov newBMfile, dx ; save new file handle mov oldBMfile, bx mov oldBMblock, ax ; allocate a new HugeArray to store the new bitmap into. ; make the directory headers size on the new one the same ; size as the old one, so we don't lose any info mov di, ax ; bx:di = old BM call HugeArrayLockDir ; mov ds, ax ; ds -> EditableBitmap EC < cmp ds:[EB_bm].CB_simple.B_compact, BMC_UNCOMPACTED > EC < ERROR_NE GRAPHICS_BITMAP_ALREADY_COMPACTED > mov di, ds:[LMBH_offset] ; di = size of header clr cx ; it's variable sized mov bx, dx ; bx = new VM file handle call HugeArrayCreate ; di = new VM block handle mov newBMblock, di ; lock down the headers and copy the usual info across. call HugeArrayLockDir ; lock down new one mov es, ax mov di, EB_bm ; es:di -> CBitmap structure mov si, di ; ds:si -> CBitmap Structure mov cx, ds:[LMBH_offset] ; cx = size of header sub cx, si ; cx = part we're interested in rep movsb ; for now ; release the source block, and fixup the info in the new ; block. call HugeArrayUnlockDir ; release the source directory mov di, EB_bm ; es:di -> new bitmap struct mov es:[di].CB_simple.B_compact, BMC_PACKBITS clr es:[di].CB_devInfo ; make it not editable ; Allocate a small buffer to do the compaction. Release the ; destination directory block. The maximum buffer size ; required is (# of bytes per scan line) + 1 + (# of bytes ; per scan line / 128 rounded up). See the header of ; CompactPackBits() for why this is so. mov cx, es:[di].CB_simple.B_width ; cx = #scans to do mov al, es:[di].CB_simple.B_type call CalcLineSize ; ax = uncompacted scan size mov scanSize, ax ; save uncompacted scan size add ax, 2 ; add one + possible round mov cx, ax shl cx, 1 ; ch = # of 128 byte pieces add al, ch adc ah, 0 EC < mov sentinelOffset, ax ; offset to sentinel > EC < add ax, 2 ; add word for sentinel > EC < mov uncompactOffset, ax ; offset to uncompacted > EC < add ax, scanSize > EC < add ax, 2 ; add word for sentinel > mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK call MemAllocFar ; bx = file handle mov scratchBlock, bx ; mov cx, es:[di].CB_simple.B_height ; cx = #scans to do segmov ds, es ; release source dir block call HugeArrayDirty call HugeArrayUnlockDir mov es, ax ; es -> newly alloc'd block EC < mov di, sentinelOffset ; initialize sentinel > EC < mov {word} es:[di], SENTINEL > EC < mov di, uncompactOffset ; ...and 2nd sentinel > EC < add di, scanSize > EC < mov {word} es:[di], SENTINEL > ; loop for each scan line, compacting as we go. ; REGISTER USAGE: ; cx = #scans to do ; es -> scratch block ; ds:si -> source scan line ; bx:di -> destination HugeArray file/block handle push cx ; save #scans to do mov di, oldBMblock mov bx, oldBMfile clr ax, dx call HugeArrayLock ; ds:si -> first scan line pop cx jmp startScan scanLoop: call HugeArrayNext ; ds:si -> next scan line startScan: push cx ; save #scanlines to go mov cx, scanSize ; pass input scanline size clr di ; es:di -> output buffer call CompactPackBits ; compact a single scan line EC < mov di, sentinelOffset ; verify the sentinel > EC < cmp {word} es:[di], SENTINEL > EC < ERROR_NE GRAPHICS_SENTINEL_FOR_BITMAP_COMPRESSION_CORRUPTED > ; now verify that the compacted data is valid EC < push cx, si > EC < push ds, si > EC < mov di, uncompactOffset ; es:di -> destination > EC < segmov ds, es > EC < clr si ; ds:si -> source > EC < mov cx, scanSize > EC < call UncompactPackBitsFar > EC < pop ds, si ; ds:si -> original data> EC < mov di, uncompactOffset ; es:di -> new data > EC < mov cx, scanSize > EC < repe cmpsb ; compare them bytes > EC < ERROR_NZ GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > EC < cmp {word} es:[di], SENTINEL > EC < ERROR_NZ GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > EC < pop cx, si > ; finished compaction. Write out the buffer. mov di, newBMblock mov bx, newBMfile push si, bp mov bp, es clr si call HugeArrayAppend pop si, bp pop cx loop scanLoop ; release the last block of the source array and scratch buff call HugeArrayUnlock ; release the last block mov bx, scratchBlock call MemFree ; return the correct information about the new BM mov dx, newBMfile ; return file and mov cx, newBMblock ; block handle .leave ret GrCompactBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CompactPackBits %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Run-length encode a single scan line of a bitmap CALLED BY: INTERNAL GrCompactBitmap PASS: ds:si - pointer to bitmap scanline data cx - #bytes in input scan line es:di - pointer to output buffer (should be sized about 1% larger than original scan, for the degenerate case). RETURN: cx - #bytes in compacted scan line DESTROYED: nothing PSEUDO CODE/STRATEGY: The format is as follows: <count><pattern>+ where: if <count> is less than 0x80 the count byte is followed by "count+1" number of individual bytes. if <count> is 0x80 through 0xff the count byte is followed by a single pattern byte, which should be copied (-count)+1 times The latter case is only used for a sequence of bytes of length three or more, as otherwise we could get an alternating pattern of of the two types of data storage that would result in more space being occuppied then the uncompressed bitmap. REGISTER USAGE: AH = Byte to match BX = Start of unique or repeat byte sequence DL = Unique byte sequence count DH = Repeat byte sequence count CX = # of bytes left in original scan line DS:SI = Scan-line soure ES:DI = Compacted scan-line destination KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/13/92 Initial version don 1/12/94 Re-wrote %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CompactPackBits proc near uses ax, bx, dx, si .enter ; Start the whole process ; push di ; save starting offset newSeed: jcxz done lodsb dec cx jmp uniqueStart ; We've run out of bytes in the middle of a unique series cleanUpUnique: dec dl EC < cmp dl, 127 ; can't be more than 127 > EC < ERROR_A GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > mov es:[bx], dl ; end unique count ; We're done - return the number of bytes in the scan-line done: mov cx, di ; last offset => CX pop di ; starting offset => DI sub cx, di ; cx = # destination bytes .leave ret ; We've just found a byte that does not match the previous uniqueStart: mov bx, di inc di ; leave room for count byte stosb ; store this first byte mov ah, al mov dx, 0x101 ; initialize both counts uniqueByte: jcxz cleanUpUnique lodsb dec cx stosb cmp ah, al je endUniqueness mov ah, al mov dh, 1 ; initialize repeat count uniqueContinue: inc dl ; increment unique count cmp dl, 128 ; compare against maximum count jne uniqueByte EC < cmp dl, 128 ; can't be more than 127 > EC < ERROR_A GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > dec dl ; reached maximum byte count mov es:[bx], dl ; ...so store (count - 1) jmp newSeed ; look for a new seed byte again endUniqueness: inc dh ; increment repeat count cmp dh, 2 ; if only two matches jle uniqueContinue ; ...then keep on going cmp dl, 2 ; if unique count is only 2(+1), je matchStart ; ...then no unique bytes sub dl, 3 ; subtract repeat length EC < cmp dl, 127 ; can't be more than 127 > EC < ERROR_A GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > mov es:[bx], dl ; store unique count inc di ; We've found three consecutive matching bytes. matchStart: sub di, 2 ; we've written three matching mov bx, di ; ...bytes, we'll use byte 0 sub bx, 2 ; ...to hold the count and start ; ...storing bytes at byte 2 matchByte: jcxz cleanUpRepeat lodsb dec cx cmp ah, al jne endMatching inc dh ; increment repeat count cmp dh, 128 ; see if we've wrapped jbe matchByte ; ...if not, continue dec dh ; ...else end run of matches ; We've end a run of matching bytes. Store the count endMatching: EC < cmp dh, 3 ; must be at least 3 matches > EC < ERROR_B GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > EC < cmp dh, 128 ; can't be more than 128 > EC < ERROR_A GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > dec dh neg dh mov es:[bx], dh jmp uniqueStart ; We've run out of bytes in the middle of a repeat series cleanUpRepeat: EC < cmp dh, 128 ; can't be more than 128 > EC < ERROR_A GRAPHICS_BITMAP_COMPACTION_INTERNAL_ERROR > dec dh neg dh mov es:[bx], dh jmp done CompactPackBits endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrUncompactBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Uncompact a HugeBitmap CALLED BY: GLOBAL PASS: bx:ax - VM file:block handle containing bitmap dx - VM file for destination bitmap (may be the same as bx) RETURN: dx:cx - VM file:block handle of new compacted bitmap. DESTROYED: nothing RETURN: DESTROYED: PSEUDO CODE/STRATEGY: Take the easy route. Create a bitmap and draw this one into it. KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/13/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrUncompactBitmap proc far uses es, ds, si, di, ax, bx oldBMfile local word oldBMblock local word newBMfile local word newBMblock local word scratchBlock local hptr scanSize local word .enter ; save away some info mov newBMfile, dx ; save new file handle mov oldBMfile, bx mov oldBMblock, ax ; access the current bitmap mov di, ax ; bx:di = old BM call HugeArrayLockDir ; mov ds, ax ; ds -> EditableBitmap EC < cmp ds:[EB_bm].CB_simple.B_compact, BMC_PACKBITS > EC < ERROR_NE GRAPHICS_BITMAP_MUST_BE_PACKBITS > ; calculate the width of the bitmap in bytes mov al, ds:[EB_bm].CB_simple.B_type mov cx, ds:[EB_bm].CB_simple.B_width call CalcLineSize ; ax = bytes / scanline mov scanSize, ax ; allocate the new bitmap (in a HugeArray, of course) mov bx, dx ; bx = new VM file handle mov_tr cx, ax ; cx = scan size (bytes / line) mov di, ds:[LMBH_offset] ; size of header + extra space call HugeArrayCreate ; di = new VM block handle mov newBMblock, di ; lock down the headers and copy the usual info across. call HugeArrayLockDir ; lock down new one mov es, ax mov di, EB_bm ; es:di -> CBitmap structure mov si, di ; ds:si -> CBitmap Structure mov cx, ds:[LMBH_offset] ; cx = size of header sub cx, si ; cx = part we're interested in rep movsb ; for now ; release the source block, and fixup the info in the new ; block. call HugeArrayUnlockDir ; release the source directory mov di, EB_bm ; es:di -> new bitmap struct mov es:[di].CB_simple.B_compact, BMC_UNCOMPACTED mov es:[di].CB_devInfo, offset EB_device - offset EB_bm ; initialize the device info mov dx, scanSize call AllocBitmapInitDeviceInfo ; Allocate a small buffer to do the de-compaction. Release the ; destination directory block mov ax, scanSize ; get uncompacted scan size mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK call MemAllocFar ; bx = file handle mov scratchBlock, bx mov cx, es:[EB_bm].CB_simple.B_height segmov ds, es ; release source dir block call HugeArrayDirty ; dirty the block call HugeArrayUnlockDir mov es, ax ; es -> scratch block ; loop for each scan line, compacting as we go. ; REGISTER USAGE: ; cx = #scans to do ; es -> scratch block ; ds:si -> source scan line ; bx:di -> destination HugeArray file/block handle push cx ; save height of bitmap mov di, oldBMblock mov bx, oldBMfile clr ax, dx call HugeArrayLock ; ds:si -> first scan line pop cx ; cx = # of scanlines jmp startScan scanLoop: call HugeArrayNext ; ds:si -> next scan line startScan: push cx ; save #scanlines to go mov cx, scanSize ; pass input scanline size push si ; want to save source ptr clr di ; es:di -> output buffer call UncompactPackBitsFar ; compact a single scan line pop si ; finished compaction. Write out the buffer. mov di, newBMblock mov bx, newBMfile push si, bp mov bp, es clr si mov cx, 1 ; just one scan line call HugeArrayAppend pop si, bp pop cx loop scanLoop ; release the last block of the source array and scratch buff call HugeArrayUnlock ; release the last block mov bx, scratchBlock call MemFree ; return the correct information about the new BM mov dx, newBMfile ; return file and mov cx, newBMblock ; block handle .leave ret GrUncompactBitmap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AllocBitmapInitDeviceInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Initialize the VideoDriverInfo structure after having allocated a bitmap. CALLED BY: GrCreateBitmap, GrCompactBitmap PASS: ES:DI = CBitmap DX = Bytes / scanline RETURN: Nothing DESTROYED: AX, BX, DI, SI, DS PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Don 8/ 5/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AllocBitmapInitDeviceInfo proc near .enter mov si, es:[di].CB_devInfo ; offset to device info add di, si ; es:di -> device info LoadVarSeg ds, ax ; ds -> idata mov ax, ds:[memVidStrategy].offset ; get strat rout addr mov bx, ds:[memVidStrategy].segment ; get strat rout addr mov es:[di].DIS_strategy.offset, ax ; save strategy rout mov es:[di].DIS_strategy.segment, bx mov es:[di].DIS_driverAttributes, mask DA_CHARACTER mov es:[di].DIS_driverType, DRIVER_TYPE_VIDEO mov es:[di].VDI_tech, DT_MEMORY mov es:[di].VDI_verMaj, VIDMEM_VERSION_MAJOR mov es:[di].VDI_verMin, VIDMEM_VERSION_MINOR mov ax, es:[EB_bm].CB_simple.B_height ; get bitmap height mov es:[di].VDI_pageH, ax ; store as device size mov ax, es:[EB_bm].CB_simple.B_width mov es:[di].VDI_pageW, ax mov ax, 72 ; assume default resolution mov es:[di].VDI_vRes, ax mov es:[di].VDI_hRes, ax mov es:[di].VDI_bpScan, dx mov al, es:[EB_bm].CB_simple.B_type and ax, mask BMT_FORMAT ; get format bits mov es:[di].VDI_bmFormat, al mov_tr bx, ax ; get into addressing register mov al, cs:[nColorTable][bx] ; get total #colors mov es:[di].VDI_nColors, al shl bx, 1 ; access a word table mov bx, cs:[bitsAndPlanes][bx] mov {word} es:[di].VDI_nPlanes, bx mov es:[di].VDI_wColTab, 24 ; palette is 24-bit/pixel .leave ret AllocBitmapInitDeviceInfo endp GraphicsAllocBitmap ends
; REpsych ; domas, @xoreaxeaxeax ; This file serves as the program effect. A more sophisticated approach would ; modify the CFG of existing code; for now, we generate new code to create the ; CFG, and simply connect it to existing code (this). extern printf code: push ebp mov ebp, esp push pusheen call printf add esp, 4 leave ret pusheen: db 0x20,0x20,0x20,0xe2,0x96,0x90,0xe2,0x96,0x80,0xe2,0x96,0x84,0x20,0x20,0x20,0x20 db 0x20,0x20,0xe2,0x96,0x84,0xe2,0x96,0x80,0xe2,0x96,0x8c,0x20,0x20,0x20,0xe2,0x96 db 0x84,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x84 db 0xe2,0x96,0x84,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20 db 0x0a,0x20,0x20,0x20,0xe2,0x96,0x8c,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x80 db 0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x80,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90,0xe2,0x96,0x84,0xe2,0x96,0x80,0xe2,0x96 db 0x80,0xe2,0x96,0x92,0xe2,0x96,0x88,0xe2,0x96,0x88,0xe2,0x96,0x92,0xe2,0x96,0x88 db 0xe2,0x96,0x88,0xe2,0x96,0x92,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x84,0x20 db 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0a,0x20,0x20,0xe2,0x96,0x90,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x80,0xe2,0x96,0x84 db 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0a,0x20,0x20,0xe2,0x96,0x8c,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x84,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x80,0xe2,0x96,0x84,0x20,0x20,0x20,0x20,0x20,0x20,0x0a,0xe2,0x96,0x80,0xe2 db 0x96,0x88,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x88,0xe2,0x96,0x8c,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x88,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90 db 0xe2,0x96,0x88,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x80,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x8c,0x20 db 0x20,0x20,0x20,0x20,0x0a,0xe2,0x96,0x80,0xe2,0x96,0x8c,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x80,0xe2,0x96,0x92 db 0xe2,0x96,0x80,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90,0x20,0x20,0x20,0xe2,0x96,0x84,0xe2,0x96 db 0x84,0x0a,0xe2,0x96,0x90,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x8c,0xe2,0x96,0x84,0xe2,0x96,0x88,0xe2,0x96 db 0x92,0xe2,0x96,0x88,0x0a,0xe2,0x96,0x90,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90,0xe2,0x96,0x92,0xe2,0x96 db 0x88,0xe2,0x96,0x80,0x20,0x0a,0xe2,0x96,0x90,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90,0xe2,0x96,0x80,0x20 db 0x20,0x20,0x0a,0xe2,0x96,0x90,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x8c,0x20,0x20,0x20,0x20,0x0a,0x20,0xe2 db 0x96,0x8c,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90,0x20 db 0x20,0x20,0x20,0x20,0x0a,0x20,0xe2,0x96,0x90,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x8c,0x20,0x20,0x20,0x20,0x20,0x0a,0x20,0x20,0xe2,0x96 db 0x8c,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x90,0x20,0x20,0x20,0x20,0x20,0x20,0x0a,0x20 db 0x20,0xe2,0x96,0x90,0xe2,0x96,0x84,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96 db 0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92 db 0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x92,0xe2 db 0x96,0x92,0xe2,0x96,0x92,0xe2,0x96,0x84,0xe2,0x96,0x8c,0x20,0x20,0x20,0x20,0x20 db 0x20,0x0a,0x20,0x20,0x20,0x20,0xe2,0x96,0x80,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2 db 0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x84,0xe2,0x96 db 0x84,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80 db 0xe2,0x96,0x80,0xe2,0x96,0x84,0xe2,0x96,0x84,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2 db 0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x80,0xe2,0x96,0x84,0xe2,0x96 db 0x84,0xe2,0x96,0x80,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x0a,0x20,0x0a,0x00
; A054113: T(2n,n), array T as in A054110. ; 1,5,17,57,197,701,2549,9413,35153,132393,501905,1912769,7321081,28122281,108355481,418590521,1620751301,6287963741,24438234341,95128761941,370821819581,1447337568461,5655535495901,22122396951101 lpb $0 mov $2,$0 sub $0,1 add $2,$0 bin $2,$0 add $1,$2 lpe mov $0,$1 mul $0,4 add $0,1
; max number .386 .model flat,stdcall .stack 4096 INCLUDE Irvine32.inc ExitProcess proto,dwExitCode:dword .data num1 DWORD 2367 num2 DWORD 4792 .code main proc mov eax, [num1] call WriteBin mov al, 10 call WriteChar mov eax, [num2] call WriteBin mov al, 10 call WriteChar mov ebx, [num1] mov eax, [num2] xor eax, ebx call WriteBin mov esi, eax mov al, 10 call WriteChar call displayBits displayBits PROC mov ecx, 32 mov ebx, 1 shl ebx, 31 l1: mov edi, esi and edi, ebx jnz write1 jmp write0 write1: mov al, '1' call WriteChar jmp return write0: mov al, '0' call WriteChar return: shl esi, 1 loop l1 displayBits ENDP invoke ExitProcess,0 main endp end main
; A035492: Position of card 1 after n-th shuffle in Guy's shuffling problem (A035485). ; Submitted by Jon Maiga ; 1,2,4,1,2,4,8,1,2,4,8,16,7,14,28,25,17,34,31,23,5,10,20,40,31,11,22,44,31,3,6,12,24,48,27,54,35,70,63,47,13,26,52,17,34,68,43,86,75,51,1,2,4,8,16,32,64,13,26,52,104,85,45,90,51,102,71,7,14,28,56,112,79,11,22,44,88,21,42,84,7,14,28,56,112,53,106,37,74,148,115,47,94,1,2,4,8,16,32,64 mov $1,1 mov $2,1 lpb $0 sub $0,1 add $2,2 mod $1,$2 mul $1,2 add $1,1 lpe mov $0,$1 div $0,2 add $0,1
/* * PKCS#11 Mechanism * (C) 2016 Daniel Neus, Sirrix AG * (C) 2016 Philipp Weber, Sirrix AG * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/p11_mechanism.h> #include <botan/scan_name.h> #include <botan/parsing.h> #include <botan/emsa.h> #include <tuple> namespace Botan { namespace PKCS11 { namespace { using PSS_Params = std::tuple<size_t, MechanismType, MGF>; // maps a PSS mechanism type to the number of bytes used for the salt, the mechanism type of the underlying hash algorithm and the MGF static const std::map<MechanismType, PSS_Params> PssOptions = { { MechanismType::RsaPkcsPss, PSS_Params(0, MechanismType::Sha1, MGF::Mgf1Sha1) }, { MechanismType::Sha1RsaPkcsPss, PSS_Params(20, MechanismType::Sha1, MGF::Mgf1Sha1) }, { MechanismType::Sha224RsaPkcsPss, PSS_Params(28, MechanismType::Sha224, MGF::Mgf1Sha224) }, { MechanismType::Sha256RsaPkcsPss, PSS_Params(32, MechanismType::Sha256, MGF::Mgf1Sha256) }, { MechanismType::Sha384RsaPkcsPss, PSS_Params(48, MechanismType::Sha384, MGF::Mgf1Sha384) }, { MechanismType::Sha512RsaPkcsPss, PSS_Params(64, MechanismType::Sha512, MGF::Mgf1Sha512) } }; struct MechanismData { explicit MechanismData(MechanismType _type) : type(_type) {} MechanismData(MechanismData const&) = default; MechanismData& operator=(MechanismData const&) = default; virtual ~MechanismData() = default; // the mechanism to perform MechanismType type; }; struct RSA_SignMechanism final : public MechanismData { explicit RSA_SignMechanism(MechanismType _type) : MechanismData(_type), hash(static_cast<MechanismType>(0)), mgf(static_cast<MGF>(0)), salt_size(0) { auto pss_option = PssOptions.find(type); if(pss_option != PssOptions.end()) { hash = std::get<1>(pss_option->second); mgf = std::get<2>(pss_option->second); salt_size = std::get<0>(pss_option->second); } } // hash algorithm used in the PSS encoding; if the signature mechanism does not include message hashing, // then this value must be the mechanism used by the application to generate the message hash; // if the signature mechanism includes hashing, then this value must match the hash algorithm indicated by the signature mechanism MechanismType hash; // mask generation function to use on the encoded block MGF mgf; // length, in bytes, of the salt value used in the PSS encoding; typical values are the length of the message hash and zero size_t salt_size; }; // note: when updating this map, update the documentation for `MechanismWrapper::create_rsa_sign_mechanism` static std::map<std::string, RSA_SignMechanism> SignMechanisms = { { "Raw", RSA_SignMechanism(MechanismType::RsaX509) }, { "EMSA2(Raw)", RSA_SignMechanism(MechanismType::RsaX931) }, { "EMSA2(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaX931) }, // RSASSA PKCS#1 v1.5 { "EMSA3(Raw)", RSA_SignMechanism(MechanismType::RsaPkcs) }, { "EMSA3(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcs) }, { "EMSA3(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcs) }, { "EMSA3(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcs) }, { "EMSA3(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcs) }, { "EMSA3(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcs) }, { "EMSA_PKCS1(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcs) }, { "EMSA_PKCS1(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcs) }, { "EMSA_PKCS1(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcs) }, { "EMSA_PKCS1(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcs) }, { "EMSA_PKCS1(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcs) }, // RSASSA PKCS#1 PSS { "EMSA4(Raw)", RSA_SignMechanism(MechanismType::RsaPkcsPss) }, { "EMSA4(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcsPss) }, { "EMSA4(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcsPss) }, { "EMSA4(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcsPss) }, { "EMSA4(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcsPss) }, { "EMSA4(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcsPss) }, { "PSSR(SHA-256,MGF1,32)", RSA_SignMechanism(MechanismType::Sha256RsaPkcsPss) }, { "PSSR(SHA-384,MGF1,48)", RSA_SignMechanism(MechanismType::Sha384RsaPkcsPss) }, { "PSSR(SHA-512,MGF1,64)", RSA_SignMechanism(MechanismType::Sha512RsaPkcsPss) }, { "ISO9796", RSA_SignMechanism(MechanismType::Rsa9796) } }; struct RSA_CryptMechanism final : public MechanismData { RSA_CryptMechanism(MechanismType _type, size_t _padding_size, MechanismType _hash, MGF _mgf) : MechanismData(_type), hash(_hash), mgf(_mgf), padding_size(_padding_size) {} RSA_CryptMechanism(MechanismType _type, size_t _padding_size) : RSA_CryptMechanism(_type, _padding_size, static_cast<MechanismType>(0), static_cast<MGF>(0)) {} // mechanism ID of the message digest algorithm used to calculate the digest of the encoding parameter MechanismType hash; // mask generation function to use on the encoded block MGF mgf; // number of bytes required for the padding size_t padding_size; }; // note: when updating this map, update the documentation for `MechanismWrapper::create_rsa_crypt_mechanism` static const std::map<std::string, RSA_CryptMechanism> CryptMechanisms = { { "Raw", RSA_CryptMechanism(MechanismType::RsaX509, 0) }, { "EME-PKCS1-v1_5", RSA_CryptMechanism(MechanismType::RsaPkcs, 11) }, { "OAEP(SHA-1)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 20, MechanismType::Sha1, MGF::Mgf1Sha1) }, { "OAEP(SHA-224)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 28, MechanismType::Sha224, MGF::Mgf1Sha224) }, { "OAEP(SHA-256)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 32, MechanismType::Sha256, MGF::Mgf1Sha256) }, { "OAEP(SHA-384)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 48, MechanismType::Sha384, MGF::Mgf1Sha384) }, { "OAEP(SHA-512)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 64, MechanismType::Sha512, MGF::Mgf1Sha512) } }; // note: when updating this map, update the documentation for `MechanismWrapper::create_ecdsa_mechanism` static std::map<std::string, MechanismType> EcdsaHash = { { "Raw", MechanismType::Ecdsa }, { "SHA-160", MechanismType::EcdsaSha1 }, { "SHA-224", MechanismType::EcdsaSha224 }, { "SHA-256", MechanismType::EcdsaSha256 }, { "SHA-384", MechanismType::EcdsaSha384 }, { "SHA-512", MechanismType::EcdsaSha512 } }; // note: when updating this map, update the documentation for `MechanismWrapper::create_ecdh_mechanism` static std::map<std::string, KeyDerivation> EcdhHash = { { "Raw", KeyDerivation::Null }, { "SHA-160", KeyDerivation::Sha1Kdf }, { "SHA-224", KeyDerivation::Sha224Kdf }, { "SHA-256", KeyDerivation::Sha256Kdf }, { "SHA-384", KeyDerivation::Sha384Kdf }, { "SHA-512", KeyDerivation::Sha512Kdf } }; } MechanismWrapper::MechanismWrapper(MechanismType mechanism_type) : m_mechanism( { static_cast<CK_MECHANISM_TYPE>(mechanism_type), nullptr, 0 }), m_parameters(nullptr) {} MechanismWrapper MechanismWrapper::create_rsa_crypt_mechanism(const std::string& padding) { auto mechanism_info_it = CryptMechanisms.find(padding); if(mechanism_info_it == CryptMechanisms.end()) { // at this point it would be possible to support additional configurations that are not predefined above by parsing `padding` throw Lookup_Error("PKCS#11 RSA encrypt/decrypt does not support EME " + padding); } RSA_CryptMechanism mechanism_info = mechanism_info_it->second; MechanismWrapper mech(mechanism_info.type); if(mechanism_info.type == MechanismType::RsaPkcsOaep) { mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->oaep_params.hashAlg = static_cast<CK_MECHANISM_TYPE>(mechanism_info.hash); mech.m_parameters->oaep_params.mgf = static_cast<CK_RSA_PKCS_MGF_TYPE>(mechanism_info.mgf); mech.m_parameters->oaep_params.source = CKZ_DATA_SPECIFIED; mech.m_parameters->oaep_params.pSourceData = nullptr; mech.m_parameters->oaep_params.ulSourceDataLen = 0; mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(RsaPkcsOaepParams); } mech.m_padding_size = mechanism_info.padding_size; return mech; } MechanismWrapper MechanismWrapper::create_rsa_sign_mechanism(const std::string& padding) { auto mechanism_info_it = SignMechanisms.find(padding); if(mechanism_info_it == SignMechanisms.end()) { // at this point it would be possible to support additional configurations that are not predefined above by parsing `padding` throw Lookup_Error("PKCS#11 RSA sign/verify does not support EMSA " + padding); } RSA_SignMechanism mechanism_info = mechanism_info_it->second; MechanismWrapper mech(mechanism_info.type); if(PssOptions.find(mechanism_info.type) != PssOptions.end()) { mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->pss_params.hashAlg = static_cast<CK_MECHANISM_TYPE>(mechanism_info.hash); mech.m_parameters->pss_params.mgf = static_cast<CK_RSA_PKCS_MGF_TYPE>(mechanism_info.mgf); mech.m_parameters->pss_params.sLen = mechanism_info.salt_size; mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(RsaPkcsPssParams); } return mech; } MechanismWrapper MechanismWrapper::create_ecdsa_mechanism(const std::string& hash) { std::string hash_name = hash; if(hash_name != "Raw") { hash_name = hash_for_emsa(hash); } auto mechanism_type = EcdsaHash.find(hash_name); if(mechanism_type == EcdsaHash.end()) { throw Lookup_Error("PKCS#11 ECDSA sign/verify does not support " + hash); } return MechanismWrapper(mechanism_type->second); } MechanismWrapper MechanismWrapper::create_ecdh_mechanism(const std::string& params) { std::vector<std::string> param_parts = split_on(params, ','); if(param_parts.empty() || param_parts.size() > 2) throw Invalid_Argument("PKCS #11 ECDH key derivation bad params " + params); const bool use_cofactor = (param_parts[0] == "Cofactor") || (param_parts.size() == 2 && param_parts[1] == "Cofactor"); std::string kdf_name = (param_parts[0] == "Cofactor" ? param_parts[1] : param_parts[0]); std::string hash = kdf_name; if(kdf_name != "Raw") { SCAN_Name kdf_hash(kdf_name); if(kdf_hash.arg_count() > 0) { hash = kdf_hash.arg(0); } } auto kdf = EcdhHash.find(hash); if(kdf == EcdhHash.end()) { throw Lookup_Error("PKCS#11 ECDH key derivation does not support KDF " + kdf_name); } MechanismWrapper mech(use_cofactor ? MechanismType::Ecdh1CofactorDerive : MechanismType::Ecdh1Derive); mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->ecdh_params.kdf = static_cast<CK_EC_KDF_TYPE>(kdf->second); mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(Ecdh1DeriveParams); return mech; } } }
BITS 32 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS=FLAG_AF|FLAG_OF ;TEST_FILE_META_END ; Shr32RI mov eax, 0x4096 ;TEST_BEGIN_RECORDING shr eax, 0x6 ;TEST_END_RECORDING
//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===// // // 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 // //===----------------------------------------------------------------------===// // // This provides Objective-C code generation targeting the Apple runtime. // //===----------------------------------------------------------------------===// #include "CGBlocks.h" #include "CGCleanup.h" #include "CGObjCRuntime.h" #include "CGRecordLayout.h" #include "CodeGenFunction.h" #include "CodeGenModule.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/StmtObjC.h" #include "clang/Basic/CodeGenOptions.h" #include "clang/Basic/LangOptions.h" #include "clang/CodeGen/CGFunctionInfo.h" #include "clang/CodeGen/ConstantInitBuilder.h" #include "llvm/ADT/CachedHashString.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/ScopedPrinter.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> using namespace clang; using namespace CodeGen; namespace { // FIXME: We should find a nicer way to make the labels for metadata, string // concatenation is lame. class ObjCCommonTypesHelper { protected: llvm::LLVMContext &VMContext; private: // The types of these functions don't really matter because we // should always bitcast before calling them. /// id objc_msgSend (id, SEL, ...) /// /// The default messenger, used for sends whose ABI is unchanged from /// the all-integer/pointer case. llvm::FunctionCallee getMessageSendFn() const { // Add the non-lazy-bind attribute, since objc_msgSend is likely to // be called a lot. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend", llvm::AttributeList::get(CGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::NonLazyBind)); } /// void objc_msgSend_stret (id, SEL, ...) /// /// The messenger used when the return value is an aggregate returned /// by indirect reference in the first argument, and therefore the /// self and selector parameters are shifted over by one. llvm::FunctionCallee getMessageSendStretFn() const { llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, params, true), "objc_msgSend_stret"); } /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...) /// /// The messenger used when the return value is returned on the x87 /// floating-point stack; without a special entrypoint, the nil case /// would be unbalanced. llvm::FunctionCallee getMessageSendFpretFn() const { llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy, params, true), "objc_msgSend_fpret"); } /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...) /// /// The messenger used when the return value is returned in two values on the /// x87 floating point stack; without a special entrypoint, the nil case /// would be unbalanced. Only used on 64-bit X86. llvm::FunctionCallee getMessageSendFp2retFn() const { llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext); llvm::Type *resultType = llvm::StructType::get(longDoubleType, longDoubleType); return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType, params, true), "objc_msgSend_fp2ret"); } /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...) /// /// The messenger used for super calls, which have different dispatch /// semantics. The class passed is the superclass of the current /// class. llvm::FunctionCallee getMessageSendSuperFn() const { llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSendSuper"); } /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...) /// /// A slightly different messenger used for super calls. The class /// passed is the current class. llvm::FunctionCallee getMessageSendSuperFn2() const { llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSendSuper2"); } /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super, /// SEL op, ...) /// /// The messenger used for super calls which return an aggregate indirectly. llvm::FunctionCallee getMessageSendSuperStretFn() const { llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(CGM.VoidTy, params, true), "objc_msgSendSuper_stret"); } /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super, /// SEL op, ...) /// /// objc_msgSendSuper_stret with the super2 semantics. llvm::FunctionCallee getMessageSendSuperStretFn2() const { llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(CGM.VoidTy, params, true), "objc_msgSendSuper2_stret"); } llvm::FunctionCallee getMessageSendSuperFpretFn() const { // There is no objc_msgSendSuper_fpret? How can that work? return getMessageSendSuperFn(); } llvm::FunctionCallee getMessageSendSuperFpretFn2() const { // There is no objc_msgSendSuper_fpret? How can that work? return getMessageSendSuperFn2(); } protected: CodeGen::CodeGenModule &CGM; public: llvm::IntegerType *ShortTy, *IntTy, *LongTy; llvm::PointerType *Int8PtrTy, *Int8PtrPtrTy; llvm::Type *IvarOffsetVarTy; /// ObjectPtrTy - LLVM type for object handles (typeof(id)) llvm::PointerType *ObjectPtrTy; /// PtrObjectPtrTy - LLVM type for id * llvm::PointerType *PtrObjectPtrTy; /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL)) llvm::PointerType *SelectorPtrTy; private: /// ProtocolPtrTy - LLVM type for external protocol handles /// (typeof(Protocol)) llvm::Type *ExternalProtocolPtrTy; public: llvm::Type *getExternalProtocolPtrTy() { if (!ExternalProtocolPtrTy) { // FIXME: It would be nice to unify this with the opaque type, so that the // IR comes out a bit cleaner. CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType()); ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T); } return ExternalProtocolPtrTy; } // SuperCTy - clang type for struct objc_super. QualType SuperCTy; // SuperPtrCTy - clang type for struct objc_super *. QualType SuperPtrCTy; /// SuperTy - LLVM type for struct objc_super. llvm::StructType *SuperTy; /// SuperPtrTy - LLVM type for struct objc_super *. llvm::PointerType *SuperPtrTy; /// PropertyTy - LLVM type for struct objc_property (struct _prop_t /// in GCC parlance). llvm::StructType *PropertyTy; /// PropertyListTy - LLVM type for struct objc_property_list /// (_prop_list_t in GCC parlance). llvm::StructType *PropertyListTy; /// PropertyListPtrTy - LLVM type for struct objc_property_list*. llvm::PointerType *PropertyListPtrTy; // MethodTy - LLVM type for struct objc_method. llvm::StructType *MethodTy; /// CacheTy - LLVM type for struct objc_cache. llvm::Type *CacheTy; /// CachePtrTy - LLVM type for struct objc_cache *. llvm::PointerType *CachePtrTy; llvm::FunctionCallee getGetPropertyFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // id objc_getProperty (id, SEL, ptrdiff_t, bool) CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); CanQualType Params[] = { IdType, SelType, Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy}; llvm::FunctionType *FTy = Types.GetFunctionType( Types.arrangeBuiltinFunctionDeclaration(IdType, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_getProperty"); } llvm::FunctionCallee getSetPropertyFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool) CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); CanQualType Params[] = { IdType, SelType, Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), IdType, Ctx.BoolTy, Ctx.BoolTy}; llvm::FunctionType *FTy = Types.GetFunctionType( Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_setProperty"); } llvm::FunctionCallee getOptimizedSetPropertyFn(bool atomic, bool copy) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // void objc_setProperty_atomic(id self, SEL _cmd, // id newValue, ptrdiff_t offset); // void objc_setProperty_nonatomic(id self, SEL _cmd, // id newValue, ptrdiff_t offset); // void objc_setProperty_atomic_copy(id self, SEL _cmd, // id newValue, ptrdiff_t offset); // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, // id newValue, ptrdiff_t offset); SmallVector<CanQualType,4> Params; CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType()); CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType()); Params.push_back(IdType); Params.push_back(SelType); Params.push_back(IdType); Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified()); llvm::FunctionType *FTy = Types.GetFunctionType( Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); const char *name; if (atomic && copy) name = "objc_setProperty_atomic_copy"; else if (atomic && !copy) name = "objc_setProperty_atomic"; else if (!atomic && copy) name = "objc_setProperty_nonatomic_copy"; else name = "objc_setProperty_nonatomic"; return CGM.CreateRuntimeFunction(FTy, name); } llvm::FunctionCallee getCopyStructFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // void objc_copyStruct (void *, const void *, size_t, bool, bool) SmallVector<CanQualType,5> Params; Params.push_back(Ctx.VoidPtrTy); Params.push_back(Ctx.VoidPtrTy); Params.push_back(Ctx.getSizeType()); Params.push_back(Ctx.BoolTy); Params.push_back(Ctx.BoolTy); llvm::FunctionType *FTy = Types.GetFunctionType( Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct"); } /// This routine declares and returns address of: /// void objc_copyCppObjectAtomic( /// void *dest, const void *src, /// void (*copyHelper) (void *dest, const void *source)); llvm::FunctionCallee getCppAtomicObjectFunction() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper); SmallVector<CanQualType,3> Params; Params.push_back(Ctx.VoidPtrTy); Params.push_back(Ctx.VoidPtrTy); Params.push_back(Ctx.VoidPtrTy); llvm::FunctionType *FTy = Types.GetFunctionType( Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic"); } llvm::FunctionCallee getEnumerationMutationFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // void objc_enumerationMutation (id) SmallVector<CanQualType,1> Params; Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType())); llvm::FunctionType *FTy = Types.GetFunctionType( Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params)); return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation"); } llvm::FunctionCallee getLookUpClassFn() { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // Class objc_lookUpClass (const char *) SmallVector<CanQualType,1> Params; Params.push_back( Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst()))); llvm::FunctionType *FTy = Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration( Ctx.getCanonicalType(Ctx.getObjCClassType()), Params)); return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass"); } /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function. llvm::FunctionCallee getGcReadWeakFn() { // id objc_read_weak (id *) llvm::Type *args[] = { ObjectPtrTy->getPointerTo() }; llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_read_weak"); } /// GcAssignWeakFn -- LLVM objc_assign_weak function. llvm::FunctionCallee getGcAssignWeakFn() { // id objc_assign_weak (id, id *) llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak"); } /// GcAssignGlobalFn -- LLVM objc_assign_global function. llvm::FunctionCallee getGcAssignGlobalFn() { // id objc_assign_global(id, id *) llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_global"); } /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function. llvm::FunctionCallee getGcAssignThreadLocalFn() { // id objc_assign_threadlocal(id src, id * dest) llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal"); } /// GcAssignIvarFn -- LLVM objc_assign_ivar function. llvm::FunctionCallee getGcAssignIvarFn() { // id objc_assign_ivar(id, id *, ptrdiff_t) llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(), CGM.PtrDiffTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar"); } /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function. llvm::FunctionCallee GcMemmoveCollectableFn() { // void *objc_memmove_collectable(void *dst, const void *src, size_t size) llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable"); } /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function. llvm::FunctionCallee getGcAssignStrongCastFn() { // id objc_assign_strongCast(id, id *) llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() }; llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast"); } /// ExceptionThrowFn - LLVM objc_exception_throw function. llvm::FunctionCallee getExceptionThrowFn() { // void objc_exception_throw(id) llvm::Type *args[] = { ObjectPtrTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw"); } /// ExceptionRethrowFn - LLVM objc_exception_rethrow function. llvm::FunctionCallee getExceptionRethrowFn() { // void objc_exception_rethrow(void) llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false); return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow"); } /// SyncEnterFn - LLVM object_sync_enter function. llvm::FunctionCallee getSyncEnterFn() { // int objc_sync_enter (id) llvm::Type *args[] = { ObjectPtrTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.IntTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter"); } /// SyncExitFn - LLVM object_sync_exit function. llvm::FunctionCallee getSyncExitFn() { // int objc_sync_exit (id) llvm::Type *args[] = { ObjectPtrTy }; llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.IntTy, args, false); return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit"); } llvm::FunctionCallee getSendFn(bool IsSuper) const { return IsSuper ? getMessageSendSuperFn() : getMessageSendFn(); } llvm::FunctionCallee getSendFn2(bool IsSuper) const { return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn(); } llvm::FunctionCallee getSendStretFn(bool IsSuper) const { return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn(); } llvm::FunctionCallee getSendStretFn2(bool IsSuper) const { return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn(); } llvm::FunctionCallee getSendFpretFn(bool IsSuper) const { return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn(); } llvm::FunctionCallee getSendFpretFn2(bool IsSuper) const { return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn(); } llvm::FunctionCallee getSendFp2retFn(bool IsSuper) const { return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn(); } llvm::FunctionCallee getSendFp2RetFn2(bool IsSuper) const { return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn(); } ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm); }; /// ObjCTypesHelper - Helper class that encapsulates lazy /// construction of varies types used during ObjC generation. class ObjCTypesHelper : public ObjCCommonTypesHelper { public: /// SymtabTy - LLVM type for struct objc_symtab. llvm::StructType *SymtabTy; /// SymtabPtrTy - LLVM type for struct objc_symtab *. llvm::PointerType *SymtabPtrTy; /// ModuleTy - LLVM type for struct objc_module. llvm::StructType *ModuleTy; /// ProtocolTy - LLVM type for struct objc_protocol. llvm::StructType *ProtocolTy; /// ProtocolPtrTy - LLVM type for struct objc_protocol *. llvm::PointerType *ProtocolPtrTy; /// ProtocolExtensionTy - LLVM type for struct /// objc_protocol_extension. llvm::StructType *ProtocolExtensionTy; /// ProtocolExtensionTy - LLVM type for struct /// objc_protocol_extension *. llvm::PointerType *ProtocolExtensionPtrTy; /// MethodDescriptionTy - LLVM type for struct /// objc_method_description. llvm::StructType *MethodDescriptionTy; /// MethodDescriptionListTy - LLVM type for struct /// objc_method_description_list. llvm::StructType *MethodDescriptionListTy; /// MethodDescriptionListPtrTy - LLVM type for struct /// objc_method_description_list *. llvm::PointerType *MethodDescriptionListPtrTy; /// ProtocolListTy - LLVM type for struct objc_property_list. llvm::StructType *ProtocolListTy; /// ProtocolListPtrTy - LLVM type for struct objc_property_list*. llvm::PointerType *ProtocolListPtrTy; /// CategoryTy - LLVM type for struct objc_category. llvm::StructType *CategoryTy; /// ClassTy - LLVM type for struct objc_class. llvm::StructType *ClassTy; /// ClassPtrTy - LLVM type for struct objc_class *. llvm::PointerType *ClassPtrTy; /// ClassExtensionTy - LLVM type for struct objc_class_ext. llvm::StructType *ClassExtensionTy; /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *. llvm::PointerType *ClassExtensionPtrTy; // IvarTy - LLVM type for struct objc_ivar. llvm::StructType *IvarTy; /// IvarListTy - LLVM type for struct objc_ivar_list. llvm::StructType *IvarListTy; /// IvarListPtrTy - LLVM type for struct objc_ivar_list *. llvm::PointerType *IvarListPtrTy; /// MethodListTy - LLVM type for struct objc_method_list. llvm::StructType *MethodListTy; /// MethodListPtrTy - LLVM type for struct objc_method_list *. llvm::PointerType *MethodListPtrTy; /// ExceptionDataTy - LLVM type for struct _objc_exception_data. llvm::StructType *ExceptionDataTy; /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function. llvm::FunctionCallee getExceptionTryEnterFn() { llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(CGM.VoidTy, params, false), "objc_exception_try_enter"); } /// ExceptionTryExitFn - LLVM objc_exception_try_exit function. llvm::FunctionCallee getExceptionTryExitFn() { llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(CGM.VoidTy, params, false), "objc_exception_try_exit"); } /// ExceptionExtractFn - LLVM objc_exception_extract function. llvm::FunctionCallee getExceptionExtractFn() { llvm::Type *params[] = { ExceptionDataTy->getPointerTo() }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, false), "objc_exception_extract"); } /// ExceptionMatchFn - LLVM objc_exception_match function. llvm::FunctionCallee getExceptionMatchFn() { llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(CGM.Int32Ty, params, false), "objc_exception_match"); } /// SetJmpFn - LLVM _setjmp function. llvm::FunctionCallee getSetJmpFn() { // This is specifically the prototype for x86. llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() }; return CGM.CreateRuntimeFunction( llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp", llvm::AttributeList::get(CGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, llvm::Attribute::NonLazyBind)); } public: ObjCTypesHelper(CodeGen::CodeGenModule &cgm); }; /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's /// modern abi class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper { public: // MethodListnfABITy - LLVM for struct _method_list_t llvm::StructType *MethodListnfABITy; // MethodListnfABIPtrTy - LLVM for struct _method_list_t* llvm::PointerType *MethodListnfABIPtrTy; // ProtocolnfABITy = LLVM for struct _protocol_t llvm::StructType *ProtocolnfABITy; // ProtocolnfABIPtrTy = LLVM for struct _protocol_t* llvm::PointerType *ProtocolnfABIPtrTy; // ProtocolListnfABITy - LLVM for struct _objc_protocol_list llvm::StructType *ProtocolListnfABITy; // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list* llvm::PointerType *ProtocolListnfABIPtrTy; // ClassnfABITy - LLVM for struct _class_t llvm::StructType *ClassnfABITy; // ClassnfABIPtrTy - LLVM for struct _class_t* llvm::PointerType *ClassnfABIPtrTy; // IvarnfABITy - LLVM for struct _ivar_t llvm::StructType *IvarnfABITy; // IvarListnfABITy - LLVM for struct _ivar_list_t llvm::StructType *IvarListnfABITy; // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t* llvm::PointerType *IvarListnfABIPtrTy; // ClassRonfABITy - LLVM for struct _class_ro_t llvm::StructType *ClassRonfABITy; // ImpnfABITy - LLVM for id (*)(id, SEL, ...) llvm::PointerType *ImpnfABITy; // CategorynfABITy - LLVM for struct _category_t llvm::StructType *CategorynfABITy; // New types for nonfragile abi messaging. // MessageRefTy - LLVM for: // struct _message_ref_t { // IMP messenger; // SEL name; // }; llvm::StructType *MessageRefTy; // MessageRefCTy - clang type for struct _message_ref_t QualType MessageRefCTy; // MessageRefPtrTy - LLVM for struct _message_ref_t* llvm::Type *MessageRefPtrTy; // MessageRefCPtrTy - clang type for struct _message_ref_t* QualType MessageRefCPtrTy; // SuperMessageRefTy - LLVM for: // struct _super_message_ref_t { // SUPER_IMP messenger; // SEL name; // }; llvm::StructType *SuperMessageRefTy; // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* llvm::PointerType *SuperMessageRefPtrTy; llvm::FunctionCallee getMessageSendFixupFn() { // id objc_msgSend_fixup(id, struct message_ref_t*, ...) llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend_fixup"); } llvm::FunctionCallee getMessageSendFpretFixupFn() { // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...) llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend_fpret_fixup"); } llvm::FunctionCallee getMessageSendStretFixupFn() { // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...) llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend_stret_fixup"); } llvm::FunctionCallee getMessageSendSuper2FixupFn() { // id objc_msgSendSuper2_fixup (struct objc_super *, // struct _super_message_ref_t*, ...) llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSendSuper2_fixup"); } llvm::FunctionCallee getMessageSendSuper2StretFixupFn() { // id objc_msgSendSuper2_stret_fixup(struct objc_super *, // struct _super_message_ref_t*, ...) llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSendSuper2_stret_fixup"); } llvm::FunctionCallee getObjCEndCatchFn() { return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false), "objc_end_catch"); } llvm::FunctionCallee getObjCBeginCatchFn() { llvm::Type *params[] = { Int8PtrTy }; return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy, params, false), "objc_begin_catch"); } /// Class objc_loadClassref (void *) /// /// Loads from a classref. For Objective-C stub classes, this invokes the /// initialization callback stored inside the stub. For all other classes /// this simply dereferences the pointer. llvm::FunctionCallee getLoadClassrefFn() const { // Add the non-lazy-bind attribute, since objc_loadClassref is likely to // be called a lot. // // Also it is safe to make it readnone, since we never load or store the // classref except by calling this function. llvm::Type *params[] = { Int8PtrPtrTy }; llvm::FunctionCallee F = CGM.CreateRuntimeFunction( llvm::FunctionType::get(ClassnfABIPtrTy, params, false), "objc_loadClassref", llvm::AttributeList::get(CGM.getLLVMContext(), llvm::AttributeList::FunctionIndex, {llvm::Attribute::NonLazyBind, llvm::Attribute::ReadNone, llvm::Attribute::NoUnwind})); if (!CGM.getTriple().isOSBinFormatCOFF()) cast<llvm::Function>(F.getCallee())->setLinkage( llvm::Function::ExternalWeakLinkage); return F; } llvm::StructType *EHTypeTy; llvm::Type *EHTypePtrTy; ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm); }; enum class ObjCLabelType { ClassName, MethodVarName, MethodVarType, PropertyName, }; class CGObjCCommonMac : public CodeGen::CGObjCRuntime { public: class SKIP_SCAN { public: unsigned skip; unsigned scan; SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0) : skip(_skip), scan(_scan) {} }; /// opcode for captured block variables layout 'instructions'. /// In the following descriptions, 'I' is the value of the immediate field. /// (field following the opcode). /// enum BLOCK_LAYOUT_OPCODE { /// An operator which affects how the following layout should be /// interpreted. /// I == 0: Halt interpretation and treat everything else as /// a non-pointer. Note that this instruction is equal /// to '\0'. /// I != 0: Currently unused. BLOCK_LAYOUT_OPERATOR = 0, /// The next I+1 bytes do not contain a value of object pointer type. /// Note that this can leave the stream unaligned, meaning that /// subsequent word-size instructions do not begin at a multiple of /// the pointer size. BLOCK_LAYOUT_NON_OBJECT_BYTES = 1, /// The next I+1 words do not contain a value of object pointer type. /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for /// when the required skip quantity is a multiple of the pointer size. BLOCK_LAYOUT_NON_OBJECT_WORDS = 2, /// The next I+1 words are __strong pointers to Objective-C /// objects or blocks. BLOCK_LAYOUT_STRONG = 3, /// The next I+1 words are pointers to __block variables. BLOCK_LAYOUT_BYREF = 4, /// The next I+1 words are __weak pointers to Objective-C /// objects or blocks. BLOCK_LAYOUT_WEAK = 5, /// The next I+1 words are __unsafe_unretained pointers to /// Objective-C objects or blocks. BLOCK_LAYOUT_UNRETAINED = 6 /// The next I+1 words are block or object pointers with some /// as-yet-unspecified ownership semantics. If we add more /// flavors of ownership semantics, values will be taken from /// this range. /// /// This is included so that older tools can at least continue /// processing the layout past such things. //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10, /// All other opcodes are reserved. Halt interpretation and /// treat everything else as opaque. }; class RUN_SKIP { public: enum BLOCK_LAYOUT_OPCODE opcode; CharUnits block_var_bytepos; CharUnits block_var_size; RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR, CharUnits BytePos = CharUnits::Zero(), CharUnits Size = CharUnits::Zero()) : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {} // Allow sorting based on byte pos. bool operator<(const RUN_SKIP &b) const { return block_var_bytepos < b.block_var_bytepos; } }; protected: llvm::LLVMContext &VMContext; // FIXME! May not be needing this after all. unsigned ObjCABI; // arc/mrr layout of captured block literal variables. SmallVector<RUN_SKIP, 16> RunSkipBlockVars; /// LazySymbols - Symbols to generate a lazy reference for. See /// DefinedSymbols and FinishModule(). llvm::SetVector<IdentifierInfo*> LazySymbols; /// DefinedSymbols - External symbols which are defined by this /// module. The symbols in this list and LazySymbols are used to add /// special linker symbols which ensure that Objective-C modules are /// linked properly. llvm::SetVector<IdentifierInfo*> DefinedSymbols; /// ClassNames - uniqued class names. llvm::StringMap<llvm::GlobalVariable*> ClassNames; /// MethodVarNames - uniqued method variable names. llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames; /// DefinedCategoryNames - list of category names in form Class_Category. llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames; /// MethodVarTypes - uniqued method type signatures. We have to use /// a StringMap here because have no other unique reference. llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes; /// MethodDefinitions - map of methods which have been defined in /// this translation unit. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions; /// DirectMethodDefinitions - map of direct methods which have been defined in /// this translation unit. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> DirectMethodDefinitions; /// PropertyNames - uniqued method variable names. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames; /// ClassReferences - uniqued class references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences; /// SelectorReferences - uniqued selector references. llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences; /// Protocols - Protocols for which an objc_protocol structure has /// been emitted. Forward declarations are handled by creating an /// empty structure whose initializer is filled in when/if defined. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols; /// DefinedProtocols - Protocols which have actually been /// defined. We should not need this, see FIXME in GenerateProtocol. llvm::DenseSet<IdentifierInfo*> DefinedProtocols; /// DefinedClasses - List of defined classes. SmallVector<llvm::GlobalValue*, 16> DefinedClasses; /// ImplementedClasses - List of @implemented classes. SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses; /// DefinedNonLazyClasses - List of defined "non-lazy" classes. SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses; /// DefinedCategories - List of defined categories. SmallVector<llvm::GlobalValue*, 16> DefinedCategories; /// DefinedStubCategories - List of defined categories on class stubs. SmallVector<llvm::GlobalValue*, 16> DefinedStubCategories; /// DefinedNonLazyCategories - List of defined "non-lazy" categories. SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories; /// Cached reference to the class for constant strings. This value has type /// int * but is actually an Obj-C class pointer. llvm::WeakTrackingVH ConstantStringClassRef; /// The LLVM type corresponding to NSConstantString. llvm::StructType *NSConstantStringType = nullptr; llvm::StringMap<llvm::GlobalVariable *> NSConstantStringMap; /// GetNameForMethod - Return a name for the given method. /// \param[out] NameOut - The return value. void GetNameForMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD, SmallVectorImpl<char> &NameOut, bool ignoreCategoryNamespace = false); /// GetMethodVarName - Return a unique constant for the given /// selector's name. The return value has type char *. llvm::Constant *GetMethodVarName(Selector Sel); llvm::Constant *GetMethodVarName(IdentifierInfo *Ident); /// GetMethodVarType - Return a unique constant for the given /// method's type encoding string. The return value has type char *. // FIXME: This is a horrible name. llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D, bool Extended = false); llvm::Constant *GetMethodVarType(const FieldDecl *D); /// GetPropertyName - Return a unique constant for the given /// name. The return value has type char *. llvm::Constant *GetPropertyName(IdentifierInfo *Ident); // FIXME: This can be dropped once string functions are unified. llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD, const Decl *Container); /// GetClassName - Return a unique constant for the given selector's /// runtime name (which may change via use of objc_runtime_name attribute on /// class or protocol definition. The return value has type char *. llvm::Constant *GetClassName(StringRef RuntimeName); llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD); /// BuildIvarLayout - Builds ivar layout bitmap for the class /// implementation for the __strong or __weak case. /// /// \param hasMRCWeakIvars - Whether we are compiling in MRC and there /// are any weak ivars defined directly in the class. Meaningless unless /// building a weak layout. Does not guarantee that the layout will /// actually have any entries, because the ivar might be under-aligned. llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI, CharUnits beginOffset, CharUnits endOffset, bool forStrongLayout, bool hasMRCWeakIvars); llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI, CharUnits beginOffset, CharUnits endOffset) { return BuildIvarLayout(OI, beginOffset, endOffset, true, false); } llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI, CharUnits beginOffset, CharUnits endOffset, bool hasMRCWeakIvars) { return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars); } Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout); void UpdateRunSkipBlockVars(bool IsByref, Qualifiers::ObjCLifetime LifeTime, CharUnits FieldOffset, CharUnits FieldSize); void BuildRCBlockVarRecordLayout(const RecordType *RT, CharUnits BytePos, bool &HasUnion, bool ByrefLayout=false); void BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const RecordDecl *RD, ArrayRef<const FieldDecl*> RecFields, CharUnits BytePos, bool &HasUnion, bool ByrefLayout); uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout); llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout); /// GetIvarLayoutName - Returns a unique constant for the given /// ivar layout bitmap. llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident, const ObjCCommonTypesHelper &ObjCTypes); /// EmitPropertyList - Emit the given property list. The return /// value has type PropertyListPtrTy. llvm::Constant *EmitPropertyList(Twine Name, const Decl *Container, const ObjCContainerDecl *OCD, const ObjCCommonTypesHelper &ObjCTypes, bool IsClassProperty); /// EmitProtocolMethodTypes - Generate the array of extended method type /// strings. The return value has type Int8PtrPtrTy. llvm::Constant *EmitProtocolMethodTypes(Twine Name, ArrayRef<llvm::Constant*> MethodTypes, const ObjCCommonTypesHelper &ObjCTypes); /// GetProtocolRef - Return a reference to the internal protocol /// description, creating an empty one if it has not been /// defined. The return value has type ProtocolPtrTy. llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD); /// Return a reference to the given Class using runtime calls rather than /// by a symbol reference. llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID, ObjCCommonTypesHelper &ObjCTypes); std::string GetSectionName(StringRef Section, StringRef MachOAttributes); public: /// CreateMetadataVar - Create a global variable with internal /// linkage for use by the Objective-C runtime. /// /// This is a convenience wrapper which not only creates the /// variable, but also sets the section and alignment and adds the /// global to the "llvm.used" list. /// /// \param Name - The variable name. /// \param Init - The variable initializer; this is also used to /// define the type of the variable. /// \param Section - The section the variable should go into, or empty. /// \param Align - The alignment for the variable, or 0. /// \param AddToUsed - Whether the variable should be added to /// "llvm.used". llvm::GlobalVariable *CreateMetadataVar(Twine Name, ConstantStructBuilder &Init, StringRef Section, CharUnits Align, bool AddToUsed); llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init, StringRef Section, CharUnits Align, bool AddToUsed); llvm::GlobalVariable *CreateCStringLiteral(StringRef Name, ObjCLabelType LabelType, bool ForceNonFragileABI = false, bool NullTerminate = true); protected: CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Arg0, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs, const ObjCMethodDecl *OMD, const ObjCInterfaceDecl *ClassReceiver, const ObjCCommonTypesHelper &ObjCTypes); /// EmitImageInfo - Emit the image info marker used to encode some module /// level information. void EmitImageInfo(); public: CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { } bool isNonFragileABI() const { return ObjCABI == 2; } ConstantAddress GenerateConstantString(const StringLiteral *SL) override; ConstantAddress GenerateConstantNSString(const StringLiteral *SL); llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD=nullptr) override; llvm::Function *GenerateDirectMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD); void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD) override; void GenerateProtocol(const ObjCProtocolDecl *PD) override; /// GetOrEmitProtocol - Get the protocol object for the given /// declaration, emitting it if necessary. The return value has type /// ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0; /// GetOrEmitProtocolRef - Get a forward reference to the protocol /// object for the given declaration, emitting it if needed. These /// forward references will be filled in with empty bodies if no /// definition is seen. The return value has type ProtocolPtrTy. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0; virtual llvm::Constant *getNSConstantStringClassRef() = 0; llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM, const CGBlockInfo &blockInfo) override; llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM, const CGBlockInfo &blockInfo) override; std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM, const CGBlockInfo &blockInfo) override; llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM, QualType T) override; private: void fillRunSkipBlockVars(CodeGenModule &CGM, const CGBlockInfo &blockInfo); }; namespace { enum class MethodListType { CategoryInstanceMethods, CategoryClassMethods, InstanceMethods, ClassMethods, ProtocolInstanceMethods, ProtocolClassMethods, OptionalProtocolInstanceMethods, OptionalProtocolClassMethods, }; /// A convenience class for splitting the methods of a protocol into /// the four interesting groups. class ProtocolMethodLists { public: enum Kind { RequiredInstanceMethods, RequiredClassMethods, OptionalInstanceMethods, OptionalClassMethods }; enum { NumProtocolMethodLists = 4 }; static MethodListType getMethodListKind(Kind kind) { switch (kind) { case RequiredInstanceMethods: return MethodListType::ProtocolInstanceMethods; case RequiredClassMethods: return MethodListType::ProtocolClassMethods; case OptionalInstanceMethods: return MethodListType::OptionalProtocolInstanceMethods; case OptionalClassMethods: return MethodListType::OptionalProtocolClassMethods; } llvm_unreachable("bad kind"); } SmallVector<const ObjCMethodDecl *, 4> Methods[NumProtocolMethodLists]; static ProtocolMethodLists get(const ObjCProtocolDecl *PD) { ProtocolMethodLists result; for (auto MD : PD->methods()) { size_t index = (2 * size_t(MD->isOptional())) + (size_t(MD->isClassMethod())); result.Methods[index].push_back(MD); } return result; } template <class Self> SmallVector<llvm::Constant*, 8> emitExtendedTypesArray(Self *self) const { // In both ABIs, the method types list is parallel with the // concatenation of the methods arrays in the following order: // instance methods // class methods // optional instance methods // optional class methods SmallVector<llvm::Constant*, 8> result; // Methods is already in the correct order for both ABIs. for (auto &list : Methods) { for (auto MD : list) { result.push_back(self->GetMethodVarType(MD, true)); } } return result; } template <class Self> llvm::Constant *emitMethodList(Self *self, const ObjCProtocolDecl *PD, Kind kind) const { return self->emitMethodList(PD->getObjCRuntimeNameAsString(), getMethodListKind(kind), Methods[kind]); } }; } // end anonymous namespace class CGObjCMac : public CGObjCCommonMac { private: friend ProtocolMethodLists; ObjCTypesHelper ObjCTypes; /// EmitModuleInfo - Another marker encoding module level /// information. void EmitModuleInfo(); /// EmitModuleSymols - Emit module symbols, the list of defined /// classes and categories. The result has type SymtabPtrTy. llvm::Constant *EmitModuleSymbols(); /// FinishModule - Write out global data structures at the end of /// processing a translation unit. void FinishModule(); /// EmitClassExtension - Generate the class extension structure used /// to store the weak ivar layout and properties. The return value /// has type ClassExtensionPtrTy. llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID, CharUnits instanceSize, bool hasMRCWeakIvars, bool isMetaclass); /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, /// for the given class. llvm::Value *EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II); llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; /// EmitSuperClassRef - Emits reference to class's main metadata class. llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID); /// EmitIvarList - Emit the ivar list for the given /// implementation. If ForClass is true the list of class ivars /// (i.e. metaclass ivars) is emitted, otherwise the list of /// interface ivars will be emitted. The return value has type /// IvarListPtrTy. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID, bool ForClass); /// EmitMetaClass - Emit a forward reference to the class structure /// for the metaclass of the given interface. The return value has /// type ClassPtrTy. llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID); /// EmitMetaClass - Emit a class structure for the metaclass of the /// given implementation. The return value has type ClassPtrTy. llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID, llvm::Constant *Protocols, ArrayRef<const ObjCMethodDecl *> Methods); void emitMethodConstant(ConstantArrayBuilder &builder, const ObjCMethodDecl *MD); void emitMethodDescriptionConstant(ConstantArrayBuilder &builder, const ObjCMethodDecl *MD); /// EmitMethodList - Emit the method list for the given /// implementation. The return value has type MethodListPtrTy. llvm::Constant *emitMethodList(Twine Name, MethodListType MLT, ArrayRef<const ObjCMethodDecl *> Methods); /// GetOrEmitProtocol - Get the protocol object for the given /// declaration, emitting it if necessary. The return value has type /// ProtocolPtrTy. llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override; /// GetOrEmitProtocolRef - Get a forward reference to the protocol /// object for the given declaration, emitting it if needed. These /// forward references will be filled in with empty bodies if no /// definition is seen. The return value has type ProtocolPtrTy. llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override; /// EmitProtocolExtension - Generate the protocol extension /// structure used to store optional instance and class methods, and /// protocol properties. The return value has type /// ProtocolExtensionPtrTy. llvm::Constant * EmitProtocolExtension(const ObjCProtocolDecl *PD, const ProtocolMethodLists &methodLists); /// EmitProtocolList - Generate the list of referenced /// protocols. The return value has type ProtocolListPtrTy. llvm::Constant *EmitProtocolList(Twine Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end); /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, /// for the given selector. llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel); Address EmitSelectorAddr(Selector Sel); public: CGObjCMac(CodeGen::CodeGenModule &cgm); llvm::Constant *getNSConstantStringClassRef() override; llvm::Function *ModuleInitFunction() override; CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &CallArgs, const ObjCInterfaceDecl *Class, const ObjCMethodDecl *Method) override; CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs, const ObjCMethodDecl *Method) override; llvm::Value *GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) override; llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override; Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override; /// The NeXT/Apple runtimes do not support typed selectors; just emit an /// untyped one. llvm::Value *GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl *Method) override; llvm::Constant *GetEHType(QualType T) override; void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {} llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, const ObjCProtocolDecl *PD) override; llvm::FunctionCallee GetPropertyGetFunction() override; llvm::FunctionCallee GetPropertySetFunction() override; llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic, bool copy) override; llvm::FunctionCallee GetGetStructFunction() override; llvm::FunctionCallee GetSetStructFunction() override; llvm::FunctionCallee GetCppAtomicObjectGetFunction() override; llvm::FunctionCallee GetCppAtomicObjectSetFunction() override; llvm::FunctionCallee EnumerationMutationFunction() override; void EmitTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S) override; void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S) override; void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S); void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true) override; llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, Address AddrWeakObj) override; void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst) override; void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, bool threadlocal = false) override; void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, llvm::Value *ivarOffset) override; void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest) override; void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, Address dest, Address src, llvm::Value *size) override; LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers) override; llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) override; }; class CGObjCNonFragileABIMac : public CGObjCCommonMac { private: friend ProtocolMethodLists; ObjCNonFragileABITypesHelper ObjCTypes; llvm::GlobalVariable* ObjCEmptyCacheVar; llvm::Constant* ObjCEmptyVtableVar; /// SuperClassReferences - uniqued super class references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences; /// MetaClassReferences - uniqued meta class references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences; /// EHTypeReferences - uniqued class ehtype references. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences; /// VTableDispatchMethods - List of methods for which we generate /// vtable-based message dispatch. llvm::DenseSet<Selector> VTableDispatchMethods; /// DefinedMetaClasses - List of defined meta-classes. std::vector<llvm::GlobalValue*> DefinedMetaClasses; /// isVTableDispatchedSelector - Returns true if SEL is a /// vtable-based selector. bool isVTableDispatchedSelector(Selector Sel); /// FinishNonFragileABIModule - Write out global data structures at the end of /// processing a translation unit. void FinishNonFragileABIModule(); /// AddModuleClassList - Add the given list of class pointers to the /// module with the provided symbol and section names. void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName, StringRef SectionName); llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags, unsigned InstanceStart, unsigned InstanceSize, const ObjCImplementationDecl *ID); llvm::GlobalVariable *BuildClassObject(const ObjCInterfaceDecl *CI, bool isMetaclass, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV, llvm::Constant *ClassRoGV, bool HiddenVisibility); void emitMethodConstant(ConstantArrayBuilder &builder, const ObjCMethodDecl *MD, bool forProtocol); /// Emit the method list for the given implementation. The return value /// has type MethodListnfABITy. llvm::Constant *emitMethodList(Twine Name, MethodListType MLT, ArrayRef<const ObjCMethodDecl *> Methods); /// EmitIvarList - Emit the ivar list for the given /// implementation. If ForClass is true the list of class ivars /// (i.e. metaclass ivars) is emitted, otherwise the list of /// interface ivars will be emitted. The return value has type /// IvarListnfABIPtrTy. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID); llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar, unsigned long int offset); /// GetOrEmitProtocol - Get the protocol object for the given /// declaration, emitting it if necessary. The return value has type /// ProtocolPtrTy. llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override; /// GetOrEmitProtocolRef - Get a forward reference to the protocol /// object for the given declaration, emitting it if needed. These /// forward references will be filled in with empty bodies if no /// definition is seen. The return value has type ProtocolPtrTy. llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override; /// EmitProtocolList - Generate the list of referenced /// protocols. The return value has type ProtocolListPtrTy. llvm::Constant *EmitProtocolList(Twine Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end); CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs, const ObjCMethodDecl *Method); /// GetClassGlobal - Return the global variable for the Objective-C /// class of the given name. llvm::Constant *GetClassGlobal(StringRef Name, ForDefinition_t IsForDefinition, bool Weak = false, bool DLLImport = false); llvm::Constant *GetClassGlobal(const ObjCInterfaceDecl *ID, bool isMetaclass, ForDefinition_t isForDefinition); llvm::Constant *GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID); llvm::Value *EmitLoadOfClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID, llvm::GlobalVariable *Entry); /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, /// for the given class reference. llvm::Value *EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II, const ObjCInterfaceDecl *ID); llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override; /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy, /// for the given super class reference. llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID); /// EmitMetaClassRef - Return a Value * of the address of _class_t /// meta-data llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID, bool Weak); /// ObjCIvarOffsetVariable - Returns the ivar offset variable for /// the given ivar. /// llvm::GlobalVariable * ObjCIvarOffsetVariable( const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar); /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy, /// for the given selector. llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel); Address EmitSelectorAddr(Selector Sel); /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C /// interface. The return value has type EHTypePtrTy. llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID, ForDefinition_t IsForDefinition); StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; } StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; } void GetClassSizeInfo(const ObjCImplementationDecl *OID, uint32_t &InstanceStart, uint32_t &InstanceSize); // Shamelessly stolen from Analysis/CFRefCount.cpp Selector GetNullarySelector(const char* name) const { IdentifierInfo* II = &CGM.getContext().Idents.get(name); return CGM.getContext().Selectors.getSelector(0, &II); } Selector GetUnarySelector(const char* name) const { IdentifierInfo* II = &CGM.getContext().Idents.get(name); return CGM.getContext().Selectors.getSelector(1, &II); } /// ImplementationIsNonLazy - Check whether the given category or /// class implementation is "non-lazy". bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const; bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF, const ObjCIvarDecl *IV) { // Annotate the load as an invariant load iff inside an instance method // and ivar belongs to instance method's class and one of its super class. // This check is needed because the ivar offset is a lazily // initialised value that may depend on objc_msgSend to perform a fixup on // the first message dispatch. // // An additional opportunity to mark the load as invariant arises when the // base of the ivar access is a parameter to an Objective C method. // However, because the parameters are not available in the current // interface, we cannot perform this check. // // Note that for direct methods, because objc_msgSend is skipped, // and that the method may be inlined, this optimization actually // can't be performed. if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl)) if (MD->isInstanceMethod() && !MD->isDirectMethod()) if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) return IV->getContainingInterface()->isSuperClassOf(ID); return false; } bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) { // NSObject is a fixed size. If we can see the @implementation of a class // which inherits from NSObject then we know that all it's offsets also must // be fixed. FIXME: Can we do this if see a chain of super classes with // implementations leading to NSObject? return ID->getImplementation() && ID->getSuperClass() && ID->getSuperClass()->getName() == "NSObject"; } public: CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm); llvm::Constant *getNSConstantStringClassRef() override; llvm::Function *ModuleInitFunction() override; CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &CallArgs, const ObjCInterfaceDecl *Class, const ObjCMethodDecl *Method) override; CodeGen::RValue GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CallArgList &CallArgs, const ObjCMethodDecl *Method) override; llvm::Value *GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) override; llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override { return EmitSelector(CGF, Sel); } Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override { return EmitSelectorAddr(Sel); } /// The NeXT/Apple runtimes do not support typed selectors; just emit an /// untyped one. llvm::Value *GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl *Method) override { return EmitSelector(CGF, Method->getSelector()); } void GenerateCategory(const ObjCCategoryImplDecl *CMD) override; void GenerateClass(const ObjCImplementationDecl *ClassDecl) override; void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {} llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF, const ObjCProtocolDecl *PD) override; llvm::Constant *GetEHType(QualType T) override; llvm::FunctionCallee GetPropertyGetFunction() override { return ObjCTypes.getGetPropertyFn(); } llvm::FunctionCallee GetPropertySetFunction() override { return ObjCTypes.getSetPropertyFn(); } llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic, bool copy) override { return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy); } llvm::FunctionCallee GetSetStructFunction() override { return ObjCTypes.getCopyStructFn(); } llvm::FunctionCallee GetGetStructFunction() override { return ObjCTypes.getCopyStructFn(); } llvm::FunctionCallee GetCppAtomicObjectSetFunction() override { return ObjCTypes.getCppAtomicObjectFunction(); } llvm::FunctionCallee GetCppAtomicObjectGetFunction() override { return ObjCTypes.getCppAtomicObjectFunction(); } llvm::FunctionCallee EnumerationMutationFunction() override { return ObjCTypes.getEnumerationMutationFn(); } void EmitTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S) override; void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S) override; void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true) override; llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, Address AddrWeakObj) override; void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address edst) override; void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, bool threadlocal = false) override; void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, llvm::Value *ivarOffset) override; void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest) override; void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, Address dest, Address src, llvm::Value *size) override; LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers) override; llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) override; }; /// A helper class for performing the null-initialization of a return /// value. struct NullReturnState { llvm::BasicBlock *NullBB; NullReturnState() : NullBB(nullptr) {} /// Perform a null-check of the given receiver. void init(CodeGenFunction &CGF, llvm::Value *receiver) { // Make blocks for the null-receiver and call edges. NullBB = CGF.createBasicBlock("msgSend.null-receiver"); llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call"); // Check for a null receiver and, if there is one, jump to the // null-receiver block. There's no point in trying to avoid it: // we're always going to put *something* there, because otherwise // we shouldn't have done this null-check in the first place. llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver); CGF.Builder.CreateCondBr(isNull, NullBB, callBB); // Otherwise, start performing the call. CGF.EmitBlock(callBB); } /// Complete the null-return operation. It is valid to call this /// regardless of whether 'init' has been called. RValue complete(CodeGenFunction &CGF, ReturnValueSlot returnSlot, RValue result, QualType resultType, const CallArgList &CallArgs, const ObjCMethodDecl *Method) { // If we never had to do a null-check, just use the raw result. if (!NullBB) return result; // The continuation block. This will be left null if we don't have an // IP, which can happen if the method we're calling is marked noreturn. llvm::BasicBlock *contBB = nullptr; // Finish the call path. llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock(); if (callBB) { contBB = CGF.createBasicBlock("msgSend.cont"); CGF.Builder.CreateBr(contBB); } // Okay, start emitting the null-receiver block. CGF.EmitBlock(NullBB); // Release any consumed arguments we've got. if (Method) { CallArgList::const_iterator I = CallArgs.begin(); for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(), e = Method->param_end(); i != e; ++i, ++I) { const ParmVarDecl *ParamDecl = (*i); if (ParamDecl->hasAttr<NSConsumedAttr>()) { RValue RV = I->getRValue(CGF); assert(RV.isScalar() && "NullReturnState::complete - arg not on object"); CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime); } } } // The phi code below assumes that we haven't needed any control flow yet. assert(CGF.Builder.GetInsertBlock() == NullBB); // If we've got a void return, just jump to the continuation block. if (result.isScalar() && resultType->isVoidType()) { // No jumps required if the message-send was noreturn. if (contBB) CGF.EmitBlock(contBB); return result; } // If we've got a scalar return, build a phi. if (result.isScalar()) { // Derive the null-initialization value. llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType); // If no join is necessary, just flow out. if (!contBB) return RValue::get(null); // Otherwise, build a phi. CGF.EmitBlock(contBB); llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2); phi->addIncoming(result.getScalarVal(), callBB); phi->addIncoming(null, NullBB); return RValue::get(phi); } // If we've got an aggregate return, null the buffer out. // FIXME: maybe we should be doing things differently for all the // cases where the ABI has us returning (1) non-agg values in // memory or (2) agg values in registers. if (result.isAggregate()) { assert(result.isAggregate() && "null init of non-aggregate result?"); if (!returnSlot.isUnused()) CGF.EmitNullInitialization(result.getAggregateAddress(), resultType); if (contBB) CGF.EmitBlock(contBB); return result; } // Complex types. CGF.EmitBlock(contBB); CodeGenFunction::ComplexPairTy callResult = result.getComplexVal(); // Find the scalar type and its zero value. llvm::Type *scalarTy = callResult.first->getType(); llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy); // Build phis for both coordinates. llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2); real->addIncoming(callResult.first, callBB); real->addIncoming(scalarZero, NullBB); llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2); imag->addIncoming(callResult.second, callBB); imag->addIncoming(scalarZero, NullBB); return RValue::getComplex(real, imag); } }; } // end anonymous namespace /* *** Helper Functions *** */ /// getConstantGEP() - Help routine to construct simple GEPs. static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext, llvm::GlobalVariable *C, unsigned idx0, unsigned idx1) { llvm::Value *Idxs[] = { llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0), llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1) }; return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs); } /// hasObjCExceptionAttribute - Return true if this class or any super /// class has the __objc_exception__ attribute. static bool hasObjCExceptionAttribute(ASTContext &Context, const ObjCInterfaceDecl *OID) { if (OID->hasAttr<ObjCExceptionAttr>()) return true; if (const ObjCInterfaceDecl *Super = OID->getSuperClass()) return hasObjCExceptionAttribute(Context, Super); return false; } static llvm::GlobalValue::LinkageTypes getLinkageTypeForObjCMetadata(CodeGenModule &CGM, StringRef Section) { if (CGM.getTriple().isOSBinFormatMachO() && (Section.empty() || Section.startswith("__DATA"))) return llvm::GlobalValue::InternalLinkage; return llvm::GlobalValue::PrivateLinkage; } /// A helper function to create an internal or private global variable. static llvm::GlobalVariable * finishAndCreateGlobal(ConstantInitBuilder::StructBuilder &Builder, const llvm::Twine &Name, CodeGenModule &CGM) { std::string SectionName; if (CGM.getTriple().isOSBinFormatMachO()) SectionName = "__DATA, __objc_const"; auto *GV = Builder.finishAndCreateGlobal( Name, CGM.getPointerAlign(), /*constant*/ false, getLinkageTypeForObjCMetadata(CGM, SectionName)); GV->setSection(SectionName); return GV; } /* *** CGObjCMac Public Interface *** */ CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), ObjCTypes(cgm) { ObjCABI = 1; EmitImageInfo(); } /// GetClass - Return a reference to the class for the given interface /// decl. llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { return EmitClassRef(CGF, ID); } /// GetSelector - Return the pointer to the unique'd string for this selector. llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) { return EmitSelector(CGF, Sel); } Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) { return EmitSelectorAddr(Sel); } llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl *Method) { return EmitSelector(CGF, Method->getSelector()); } llvm::Constant *CGObjCMac::GetEHType(QualType T) { if (T->isObjCIdType() || T->isObjCQualifiedIdType()) { return CGM.GetAddrOfRTTIDescriptor( CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true); } if (T->isObjCClassType() || T->isObjCQualifiedClassType()) { return CGM.GetAddrOfRTTIDescriptor( CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true); } if (T->isObjCObjectPointerType()) return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true); llvm_unreachable("asking for catch type for ObjC type in fragile runtime"); } /// Generate a constant CFString object. /* struct __builtin_CFString { const int *isa; // point to __CFConstantStringClassReference int flags; const char *str; long length; }; */ /// or Generate a constant NSString object. /* struct __builtin_NSString { const int *isa; // point to __NSConstantStringClassReference const char *str; unsigned int length; }; */ ConstantAddress CGObjCCommonMac::GenerateConstantString(const StringLiteral *SL) { return (!CGM.getLangOpts().NoConstantCFStrings ? CGM.GetAddrOfConstantCFString(SL) : GenerateConstantNSString(SL)); } static llvm::StringMapEntry<llvm::GlobalVariable *> & GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, const StringLiteral *Literal, unsigned &StringLength) { StringRef String = Literal->getString(); StringLength = String.size(); return *Map.insert(std::make_pair(String, nullptr)).first; } llvm::Constant *CGObjCMac::getNSConstantStringClassRef() { if (llvm::Value *V = ConstantStringClassRef) return cast<llvm::Constant>(V); auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass; std::string str = StringClass.empty() ? "_NSConstantStringClassReference" : "_" + StringClass + "ClassReference"; llvm::Type *PTy = llvm::ArrayType::get(CGM.IntTy, 0); auto GV = CGM.CreateRuntimeVariable(PTy, str); auto V = llvm::ConstantExpr::getBitCast(GV, CGM.IntTy->getPointerTo()); ConstantStringClassRef = V; return V; } llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() { if (llvm::Value *V = ConstantStringClassRef) return cast<llvm::Constant>(V); auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass; std::string str = StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" : "OBJC_CLASS_$_" + StringClass; llvm::Constant *GV = GetClassGlobal(str, NotForDefinition); // Make sure the result is of the correct type. auto V = llvm::ConstantExpr::getBitCast(GV, CGM.IntTy->getPointerTo()); ConstantStringClassRef = V; return V; } ConstantAddress CGObjCCommonMac::GenerateConstantNSString(const StringLiteral *Literal) { unsigned StringLength = 0; llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = GetConstantStringEntry(NSConstantStringMap, Literal, StringLength); if (auto *C = Entry.second) return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); // If we don't already have it, get _NSConstantStringClassReference. llvm::Constant *Class = getNSConstantStringClassRef(); // If we don't already have it, construct the type for a constant NSString. if (!NSConstantStringType) { NSConstantStringType = llvm::StructType::create({ CGM.Int32Ty->getPointerTo(), CGM.Int8PtrTy, CGM.IntTy }, "struct.__builtin_NSString"); } ConstantInitBuilder Builder(CGM); auto Fields = Builder.beginStruct(NSConstantStringType); // Class pointer. Fields.add(Class); // String pointer. llvm::Constant *C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); llvm::GlobalValue::LinkageTypes Linkage = llvm::GlobalValue::PrivateLinkage; bool isConstant = !CGM.getLangOpts().WritableStrings; auto *GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), isConstant, Linkage, C, ".str"); GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); // Don't enforce the target's minimum global alignment, since the only use // of the string is via this class initializer. GV->setAlignment(llvm::Align(1)); Fields.addBitCast(GV, CGM.Int8PtrTy); // String length. Fields.addInt(CGM.IntTy, StringLength); // The struct. CharUnits Alignment = CGM.getPointerAlign(); GV = Fields.finishAndCreateGlobal("_unnamed_nsstring_", Alignment, /*constant*/ true, llvm::GlobalVariable::PrivateLinkage); const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; const char *NSStringNonFragileABISection = "__DATA,__objc_stringobj,regular,no_dead_strip"; // FIXME. Fix section. GV->setSection(CGM.getLangOpts().ObjCRuntime.isNonFragile() ? NSStringNonFragileABISection : NSStringSection); Entry.second = GV; return ConstantAddress(GV, Alignment); } enum { kCFTaggedObjectID_Integer = (1 << 1) + 1 }; /// Generates a message send where the super is the receiver. This is /// a message send to self with special delivery semantics indicating /// which class's method should be called. CodeGen::RValue CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CodeGen::CallArgList &CallArgs, const ObjCMethodDecl *Method) { // Create and init a super structure; this is a (receiver, class) // pair we will pass to objc_msgSendSuper. Address ObjCSuper = CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(), "objc_super"); llvm::Value *ReceiverAsObject = CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); CGF.Builder.CreateStore(ReceiverAsObject, CGF.Builder.CreateStructGEP(ObjCSuper, 0)); // If this is a class message the metaclass is passed as the target. llvm::Value *Target; if (IsClassMessage) { if (isCategoryImpl) { // Message sent to 'super' in a class method defined in a category // implementation requires an odd treatment. // If we are in a class method, we must retrieve the // _metaclass_ for the current class, pointed at by // the class's "isa" pointer. The following assumes that // isa" is the first ivar in a class (which it must be). Target = EmitClassRef(CGF, Class->getSuperClass()); Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0); Target = CGF.Builder.CreateAlignedLoad(Target, CGF.getPointerAlign()); } else { llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class); llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1); llvm::Value *Super = CGF.Builder.CreateAlignedLoad(SuperPtr, CGF.getPointerAlign()); Target = Super; } } else if (isCategoryImpl) Target = EmitClassRef(CGF, Class->getSuperClass()); else { llvm::Value *ClassPtr = EmitSuperClassRef(Class); ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1); Target = CGF.Builder.CreateAlignedLoad(ClassPtr, CGF.getPointerAlign()); } // FIXME: We shouldn't need to do this cast, rectify the ASTContext and // ObjCTypes types. llvm::Type *ClassTy = CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); Target = CGF.Builder.CreateBitCast(Target, ClassTy); CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1)); return EmitMessageSend(CGF, Return, ResultType, Sel, ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy, true, CallArgs, Method, Class, ObjCTypes); } /// Generate code for a message send expression. CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &CallArgs, const ObjCInterfaceDecl *Class, const ObjCMethodDecl *Method) { return EmitMessageSend(CGF, Return, ResultType, Sel, Receiver, CGF.getContext().getObjCIdType(), false, CallArgs, Method, Class, ObjCTypes); } static bool isWeakLinkedClass(const ObjCInterfaceDecl *ID) { do { if (ID->isWeakImported()) return true; } while ((ID = ID->getSuperClass())); return false; } CodeGen::RValue CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Arg0, QualType Arg0Ty, bool IsSuper, const CallArgList &CallArgs, const ObjCMethodDecl *Method, const ObjCInterfaceDecl *ClassReceiver, const ObjCCommonTypesHelper &ObjCTypes) { CodeGenTypes &Types = CGM.getTypes(); auto selTy = CGF.getContext().getObjCSelType(); llvm::Value *SelValue; if (Method && Method->isDirectMethod()) { // Direct methods will synthesize the proper `_cmd` internally, // so just don't bother with setting the `_cmd` argument. assert(!IsSuper); SelValue = llvm::UndefValue::get(Types.ConvertType(selTy)); } else { SelValue = GetSelector(CGF, Sel); } CallArgList ActualArgs; if (!IsSuper) Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy); ActualArgs.add(RValue::get(Arg0), Arg0Ty); ActualArgs.add(RValue::get(SelValue), selTy); ActualArgs.addFrom(CallArgs); // If we're calling a method, use the formal signature. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs); if (Method) assert(CGM.getContext().getCanonicalType(Method->getReturnType()) == CGM.getContext().getCanonicalType(ResultType) && "Result type mismatch!"); bool ReceiverCanBeNull = true; // Super dispatch assumes that self is non-null; even the messenger // doesn't have a null check internally. if (IsSuper) { ReceiverCanBeNull = false; // If this is a direct dispatch of a class method, check whether the class, // or anything in its hierarchy, was weak-linked. } else if (ClassReceiver && Method && Method->isClassMethod()) { ReceiverCanBeNull = isWeakLinkedClass(ClassReceiver); // If we're emitting a method, and self is const (meaning just ARC, for now), // and the receiver is a load of self, then self is a valid object. } else if (auto CurMethod = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl)) { auto Self = CurMethod->getSelfDecl(); if (Self->getType().isConstQualified()) { if (auto LI = dyn_cast<llvm::LoadInst>(Arg0->stripPointerCasts())) { llvm::Value *SelfAddr = CGF.GetAddrOfLocalVar(Self).getPointer(); if (SelfAddr == LI->getPointerOperand()) { ReceiverCanBeNull = false; } } } } bool RequiresNullCheck = false; llvm::FunctionCallee Fn = nullptr; if (Method && Method->isDirectMethod()) { Fn = GenerateDirectMethod(Method, Method->getClassInterface()); } else if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) { if (ReceiverCanBeNull) RequiresNullCheck = true; Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper) : ObjCTypes.getSendStretFn(IsSuper); } else if (CGM.ReturnTypeUsesFPRet(ResultType)) { Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper) : ObjCTypes.getSendFpretFn(IsSuper); } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) { Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper) : ObjCTypes.getSendFp2retFn(IsSuper); } else { // arm64 uses objc_msgSend for stret methods and yet null receiver check // must be made for it. if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo)) RequiresNullCheck = true; Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper) : ObjCTypes.getSendFn(IsSuper); } // Cast function to proper signature llvm::Constant *BitcastFn = cast<llvm::Constant>( CGF.Builder.CreateBitCast(Fn.getCallee(), MSI.MessengerType)); // We don't need to emit a null check to zero out an indirect result if the // result is ignored. if (Return.isUnused()) RequiresNullCheck = false; // Emit a null-check if there's a consumed argument other than the receiver. if (!RequiresNullCheck && CGM.getLangOpts().ObjCAutoRefCount && Method) { for (const auto *ParamDecl : Method->parameters()) { if (ParamDecl->hasAttr<NSConsumedAttr>()) { RequiresNullCheck = true; break; } } } NullReturnState nullReturn; if (RequiresNullCheck) { nullReturn.init(CGF, Arg0); } llvm::CallBase *CallSite; CGCallee Callee = CGCallee::forDirect(BitcastFn); RValue rvalue = CGF.EmitCall(MSI.CallInfo, Callee, Return, ActualArgs, &CallSite); // Mark the call as noreturn if the method is marked noreturn and the // receiver cannot be null. if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) { CallSite->setDoesNotReturn(); } return nullReturn.complete(CGF, Return, rvalue, ResultType, CallArgs, RequiresNullCheck ? Method : nullptr); } static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT, bool pointee = false) { // Note that GC qualification applies recursively to C pointer types // that aren't otherwise decorated. This is weird, but it's probably // an intentional workaround to the unreliable placement of GC qualifiers. if (FQT.isObjCGCStrong()) return Qualifiers::Strong; if (FQT.isObjCGCWeak()) return Qualifiers::Weak; if (auto ownership = FQT.getObjCLifetime()) { // Ownership does not apply recursively to C pointer types. if (pointee) return Qualifiers::GCNone; switch (ownership) { case Qualifiers::OCL_Weak: return Qualifiers::Weak; case Qualifiers::OCL_Strong: return Qualifiers::Strong; case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone; case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?"); case Qualifiers::OCL_None: llvm_unreachable("known nonzero"); } llvm_unreachable("bad objc ownership"); } // Treat unqualified retainable pointers as strong. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) return Qualifiers::Strong; // Walk into C pointer types, but only in GC. if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) { if (const PointerType *PT = FQT->getAs<PointerType>()) return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true); } return Qualifiers::GCNone; } namespace { struct IvarInfo { CharUnits Offset; uint64_t SizeInWords; IvarInfo(CharUnits offset, uint64_t sizeInWords) : Offset(offset), SizeInWords(sizeInWords) {} // Allow sorting based on byte pos. bool operator<(const IvarInfo &other) const { return Offset < other.Offset; } }; /// A helper class for building GC layout strings. class IvarLayoutBuilder { CodeGenModule &CGM; /// The start of the layout. Offsets will be relative to this value, /// and entries less than this value will be silently discarded. CharUnits InstanceBegin; /// The end of the layout. Offsets will never exceed this value. CharUnits InstanceEnd; /// Whether we're generating the strong layout or the weak layout. bool ForStrongLayout; /// Whether the offsets in IvarsInfo might be out-of-order. bool IsDisordered = false; llvm::SmallVector<IvarInfo, 8> IvarsInfo; public: IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin, CharUnits instanceEnd, bool forStrongLayout) : CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd), ForStrongLayout(forStrongLayout) { } void visitRecord(const RecordType *RT, CharUnits offset); template <class Iterator, class GetOffsetFn> void visitAggregate(Iterator begin, Iterator end, CharUnits aggrOffset, const GetOffsetFn &getOffset); void visitField(const FieldDecl *field, CharUnits offset); /// Add the layout of a block implementation. void visitBlock(const CGBlockInfo &blockInfo); /// Is there any information for an interesting bitmap? bool hasBitmapData() const { return !IvarsInfo.empty(); } llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC, llvm::SmallVectorImpl<unsigned char> &buffer); static void dump(ArrayRef<unsigned char> buffer) { const unsigned char *s = buffer.data(); for (unsigned i = 0, e = buffer.size(); i < e; i++) if (!(s[i] & 0xf0)) printf("0x0%x%s", s[i], s[i] != 0 ? ", " : ""); else printf("0x%x%s", s[i], s[i] != 0 ? ", " : ""); printf("\n"); } }; } // end anonymous namespace llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); if (CGM.getLangOpts().getGC() == LangOptions::NonGC) return nullPtr; IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize, /*for strong layout*/ true); builder.visitBlock(blockInfo); if (!builder.hasBitmapData()) return nullPtr; llvm::SmallVector<unsigned char, 32> buffer; llvm::Constant *C = builder.buildBitmap(*this, buffer); if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) { printf("\n block variable layout for block: "); builder.dump(buffer); } return C; } void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) { // __isa is the first field in block descriptor and must assume by runtime's // convention that it is GC'able. IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1)); const BlockDecl *blockDecl = blockInfo.getBlockDecl(); // Ignore the optional 'this' capture: C++ objects are not assumed // to be GC'ed. CharUnits lastFieldOffset; // Walk the captured variables. for (const auto &CI : blockDecl->captures()) { const VarDecl *variable = CI.getVariable(); QualType type = variable->getType(); const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); // Ignore constant captures. if (capture.isConstant()) continue; CharUnits fieldOffset = capture.getOffset(); // Block fields are not necessarily ordered; if we detect that we're // adding them out-of-order, make sure we sort later. if (fieldOffset < lastFieldOffset) IsDisordered = true; lastFieldOffset = fieldOffset; // __block variables are passed by their descriptor address. if (CI.isByRef()) { IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1)); continue; } assert(!type->isArrayType() && "array variable should not be caught"); if (const RecordType *record = type->getAs<RecordType>()) { visitRecord(record, fieldOffset); continue; } Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type); if (GCAttr == Qualifiers::Strong) { assert(CGM.getContext().getTypeSize(type) == CGM.getTarget().getPointerWidth(0)); IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1)); } } } /// getBlockCaptureLifetime - This routine returns life time of the captured /// block variable for the purpose of block layout meta-data generation. FQT is /// the type of the variable captured in the block. Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT, bool ByrefLayout) { // If it has an ownership qualifier, we're done. if (auto lifetime = FQT.getObjCLifetime()) return lifetime; // If it doesn't, and this is ARC, it has no ownership. if (CGM.getLangOpts().ObjCAutoRefCount) return Qualifiers::OCL_None; // In MRC, retainable pointers are owned by non-__block variables. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType()) return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong; return Qualifiers::OCL_None; } void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref, Qualifiers::ObjCLifetime LifeTime, CharUnits FieldOffset, CharUnits FieldSize) { // __block variables are passed by their descriptor address. if (IsByref) RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset, FieldSize)); else if (LifeTime == Qualifiers::OCL_Strong) RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset, FieldSize)); else if (LifeTime == Qualifiers::OCL_Weak) RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset, FieldSize)); else if (LifeTime == Qualifiers::OCL_ExplicitNone) RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset, FieldSize)); else RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES, FieldOffset, FieldSize)); } void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout, const RecordDecl *RD, ArrayRef<const FieldDecl*> RecFields, CharUnits BytePos, bool &HasUnion, bool ByrefLayout) { bool IsUnion = (RD && RD->isUnion()); CharUnits MaxUnionSize = CharUnits::Zero(); const FieldDecl *MaxField = nullptr; const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr; CharUnits MaxFieldOffset = CharUnits::Zero(); CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero(); if (RecFields.empty()) return; unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { const FieldDecl *Field = RecFields[i]; // Note that 'i' here is actually the field index inside RD of Field, // although this dependency is hidden. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); CharUnits FieldOffset = CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i)); // Skip over unnamed or bitfields if (!Field->getIdentifier() || Field->isBitField()) { LastFieldBitfieldOrUnnamed = Field; LastBitfieldOrUnnamedOffset = FieldOffset; continue; } LastFieldBitfieldOrUnnamed = nullptr; QualType FQT = Field->getType(); if (FQT->isRecordType() || FQT->isUnionType()) { if (FQT->isUnionType()) HasUnion = true; BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(), BytePos + FieldOffset, HasUnion); continue; } if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { auto *CArray = cast<ConstantArrayType>(Array); uint64_t ElCount = CArray->getSize().getZExtValue(); assert(CArray && "only array with known element size is supported"); FQT = CArray->getElementType(); while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) { auto *CArray = cast<ConstantArrayType>(Array); ElCount *= CArray->getSize().getZExtValue(); FQT = CArray->getElementType(); } if (FQT->isRecordType() && ElCount) { int OldIndex = RunSkipBlockVars.size() - 1; const RecordType *RT = FQT->getAs<RecordType>(); BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset, HasUnion); // Replicate layout information for each array element. Note that // one element is already done. uint64_t ElIx = 1; for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) { CharUnits Size = CGM.getContext().getTypeSizeInChars(RT); for (int i = OldIndex+1; i <= FirstIndex; ++i) RunSkipBlockVars.push_back( RUN_SKIP(RunSkipBlockVars[i].opcode, RunSkipBlockVars[i].block_var_bytepos + Size*ElIx, RunSkipBlockVars[i].block_var_size)); } continue; } } CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType()); if (IsUnion) { CharUnits UnionIvarSize = FieldSize; if (UnionIvarSize > MaxUnionSize) { MaxUnionSize = UnionIvarSize; MaxField = Field; MaxFieldOffset = FieldOffset; } } else { UpdateRunSkipBlockVars(false, getBlockCaptureLifetime(FQT, ByrefLayout), BytePos + FieldOffset, FieldSize); } } if (LastFieldBitfieldOrUnnamed) { if (LastFieldBitfieldOrUnnamed->isBitField()) { // Last field was a bitfield. Must update the info. uint64_t BitFieldSize = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext()); unsigned UnsSize = (BitFieldSize / ByteSizeInBits) + ((BitFieldSize % ByteSizeInBits) != 0); CharUnits Size = CharUnits::fromQuantity(UnsSize); Size += LastBitfieldOrUnnamedOffset; UpdateRunSkipBlockVars(false, getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(), ByrefLayout), BytePos + LastBitfieldOrUnnamedOffset, Size); } else { assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed"); // Last field was unnamed. Must update skip info. CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType()); UpdateRunSkipBlockVars(false, getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(), ByrefLayout), BytePos + LastBitfieldOrUnnamedOffset, FieldSize); } } if (MaxField) UpdateRunSkipBlockVars(false, getBlockCaptureLifetime(MaxField->getType(), ByrefLayout), BytePos + MaxFieldOffset, MaxUnionSize); } void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT, CharUnits BytePos, bool &HasUnion, bool ByrefLayout) { const RecordDecl *RD = RT->getDecl(); SmallVector<const FieldDecl*, 16> Fields(RD->fields()); llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0)); const llvm::StructLayout *RecLayout = CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty)); BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout); } /// InlineLayoutInstruction - This routine produce an inline instruction for the /// block variable layout if it can. If not, it returns 0. Rules are as follow: /// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world, /// an inline layout of value 0x0000000000000xyz is interpreted as follows: /// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by /// y captured object of BLOCK_LAYOUT_BYREF. Followed by /// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero /// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no /// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured. uint64_t CGObjCCommonMac::InlineLayoutInstruction( SmallVectorImpl<unsigned char> &Layout) { uint64_t Result = 0; if (Layout.size() <= 3) { unsigned size = Layout.size(); unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0; unsigned char inst; enum BLOCK_LAYOUT_OPCODE opcode ; switch (size) { case 3: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_STRONG) strong_word_count = (inst & 0xF)+1; else return 0; inst = Layout[1]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_BYREF) byref_word_count = (inst & 0xF)+1; else return 0; inst = Layout[2]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_WEAK) weak_word_count = (inst & 0xF)+1; else return 0; break; case 2: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_STRONG) { strong_word_count = (inst & 0xF)+1; inst = Layout[1]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_BYREF) byref_word_count = (inst & 0xF)+1; else if (opcode == BLOCK_LAYOUT_WEAK) weak_word_count = (inst & 0xF)+1; else return 0; } else if (opcode == BLOCK_LAYOUT_BYREF) { byref_word_count = (inst & 0xF)+1; inst = Layout[1]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_WEAK) weak_word_count = (inst & 0xF)+1; else return 0; } else return 0; break; case 1: inst = Layout[0]; opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_STRONG) strong_word_count = (inst & 0xF)+1; else if (opcode == BLOCK_LAYOUT_BYREF) byref_word_count = (inst & 0xF)+1; else if (opcode == BLOCK_LAYOUT_WEAK) weak_word_count = (inst & 0xF)+1; else return 0; break; default: return 0; } // Cannot inline when any of the word counts is 15. Because this is one less // than the actual work count (so 15 means 16 actual word counts), // and we can only display 0 thru 15 word counts. if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16) return 0; unsigned count = (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0); if (size == count) { if (strong_word_count) Result = strong_word_count; Result <<= 4; if (byref_word_count) Result += byref_word_count; Result <<= 4; if (weak_word_count) Result += weak_word_count; } } return Result; } llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) { llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); if (RunSkipBlockVars.empty()) return nullPtr; unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; // Sort on byte position; captures might not be allocated in order, // and unions can do funny things. llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end()); SmallVector<unsigned char, 16> Layout; unsigned size = RunSkipBlockVars.size(); for (unsigned i = 0; i < size; i++) { enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode; CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos; CharUnits end_byte_pos = start_byte_pos; unsigned j = i+1; while (j < size) { if (opcode == RunSkipBlockVars[j].opcode) { end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos; i++; } else break; } CharUnits size_in_bytes = end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size; if (j < size) { CharUnits gap = RunSkipBlockVars[j].block_var_bytepos - RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size; size_in_bytes += gap; } CharUnits residue_in_bytes = CharUnits::Zero(); if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) { residue_in_bytes = size_in_bytes % WordSizeInBytes; size_in_bytes -= residue_in_bytes; opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS; } unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes; while (size_in_words >= 16) { // Note that value in imm. is one less that the actual // value. So, 0xf means 16 words follow! unsigned char inst = (opcode << 4) | 0xf; Layout.push_back(inst); size_in_words -= 16; } if (size_in_words > 0) { // Note that value in imm. is one less that the actual // value. So, we subtract 1 away! unsigned char inst = (opcode << 4) | (size_in_words-1); Layout.push_back(inst); } if (residue_in_bytes > CharUnits::Zero()) { unsigned char inst = (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1); Layout.push_back(inst); } } while (!Layout.empty()) { unsigned char inst = Layout.back(); enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS) Layout.pop_back(); else break; } uint64_t Result = InlineLayoutInstruction(Layout); if (Result != 0) { // Block variable layout instruction has been inlined. if (CGM.getLangOpts().ObjCGCBitmapPrint) { if (ComputeByrefLayout) printf("\n Inline BYREF variable layout: "); else printf("\n Inline block variable layout: "); printf("0x0%" PRIx64 "", Result); if (auto numStrong = (Result & 0xF00) >> 8) printf(", BL_STRONG:%d", (int) numStrong); if (auto numByref = (Result & 0x0F0) >> 4) printf(", BL_BYREF:%d", (int) numByref); if (auto numWeak = (Result & 0x00F) >> 0) printf(", BL_WEAK:%d", (int) numWeak); printf(", BL_OPERATOR:0\n"); } return llvm::ConstantInt::get(CGM.IntPtrTy, Result); } unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0; Layout.push_back(inst); std::string BitMap; for (unsigned i = 0, e = Layout.size(); i != e; i++) BitMap += Layout[i]; if (CGM.getLangOpts().ObjCGCBitmapPrint) { if (ComputeByrefLayout) printf("\n Byref variable layout: "); else printf("\n Block variable layout: "); for (unsigned i = 0, e = BitMap.size(); i != e; i++) { unsigned char inst = BitMap[i]; enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4); unsigned delta = 1; switch (opcode) { case BLOCK_LAYOUT_OPERATOR: printf("BL_OPERATOR:"); delta = 0; break; case BLOCK_LAYOUT_NON_OBJECT_BYTES: printf("BL_NON_OBJECT_BYTES:"); break; case BLOCK_LAYOUT_NON_OBJECT_WORDS: printf("BL_NON_OBJECT_WORD:"); break; case BLOCK_LAYOUT_STRONG: printf("BL_STRONG:"); break; case BLOCK_LAYOUT_BYREF: printf("BL_BYREF:"); break; case BLOCK_LAYOUT_WEAK: printf("BL_WEAK:"); break; case BLOCK_LAYOUT_UNRETAINED: printf("BL_UNRETAINED:"); break; } // Actual value of word count is one more that what is in the imm. // field of the instruction printf("%d", (inst & 0xf) + delta); if (i < e-1) printf(", "); else printf("\n"); } } auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName, /*ForceNonFragileABI=*/true, /*NullTerminate=*/false); return getConstantGEP(VMContext, Entry, 0, 0); } static std::string getBlockLayoutInfoString( const SmallVectorImpl<CGObjCCommonMac::RUN_SKIP> &RunSkipBlockVars, bool HasCopyDisposeHelpers) { std::string Str; for (const CGObjCCommonMac::RUN_SKIP &R : RunSkipBlockVars) { if (R.opcode == CGObjCCommonMac::BLOCK_LAYOUT_UNRETAINED) { // Copy/dispose helpers don't have any information about // __unsafe_unretained captures, so unconditionally concatenate a string. Str += "u"; } else if (HasCopyDisposeHelpers) { // Information about __strong, __weak, or byref captures has already been // encoded into the names of the copy/dispose helpers. We have to add a // string here only when the copy/dispose helpers aren't generated (which // happens when the block is non-escaping). continue; } else { switch (R.opcode) { case CGObjCCommonMac::BLOCK_LAYOUT_STRONG: Str += "s"; break; case CGObjCCommonMac::BLOCK_LAYOUT_BYREF: Str += "r"; break; case CGObjCCommonMac::BLOCK_LAYOUT_WEAK: Str += "w"; break; default: continue; } } Str += llvm::to_string(R.block_var_bytepos.getQuantity()); Str += "l" + llvm::to_string(R.block_var_size.getQuantity()); } return Str; } void CGObjCCommonMac::fillRunSkipBlockVars(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); RunSkipBlockVars.clear(); bool hasUnion = false; unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0); unsigned ByteSizeInBits = CGM.getTarget().getCharWidth(); unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits; const BlockDecl *blockDecl = blockInfo.getBlockDecl(); // Calculate the basic layout of the block structure. const llvm::StructLayout *layout = CGM.getDataLayout().getStructLayout(blockInfo.StructureType); // Ignore the optional 'this' capture: C++ objects are not assumed // to be GC'ed. if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero()) UpdateRunSkipBlockVars(false, Qualifiers::OCL_None, blockInfo.BlockHeaderForcedGapOffset, blockInfo.BlockHeaderForcedGapSize); // Walk the captured variables. for (const auto &CI : blockDecl->captures()) { const VarDecl *variable = CI.getVariable(); QualType type = variable->getType(); const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable); // Ignore constant captures. if (capture.isConstant()) continue; CharUnits fieldOffset = CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex())); assert(!type->isArrayType() && "array variable should not be caught"); if (!CI.isByRef()) if (const RecordType *record = type->getAs<RecordType>()) { BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion); continue; } CharUnits fieldSize; if (CI.isByRef()) fieldSize = CharUnits::fromQuantity(WordSizeInBytes); else fieldSize = CGM.getContext().getTypeSizeInChars(type); UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false), fieldOffset, fieldSize); } } llvm::Constant * CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { fillRunSkipBlockVars(CGM, blockInfo); return getBitmapBlockLayout(false); } std::string CGObjCCommonMac::getRCBlockLayoutStr(CodeGenModule &CGM, const CGBlockInfo &blockInfo) { fillRunSkipBlockVars(CGM, blockInfo); return getBlockLayoutInfoString(RunSkipBlockVars, blockInfo.needsCopyDisposeHelpers(CGM.getContext())); } llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM, QualType T) { assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); assert(!T->isArrayType() && "__block array variable should not be caught"); CharUnits fieldOffset; RunSkipBlockVars.clear(); bool hasUnion = false; if (const RecordType *record = T->getAs<RecordType>()) { BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */); llvm::Constant *Result = getBitmapBlockLayout(true); if (isa<llvm::ConstantInt>(Result)) Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy); return Result; } llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy); return nullPtr; } llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF, const ObjCProtocolDecl *PD) { // FIXME: I don't understand why gcc generates this, or where it is // resolved. Investigate. Its also wasteful to look this up over and over. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD), ObjCTypes.getExternalProtocolPtrTy()); } void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) { // FIXME: We shouldn't need this, the protocol decl should contain enough // information to tell us whether this was a declaration or a definition. DefinedProtocols.insert(PD->getIdentifier()); // If we have generated a forward reference to this protocol, emit // it now. Otherwise do nothing, the protocol objects are lazily // emitted. if (Protocols.count(PD->getIdentifier())) GetOrEmitProtocol(PD); } llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) { if (DefinedProtocols.count(PD->getIdentifier())) return GetOrEmitProtocol(PD); return GetOrEmitProtocolRef(PD); } llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime( CodeGenFunction &CGF, const ObjCInterfaceDecl *ID, ObjCCommonTypesHelper &ObjCTypes) { llvm::FunctionCallee lookUpClassFn = ObjCTypes.getLookUpClassFn(); llvm::Value *className = CGF.CGM .GetAddrOfConstantCString(std::string( ID->getObjCRuntimeNameAsString())) .getPointer(); ASTContext &ctx = CGF.CGM.getContext(); className = CGF.Builder.CreateBitCast(className, CGF.ConvertType( ctx.getPointerType(ctx.CharTy.withConst()))); llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className); call->setDoesNotThrow(); return call; } /* // Objective-C 1.0 extensions struct _objc_protocol { struct _objc_protocol_extension *isa; char *protocol_name; struct _objc_protocol_list *protocol_list; struct _objc__method_prototype_list *instance_methods; struct _objc__method_prototype_list *class_methods }; See EmitProtocolExtension(). */ llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) { llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()]; // Early exit if a defining object has already been generated. if (Entry && Entry->hasInitializer()) return Entry; // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; // FIXME: I don't understand why gcc generates this, or where it is // resolved. Investigate. Its also wasteful to look this up over and over. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol")); // Construct method lists. auto methodLists = ProtocolMethodLists::get(PD); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ProtocolTy); values.add(EmitProtocolExtension(PD, methodLists)); values.add(GetClassName(PD->getObjCRuntimeNameAsString())); values.add(EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(), PD->protocol_begin(), PD->protocol_end())); values.add(methodLists.emitMethodList(this, PD, ProtocolMethodLists::RequiredInstanceMethods)); values.add(methodLists.emitMethodList(this, PD, ProtocolMethodLists::RequiredClassMethods)); if (Entry) { // Already created, update the initializer. assert(Entry->hasPrivateLinkage()); values.finishAndSetAsInitializer(Entry); } else { Entry = values.finishAndCreateGlobal("OBJC_PROTOCOL_" + PD->getName(), CGM.getPointerAlign(), /*constant*/ false, llvm::GlobalValue::PrivateLinkage); Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); Protocols[PD->getIdentifier()] = Entry; } CGM.addCompilerUsedGlobal(Entry); return Entry; } llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) { llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; if (!Entry) { // We use the initializer as a marker of whether this is a forward // reference or not. At module finalization we add the empty // contents for protocols which were referenced but never defined. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false, llvm::GlobalValue::PrivateLinkage, nullptr, "OBJC_PROTOCOL_" + PD->getName()); Entry->setSection("__OBJC,__protocol,regular,no_dead_strip"); // FIXME: Is this necessary? Why only for protocol? Entry->setAlignment(llvm::Align(4)); } return Entry; } /* struct _objc_protocol_extension { uint32_t size; struct objc_method_description_list *optional_instance_methods; struct objc_method_description_list *optional_class_methods; struct objc_property_list *instance_properties; const char ** extendedMethodTypes; struct objc_property_list *class_properties; }; */ llvm::Constant * CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD, const ProtocolMethodLists &methodLists) { auto optInstanceMethods = methodLists.emitMethodList(this, PD, ProtocolMethodLists::OptionalInstanceMethods); auto optClassMethods = methodLists.emitMethodList(this, PD, ProtocolMethodLists::OptionalClassMethods); auto extendedMethodTypes = EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(), methodLists.emitExtendedTypesArray(this), ObjCTypes); auto instanceProperties = EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD, ObjCTypes, false); auto classProperties = EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD, ObjCTypes, true); // Return null if no extension bits are used. if (optInstanceMethods->isNullValue() && optClassMethods->isNullValue() && extendedMethodTypes->isNullValue() && instanceProperties->isNullValue() && classProperties->isNullValue()) { return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy); } uint64_t size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ProtocolExtensionTy); values.addInt(ObjCTypes.IntTy, size); values.add(optInstanceMethods); values.add(optClassMethods); values.add(instanceProperties); values.add(extendedMethodTypes); values.add(classProperties); // No special section, but goes in llvm.used return CreateMetadataVar("_OBJC_PROTOCOLEXT_" + PD->getName(), values, StringRef(), CGM.getPointerAlign(), true); } /* struct objc_protocol_list { struct objc_protocol_list *next; long count; Protocol *list[]; }; */ llvm::Constant * CGObjCMac::EmitProtocolList(Twine name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end) { // Just return null for empty protocol lists if (begin == end) return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); // This field is only used by the runtime. values.addNullPointer(ObjCTypes.ProtocolListPtrTy); // Reserve a slot for the count. auto countSlot = values.addPlaceholder(); auto refsArray = values.beginArray(ObjCTypes.ProtocolPtrTy); for (; begin != end; ++begin) { refsArray.add(GetProtocolRef(*begin)); } auto count = refsArray.size(); // This list is null terminated. refsArray.addNullPointer(ObjCTypes.ProtocolPtrTy); refsArray.finishAndAddTo(values); values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count); StringRef section; if (CGM.getTriple().isOSBinFormatMachO()) section = "__OBJC,__cat_cls_meth,regular,no_dead_strip"; llvm::GlobalVariable *GV = CreateMetadataVar(name, values, section, CGM.getPointerAlign(), false); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy); } static void PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet, SmallVectorImpl<const ObjCPropertyDecl *> &Properties, const ObjCProtocolDecl *Proto, bool IsClassProperty) { for (const auto *PD : Proto->properties()) { if (IsClassProperty != PD->isClassProperty()) continue; if (!PropertySet.insert(PD->getIdentifier()).second) continue; Properties.push_back(PD); } for (const auto *P : Proto->protocols()) PushProtocolProperties(PropertySet, Properties, P, IsClassProperty); } /* struct _objc_property { const char * const name; const char * const attributes; }; struct _objc_property_list { uint32_t entsize; // sizeof (struct _objc_property) uint32_t prop_count; struct _objc_property[prop_count]; }; */ llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name, const Decl *Container, const ObjCContainerDecl *OCD, const ObjCCommonTypesHelper &ObjCTypes, bool IsClassProperty) { if (IsClassProperty) { // Make this entry NULL for OS X with deployment target < 10.11, for iOS // with deployment target < 9.0. const llvm::Triple &Triple = CGM.getTarget().getTriple(); if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) || (Triple.isiOS() && Triple.isOSVersionLT(9))) return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); } SmallVector<const ObjCPropertyDecl *, 16> Properties; llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet; if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) for (const ObjCCategoryDecl *ClassExt : OID->known_extensions()) for (auto *PD : ClassExt->properties()) { if (IsClassProperty != PD->isClassProperty()) continue; if (PD->isDirectProperty()) continue; PropertySet.insert(PD->getIdentifier()); Properties.push_back(PD); } for (const auto *PD : OCD->properties()) { if (IsClassProperty != PD->isClassProperty()) continue; // Don't emit duplicate metadata for properties that were already in a // class extension. if (!PropertySet.insert(PD->getIdentifier()).second) continue; if (PD->isDirectProperty()) continue; Properties.push_back(PD); } if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) { for (const auto *P : OID->all_referenced_protocols()) PushProtocolProperties(PropertySet, Properties, P, IsClassProperty); } else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) { for (const auto *P : CD->protocols()) PushProtocolProperties(PropertySet, Properties, P, IsClassProperty); } // Return null for empty list. if (Properties.empty()) return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy); unsigned propertySize = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); values.addInt(ObjCTypes.IntTy, propertySize); values.addInt(ObjCTypes.IntTy, Properties.size()); auto propertiesArray = values.beginArray(ObjCTypes.PropertyTy); for (auto PD : Properties) { auto property = propertiesArray.beginStruct(ObjCTypes.PropertyTy); property.add(GetPropertyName(PD->getIdentifier())); property.add(GetPropertyTypeString(PD, Container)); property.finishAndAddTo(propertiesArray); } propertiesArray.finishAndAddTo(values); StringRef Section; if (CGM.getTriple().isOSBinFormatMachO()) Section = (ObjCABI == 2) ? "__DATA, __objc_const" : "__OBJC,__property,regular,no_dead_strip"; llvm::GlobalVariable *GV = CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy); } llvm::Constant * CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name, ArrayRef<llvm::Constant*> MethodTypes, const ObjCCommonTypesHelper &ObjCTypes) { // Return null for empty list. if (MethodTypes.empty()) return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy); llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, MethodTypes.size()); llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes); StringRef Section; if (CGM.getTriple().isOSBinFormatMachO() && ObjCABI == 2) Section = "__DATA, __objc_const"; llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy); } /* struct _objc_category { char *category_name; char *class_name; struct _objc_method_list *instance_methods; struct _objc_method_list *class_methods; struct _objc_protocol_list *protocols; uint32_t size; // <rdar://4585769> struct _objc_property_list *instance_properties; struct _objc_property_list *class_properties; }; */ void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy); // FIXME: This is poor design, the OCD should have a pointer to the category // decl. Additionally, note that Category can be null for the @implementation // w/o an @interface case. Sema should just create one for us as it does for // @implementation so everyone else can live life under a clear blue sky. const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const ObjCCategoryDecl *Category = Interface->FindCategoryDeclaration(OCD->getIdentifier()); SmallString<256> ExtName; llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_' << OCD->getName(); ConstantInitBuilder Builder(CGM); auto Values = Builder.beginStruct(ObjCTypes.CategoryTy); enum { InstanceMethods, ClassMethods, NumMethodLists }; SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists]; for (const auto *MD : OCD->methods()) { if (!MD->isDirectMethod()) Methods[unsigned(MD->isClassMethod())].push_back(MD); } Values.add(GetClassName(OCD->getName())); Values.add(GetClassName(Interface->getObjCRuntimeNameAsString())); LazySymbols.insert(Interface->getIdentifier()); Values.add(emitMethodList(ExtName, MethodListType::CategoryInstanceMethods, Methods[InstanceMethods])); Values.add(emitMethodList(ExtName, MethodListType::CategoryClassMethods, Methods[ClassMethods])); if (Category) { Values.add( EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(), Category->protocol_begin(), Category->protocol_end())); } else { Values.addNullPointer(ObjCTypes.ProtocolListPtrTy); } Values.addInt(ObjCTypes.IntTy, Size); // If there is no category @interface then there can be no properties. if (Category) { Values.add(EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(), OCD, Category, ObjCTypes, false)); Values.add(EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(), OCD, Category, ObjCTypes, true)); } else { Values.addNullPointer(ObjCTypes.PropertyListPtrTy); Values.addNullPointer(ObjCTypes.PropertyListPtrTy); } llvm::GlobalVariable *GV = CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Values, "__OBJC,__category,regular,no_dead_strip", CGM.getPointerAlign(), true); DefinedCategories.push_back(GV); DefinedCategoryNames.insert(llvm::CachedHashString(ExtName)); // method definition entries must be clear for next implementation. MethodDefinitions.clear(); } enum FragileClassFlags { /// Apparently: is not a meta-class. FragileABI_Class_Factory = 0x00001, /// Is a meta-class. FragileABI_Class_Meta = 0x00002, /// Has a non-trivial constructor or destructor. FragileABI_Class_HasCXXStructors = 0x02000, /// Has hidden visibility. FragileABI_Class_Hidden = 0x20000, /// Class implementation was compiled under ARC. FragileABI_Class_CompiledByARC = 0x04000000, /// Class implementation was compiled under MRC and has MRC weak ivars. /// Exclusive with CompiledByARC. FragileABI_Class_HasMRCWeakIvars = 0x08000000, }; enum NonFragileClassFlags { /// Is a meta-class. NonFragileABI_Class_Meta = 0x00001, /// Is a root class. NonFragileABI_Class_Root = 0x00002, /// Has a non-trivial constructor or destructor. NonFragileABI_Class_HasCXXStructors = 0x00004, /// Has hidden visibility. NonFragileABI_Class_Hidden = 0x00010, /// Has the exception attribute. NonFragileABI_Class_Exception = 0x00020, /// (Obsolete) ARC-specific: this class has a .release_ivars method NonFragileABI_Class_HasIvarReleaser = 0x00040, /// Class implementation was compiled under ARC. NonFragileABI_Class_CompiledByARC = 0x00080, /// Class has non-trivial destructors, but zero-initialization is okay. NonFragileABI_Class_HasCXXDestructorOnly = 0x00100, /// Class implementation was compiled under MRC and has MRC weak ivars. /// Exclusive with CompiledByARC. NonFragileABI_Class_HasMRCWeakIvars = 0x00200, }; static bool hasWeakMember(QualType type) { if (type.getObjCLifetime() == Qualifiers::OCL_Weak) { return true; } if (auto recType = type->getAs<RecordType>()) { for (auto field : recType->getDecl()->fields()) { if (hasWeakMember(field->getType())) return true; } } return false; } /// For compatibility, we only want to set the "HasMRCWeakIvars" flag /// (and actually fill in a layout string) if we really do have any /// __weak ivars. static bool hasMRCWeakIvars(CodeGenModule &CGM, const ObjCImplementationDecl *ID) { if (!CGM.getLangOpts().ObjCWeak) return false; assert(CGM.getLangOpts().getGC() == LangOptions::NonGC); for (const ObjCIvarDecl *ivar = ID->getClassInterface()->all_declared_ivar_begin(); ivar; ivar = ivar->getNextIvar()) { if (hasWeakMember(ivar->getType())) return true; } return false; } /* struct _objc_class { Class isa; Class super_class; const char *name; long version; long info; long instance_size; struct _objc_ivar_list *ivars; struct _objc_method_list *methods; struct _objc_cache *cache; struct _objc_protocol_list *protocols; // Objective-C 1.0 extensions (<rdr://4585769>) const char *ivar_layout; struct _objc_class_ext *ext; }; See EmitClassExtension(); */ void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) { IdentifierInfo *RuntimeName = &CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString()); DefinedSymbols.insert(RuntimeName); std::string ClassName = ID->getNameAsString(); // FIXME: Gross ObjCInterfaceDecl *Interface = const_cast<ObjCInterfaceDecl*>(ID->getClassInterface()); llvm::Constant *Protocols = EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(), Interface->all_referenced_protocol_begin(), Interface->all_referenced_protocol_end()); unsigned Flags = FragileABI_Class_Factory; if (ID->hasNonZeroConstructors() || ID->hasDestructors()) Flags |= FragileABI_Class_HasCXXStructors; bool hasMRCWeak = false; if (CGM.getLangOpts().ObjCAutoRefCount) Flags |= FragileABI_Class_CompiledByARC; else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID))) Flags |= FragileABI_Class_HasMRCWeakIvars; CharUnits Size = CGM.getContext().getASTObjCImplementationLayout(ID).getSize(); // FIXME: Set CXX-structors flag. if (ID->getClassInterface()->getVisibility() == HiddenVisibility) Flags |= FragileABI_Class_Hidden; enum { InstanceMethods, ClassMethods, NumMethodLists }; SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists]; for (const auto *MD : ID->methods()) { if (!MD->isDirectMethod()) Methods[unsigned(MD->isClassMethod())].push_back(MD); } for (const auto *PID : ID->property_impls()) { if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { if (PID->getPropertyDecl()->isDirectProperty()) continue; if (ObjCMethodDecl *MD = PID->getGetterMethodDecl()) if (GetMethodDefinition(MD)) Methods[InstanceMethods].push_back(MD); if (ObjCMethodDecl *MD = PID->getSetterMethodDecl()) if (GetMethodDefinition(MD)) Methods[InstanceMethods].push_back(MD); } } ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ClassTy); values.add(EmitMetaClass(ID, Protocols, Methods[ClassMethods])); if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) { // Record a reference to the super class. LazySymbols.insert(Super->getIdentifier()); values.addBitCast(GetClassName(Super->getObjCRuntimeNameAsString()), ObjCTypes.ClassPtrTy); } else { values.addNullPointer(ObjCTypes.ClassPtrTy); } values.add(GetClassName(ID->getObjCRuntimeNameAsString())); // Version is always 0. values.addInt(ObjCTypes.LongTy, 0); values.addInt(ObjCTypes.LongTy, Flags); values.addInt(ObjCTypes.LongTy, Size.getQuantity()); values.add(EmitIvarList(ID, false)); values.add(emitMethodList(ID->getName(), MethodListType::InstanceMethods, Methods[InstanceMethods])); // cache is always NULL. values.addNullPointer(ObjCTypes.CachePtrTy); values.add(Protocols); values.add(BuildStrongIvarLayout(ID, CharUnits::Zero(), Size)); values.add(EmitClassExtension(ID, Size, hasMRCWeak, /*isMetaclass*/ false)); std::string Name("OBJC_CLASS_"); Name += ClassName; const char *Section = "__OBJC,__class,regular,no_dead_strip"; // Check for a forward reference. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); if (GV) { assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward metaclass reference has incorrect type."); values.finishAndSetAsInitializer(GV); GV->setSection(Section); GV->setAlignment(CGM.getPointerAlign().getAsAlign()); CGM.addCompilerUsedGlobal(GV); } else GV = CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true); DefinedClasses.push_back(GV); ImplementedClasses.push_back(Interface); // method definition entries must be clear for next implementation. MethodDefinitions.clear(); } llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID, llvm::Constant *Protocols, ArrayRef<const ObjCMethodDecl*> Methods) { unsigned Flags = FragileABI_Class_Meta; unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy); if (ID->getClassInterface()->getVisibility() == HiddenVisibility) Flags |= FragileABI_Class_Hidden; ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ClassTy); // The isa for the metaclass is the root of the hierarchy. const ObjCInterfaceDecl *Root = ID->getClassInterface(); while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) Root = Super; values.addBitCast(GetClassName(Root->getObjCRuntimeNameAsString()), ObjCTypes.ClassPtrTy); // The super class for the metaclass is emitted as the name of the // super class. The runtime fixes this up to point to the // *metaclass* for the super class. if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) { values.addBitCast(GetClassName(Super->getObjCRuntimeNameAsString()), ObjCTypes.ClassPtrTy); } else { values.addNullPointer(ObjCTypes.ClassPtrTy); } values.add(GetClassName(ID->getObjCRuntimeNameAsString())); // Version is always 0. values.addInt(ObjCTypes.LongTy, 0); values.addInt(ObjCTypes.LongTy, Flags); values.addInt(ObjCTypes.LongTy, Size); values.add(EmitIvarList(ID, true)); values.add(emitMethodList(ID->getName(), MethodListType::ClassMethods, Methods)); // cache is always NULL. values.addNullPointer(ObjCTypes.CachePtrTy); values.add(Protocols); // ivar_layout for metaclass is always NULL. values.addNullPointer(ObjCTypes.Int8PtrTy); // The class extension is used to store class properties for metaclasses. values.add(EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/, /*isMetaclass*/true)); std::string Name("OBJC_METACLASS_"); Name += ID->getName(); // Check for a forward reference. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); if (GV) { assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward metaclass reference has incorrect type."); values.finishAndSetAsInitializer(GV); } else { GV = values.finishAndCreateGlobal(Name, CGM.getPointerAlign(), /*constant*/ false, llvm::GlobalValue::PrivateLinkage); } GV->setSection("__OBJC,__meta_class,regular,no_dead_strip"); CGM.addCompilerUsedGlobal(GV); return GV; } llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) { std::string Name = "OBJC_METACLASS_" + ID->getNameAsString(); // FIXME: Should we look these up somewhere other than the module. Its a bit // silly since we only generate these while processing an implementation, so // exactly one pointer would work if know when we entered/exitted an // implementation block. // Check for an existing forward reference. // Previously, metaclass with internal linkage may have been defined. // pass 'true' as 2nd argument so it is returned. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); if (!GV) GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false, llvm::GlobalValue::PrivateLinkage, nullptr, Name); assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward metaclass reference has incorrect type."); return GV; } llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) { std::string Name = "OBJC_CLASS_" + ID->getNameAsString(); llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true); if (!GV) GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false, llvm::GlobalValue::PrivateLinkage, nullptr, Name); assert(GV->getType()->getElementType() == ObjCTypes.ClassTy && "Forward class metadata reference has incorrect type."); return GV; } /* Emit a "class extension", which in this specific context means extra data that doesn't fit in the normal fragile-ABI class structure, and has nothing to do with the language concept of a class extension. struct objc_class_ext { uint32_t size; const char *weak_ivar_layout; struct _objc_property_list *properties; }; */ llvm::Constant * CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID, CharUnits InstanceSize, bool hasMRCWeakIvars, bool isMetaclass) { // Weak ivar layout. llvm::Constant *layout; if (isMetaclass) { layout = llvm::ConstantPointerNull::get(CGM.Int8PtrTy); } else { layout = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize, hasMRCWeakIvars); } // Properties. llvm::Constant *propertyList = EmitPropertyList((isMetaclass ? Twine("_OBJC_$_CLASS_PROP_LIST_") : Twine("_OBJC_$_PROP_LIST_")) + ID->getName(), ID, ID->getClassInterface(), ObjCTypes, isMetaclass); // Return null if no extension bits are used. if (layout->isNullValue() && propertyList->isNullValue()) { return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy); } uint64_t size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ClassExtensionTy); values.addInt(ObjCTypes.IntTy, size); values.add(layout); values.add(propertyList); return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), values, "__OBJC,__class_ext,regular,no_dead_strip", CGM.getPointerAlign(), true); } /* struct objc_ivar { char *ivar_name; char *ivar_type; int ivar_offset; }; struct objc_ivar_list { int ivar_count; struct objc_ivar list[count]; }; */ llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID, bool ForClass) { // When emitting the root class GCC emits ivar entries for the // actual class structure. It is not clear if we need to follow this // behavior; for now lets try and get away with not doing it. If so, // the cleanest solution would be to make up an ObjCInterfaceDecl // for the class. if (ForClass) return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); const ObjCInterfaceDecl *OID = ID->getClassInterface(); ConstantInitBuilder builder(CGM); auto ivarList = builder.beginStruct(); auto countSlot = ivarList.addPlaceholder(); auto ivars = ivarList.beginArray(ObjCTypes.IvarTy); for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) continue; auto ivar = ivars.beginStruct(ObjCTypes.IvarTy); ivar.add(GetMethodVarName(IVD->getIdentifier())); ivar.add(GetMethodVarType(IVD)); ivar.addInt(ObjCTypes.IntTy, ComputeIvarBaseOffset(CGM, OID, IVD)); ivar.finishAndAddTo(ivars); } // Return null for empty list. auto count = ivars.size(); if (count == 0) { ivars.abandon(); ivarList.abandon(); return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy); } ivars.finishAndAddTo(ivarList); ivarList.fillPlaceholderWithInt(countSlot, ObjCTypes.IntTy, count); llvm::GlobalVariable *GV; if (ForClass) GV = CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), ivarList, "__OBJC,__class_vars,regular,no_dead_strip", CGM.getPointerAlign(), true); else GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), ivarList, "__OBJC,__instance_vars,regular,no_dead_strip", CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy); } /// Build a struct objc_method_description constant for the given method. /// /// struct objc_method_description { /// SEL method_name; /// char *method_types; /// }; void CGObjCMac::emitMethodDescriptionConstant(ConstantArrayBuilder &builder, const ObjCMethodDecl *MD) { auto description = builder.beginStruct(ObjCTypes.MethodDescriptionTy); description.addBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); description.add(GetMethodVarType(MD)); description.finishAndAddTo(builder); } /// Build a struct objc_method constant for the given method. /// /// struct objc_method { /// SEL method_name; /// char *method_types; /// void *method; /// }; void CGObjCMac::emitMethodConstant(ConstantArrayBuilder &builder, const ObjCMethodDecl *MD) { llvm::Function *fn = GetMethodDefinition(MD); assert(fn && "no definition registered for method"); auto method = builder.beginStruct(ObjCTypes.MethodTy); method.addBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); method.add(GetMethodVarType(MD)); method.addBitCast(fn, ObjCTypes.Int8PtrTy); method.finishAndAddTo(builder); } /// Build a struct objc_method_list or struct objc_method_description_list, /// as appropriate. /// /// struct objc_method_list { /// struct objc_method_list *obsolete; /// int count; /// struct objc_method methods_list[count]; /// }; /// /// struct objc_method_description_list { /// int count; /// struct objc_method_description list[count]; /// }; llvm::Constant *CGObjCMac::emitMethodList(Twine name, MethodListType MLT, ArrayRef<const ObjCMethodDecl *> methods) { StringRef prefix; StringRef section; bool forProtocol = false; switch (MLT) { case MethodListType::CategoryInstanceMethods: prefix = "OBJC_CATEGORY_INSTANCE_METHODS_"; section = "__OBJC,__cat_inst_meth,regular,no_dead_strip"; forProtocol = false; break; case MethodListType::CategoryClassMethods: prefix = "OBJC_CATEGORY_CLASS_METHODS_"; section = "__OBJC,__cat_cls_meth,regular,no_dead_strip"; forProtocol = false; break; case MethodListType::InstanceMethods: prefix = "OBJC_INSTANCE_METHODS_"; section = "__OBJC,__inst_meth,regular,no_dead_strip"; forProtocol = false; break; case MethodListType::ClassMethods: prefix = "OBJC_CLASS_METHODS_"; section = "__OBJC,__cls_meth,regular,no_dead_strip"; forProtocol = false; break; case MethodListType::ProtocolInstanceMethods: prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_"; section = "__OBJC,__cat_inst_meth,regular,no_dead_strip"; forProtocol = true; break; case MethodListType::ProtocolClassMethods: prefix = "OBJC_PROTOCOL_CLASS_METHODS_"; section = "__OBJC,__cat_cls_meth,regular,no_dead_strip"; forProtocol = true; break; case MethodListType::OptionalProtocolInstanceMethods: prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"; section = "__OBJC,__cat_inst_meth,regular,no_dead_strip"; forProtocol = true; break; case MethodListType::OptionalProtocolClassMethods: prefix = "OBJC_PROTOCOL_CLASS_METHODS_OPT_"; section = "__OBJC,__cat_cls_meth,regular,no_dead_strip"; forProtocol = true; break; } // Return null for empty list. if (methods.empty()) return llvm::Constant::getNullValue(forProtocol ? ObjCTypes.MethodDescriptionListPtrTy : ObjCTypes.MethodListPtrTy); // For protocols, this is an objc_method_description_list, which has // a slightly different structure. if (forProtocol) { ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); values.addInt(ObjCTypes.IntTy, methods.size()); auto methodArray = values.beginArray(ObjCTypes.MethodDescriptionTy); for (auto MD : methods) { emitMethodDescriptionConstant(methodArray, MD); } methodArray.finishAndAddTo(values); llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section, CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodDescriptionListPtrTy); } // Otherwise, it's an objc_method_list. ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); values.addNullPointer(ObjCTypes.Int8PtrTy); values.addInt(ObjCTypes.IntTy, methods.size()); auto methodArray = values.beginArray(ObjCTypes.MethodTy); for (auto MD : methods) { if (!MD->isDirectMethod()) emitMethodConstant(methodArray, MD); } methodArray.finishAndAddTo(values); llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section, CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy); } llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD) { llvm::Function *Method; if (OMD->isDirectMethod()) { Method = GenerateDirectMethod(OMD, CD); } else { SmallString<256> Name; GetNameForMethod(OMD, CD, Name); CodeGenTypes &Types = CGM.getTypes(); llvm::FunctionType *MethodTy = Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD)); Method = llvm::Function::Create(MethodTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule()); } MethodDefinitions.insert(std::make_pair(OMD, Method)); return Method; } llvm::Function * CGObjCCommonMac::GenerateDirectMethod(const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD) { auto I = DirectMethodDefinitions.find(OMD->getCanonicalDecl()); if (I != DirectMethodDefinitions.end()) return I->second; SmallString<256> Name; GetNameForMethod(OMD, CD, Name, /*ignoreCategoryNamespace*/true); CodeGenTypes &Types = CGM.getTypes(); llvm::FunctionType *MethodTy = Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD)); llvm::Function *Method = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage, Name.str(), &CGM.getModule()); DirectMethodDefinitions.insert(std::make_pair(OMD->getCanonicalDecl(), Method)); return Method; } void CGObjCCommonMac::GenerateDirectMethodPrologue( CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD, const ObjCContainerDecl *CD) { auto &Builder = CGF.Builder; bool ReceiverCanBeNull = true; auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl()); auto selfValue = Builder.CreateLoad(selfAddr); // Generate: // // /* for class methods only to force class lazy initialization */ // self = [self self]; // // /* unless the receiver is never NULL */ // if (self == nil) { // return (ReturnType){ }; // } // // _cmd = @selector(...) // ... if (OMD->isClassMethod()) { const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD); assert(OID && "GenerateDirectMethod() should be called with the Class Interface"); Selector SelfSel = GetNullarySelector("self", CGM.getContext()); auto ResultType = CGF.getContext().getObjCIdType(); RValue result; CallArgList Args; // TODO: If this method is inlined, the caller might know that `self` is // already initialized; for example, it might be an ordinary Objective-C // method which always receives an initialized `self`, or it might have just // forced initialization on its own. // // We should find a way to eliminate this unnecessary initialization in such // cases in LLVM. result = GeneratePossiblySpecializedMessageSend( CGF, ReturnValueSlot(), ResultType, SelfSel, selfValue, Args, OID, nullptr, true); Builder.CreateStore(result.getScalarVal(), selfAddr); // Nullable `Class` expressions cannot be messaged with a direct method // so the only reason why the receive can be null would be because // of weak linking. ReceiverCanBeNull = isWeakLinkedClass(OID); } if (ReceiverCanBeNull) { llvm::BasicBlock *SelfIsNilBlock = CGF.createBasicBlock("objc_direct_method.self_is_nil"); llvm::BasicBlock *ContBlock = CGF.createBasicBlock("objc_direct_method.cont"); // if (self == nil) { auto selfTy = cast<llvm::PointerType>(selfValue->getType()); auto Zero = llvm::ConstantPointerNull::get(selfTy); llvm::MDBuilder MDHelper(CGM.getLLVMContext()); Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero), SelfIsNilBlock, ContBlock, MDHelper.createBranchWeights(1, 1 << 20)); CGF.EmitBlock(SelfIsNilBlock); // return (ReturnType){ }; auto retTy = OMD->getReturnType(); Builder.SetInsertPoint(SelfIsNilBlock); if (!retTy->isVoidType()) { CGF.EmitNullInitialization(CGF.ReturnValue, retTy); } CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); // } // rest of the body CGF.EmitBlock(ContBlock); Builder.SetInsertPoint(ContBlock); } // only synthesize _cmd if it's referenced if (OMD->getCmdDecl()->isUsed()) { Builder.CreateStore(GetSelector(CGF, OMD), CGF.GetAddrOfLocalVar(OMD->getCmdDecl())); } } llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name, ConstantStructBuilder &Init, StringRef Section, CharUnits Align, bool AddToUsed) { llvm::GlobalValue::LinkageTypes LT = getLinkageTypeForObjCMetadata(CGM, Section); llvm::GlobalVariable *GV = Init.finishAndCreateGlobal(Name, Align, /*constant*/ false, LT); if (!Section.empty()) GV->setSection(Section); if (AddToUsed) CGM.addCompilerUsedGlobal(GV); return GV; } llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name, llvm::Constant *Init, StringRef Section, CharUnits Align, bool AddToUsed) { llvm::Type *Ty = Init->getType(); llvm::GlobalValue::LinkageTypes LT = getLinkageTypeForObjCMetadata(CGM, Section); llvm::GlobalVariable *GV = new llvm::GlobalVariable(CGM.getModule(), Ty, false, LT, Init, Name); if (!Section.empty()) GV->setSection(Section); GV->setAlignment(Align.getAsAlign()); if (AddToUsed) CGM.addCompilerUsedGlobal(GV); return GV; } llvm::GlobalVariable * CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type, bool ForceNonFragileABI, bool NullTerminate) { StringRef Label; switch (Type) { case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break; case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break; case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break; case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break; } bool NonFragile = ForceNonFragileABI || isNonFragileABI(); StringRef Section; switch (Type) { case ObjCLabelType::ClassName: Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals" : "__TEXT,__cstring,cstring_literals"; break; case ObjCLabelType::MethodVarName: Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals" : "__TEXT,__cstring,cstring_literals"; break; case ObjCLabelType::MethodVarType: Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals" : "__TEXT,__cstring,cstring_literals"; break; case ObjCLabelType::PropertyName: Section = "__TEXT,__cstring,cstring_literals"; break; } llvm::Constant *Value = llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate); llvm::GlobalVariable *GV = new llvm::GlobalVariable(CGM.getModule(), Value->getType(), /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Value, Label); if (CGM.getTriple().isOSBinFormatMachO()) GV->setSection(Section); GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); GV->setAlignment(CharUnits::One().getAsAlign()); CGM.addCompilerUsedGlobal(GV); return GV; } llvm::Function *CGObjCMac::ModuleInitFunction() { // Abuse this interface function as a place to finalize. FinishModule(); return nullptr; } llvm::FunctionCallee CGObjCMac::GetPropertyGetFunction() { return ObjCTypes.getGetPropertyFn(); } llvm::FunctionCallee CGObjCMac::GetPropertySetFunction() { return ObjCTypes.getSetPropertyFn(); } llvm::FunctionCallee CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, bool copy) { return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy); } llvm::FunctionCallee CGObjCMac::GetGetStructFunction() { return ObjCTypes.getCopyStructFn(); } llvm::FunctionCallee CGObjCMac::GetSetStructFunction() { return ObjCTypes.getCopyStructFn(); } llvm::FunctionCallee CGObjCMac::GetCppAtomicObjectGetFunction() { return ObjCTypes.getCppAtomicObjectFunction(); } llvm::FunctionCallee CGObjCMac::GetCppAtomicObjectSetFunction() { return ObjCTypes.getCppAtomicObjectFunction(); } llvm::FunctionCallee CGObjCMac::EnumerationMutationFunction() { return ObjCTypes.getEnumerationMutationFn(); } void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) { return EmitTryOrSynchronizedStmt(CGF, S); } void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S) { return EmitTryOrSynchronizedStmt(CGF, S); } namespace { struct PerformFragileFinally final : EHScopeStack::Cleanup { const Stmt &S; Address SyncArgSlot; Address CallTryExitVar; Address ExceptionData; ObjCTypesHelper &ObjCTypes; PerformFragileFinally(const Stmt *S, Address SyncArgSlot, Address CallTryExitVar, Address ExceptionData, ObjCTypesHelper *ObjCTypes) : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar), ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {} void Emit(CodeGenFunction &CGF, Flags flags) override { // Check whether we need to call objc_exception_try_exit. // In optimized code, this branch will always be folded. llvm::BasicBlock *FinallyCallExit = CGF.createBasicBlock("finally.call_exit"); llvm::BasicBlock *FinallyNoCallExit = CGF.createBasicBlock("finally.no_call_exit"); CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar), FinallyCallExit, FinallyNoCallExit); CGF.EmitBlock(FinallyCallExit); CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData.getPointer()); CGF.EmitBlock(FinallyNoCallExit); if (isa<ObjCAtTryStmt>(S)) { if (const ObjCAtFinallyStmt* FinallyStmt = cast<ObjCAtTryStmt>(S).getFinallyStmt()) { // Don't try to do the @finally if this is an EH cleanup. if (flags.isForEHCleanup()) return; // Save the current cleanup destination in case there's // control flow inside the finally statement. llvm::Value *CurCleanupDest = CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot()); CGF.EmitStmt(FinallyStmt->getFinallyBody()); if (CGF.HaveInsertPoint()) { CGF.Builder.CreateStore(CurCleanupDest, CGF.getNormalCleanupDestSlot()); } else { // Currently, the end of the cleanup must always exist. CGF.EnsureInsertPoint(); } } } else { // Emit objc_sync_exit(expr); as finally's sole statement for // @synchronized. llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot); CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg); } } }; class FragileHazards { CodeGenFunction &CGF; SmallVector<llvm::Value*, 20> Locals; llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry; llvm::InlineAsm *ReadHazard; llvm::InlineAsm *WriteHazard; llvm::FunctionType *GetAsmFnType(); void collectLocals(); void emitReadHazard(CGBuilderTy &Builder); public: FragileHazards(CodeGenFunction &CGF); void emitWriteHazard(); void emitHazardsInNewBlocks(); }; } // end anonymous namespace /// Create the fragile-ABI read and write hazards based on the current /// state of the function, which is presumed to be immediately prior /// to a @try block. These hazards are used to maintain correct /// semantics in the face of optimization and the fragile ABI's /// cavalier use of setjmp/longjmp. FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) { collectLocals(); if (Locals.empty()) return; // Collect all the blocks in the function. for (llvm::Function::iterator I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I) BlocksBeforeTry.insert(&*I); llvm::FunctionType *AsmFnTy = GetAsmFnType(); // Create a read hazard for the allocas. This inhibits dead-store // optimizations and forces the values to memory. This hazard is // inserted before any 'throwing' calls in the protected scope to // reflect the possibility that the variables might be read from the // catch block if the call throws. { std::string Constraint; for (unsigned I = 0, E = Locals.size(); I != E; ++I) { if (I) Constraint += ','; Constraint += "*m"; } ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false); } // Create a write hazard for the allocas. This inhibits folding // loads across the hazard. This hazard is inserted at the // beginning of the catch path to reflect the possibility that the // variables might have been written within the protected scope. { std::string Constraint; for (unsigned I = 0, E = Locals.size(); I != E; ++I) { if (I) Constraint += ','; Constraint += "=*m"; } WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false); } } /// Emit a write hazard at the current location. void FragileHazards::emitWriteHazard() { if (Locals.empty()) return; CGF.EmitNounwindRuntimeCall(WriteHazard, Locals); } void FragileHazards::emitReadHazard(CGBuilderTy &Builder) { assert(!Locals.empty()); llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals); call->setDoesNotThrow(); call->setCallingConv(CGF.getRuntimeCC()); } /// Emit read hazards in all the protected blocks, i.e. all the blocks /// which have been inserted since the beginning of the try. void FragileHazards::emitHazardsInNewBlocks() { if (Locals.empty()) return; CGBuilderTy Builder(CGF, CGF.getLLVMContext()); // Iterate through all blocks, skipping those prior to the try. for (llvm::Function::iterator FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) { llvm::BasicBlock &BB = *FI; if (BlocksBeforeTry.count(&BB)) continue; // Walk through all the calls in the block. for (llvm::BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) { llvm::Instruction &I = *BI; // Ignore instructions that aren't non-intrinsic calls. // These are the only calls that can possibly call longjmp. if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue; if (isa<llvm::IntrinsicInst>(I)) continue; // Ignore call sites marked nounwind. This may be questionable, // since 'nounwind' doesn't necessarily mean 'does not call longjmp'. if (cast<llvm::CallBase>(I).doesNotThrow()) continue; // Insert a read hazard before the call. This will ensure that // any writes to the locals are performed before making the // call. If the call throws, then this is sufficient to // guarantee correctness as long as it doesn't also write to any // locals. Builder.SetInsertPoint(&BB, BI); emitReadHazard(Builder); } } } static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) { if (V.isValid()) S.insert(V.getPointer()); } void FragileHazards::collectLocals() { // Compute a set of allocas to ignore. llvm::DenseSet<llvm::Value*> AllocasToIgnore; addIfPresent(AllocasToIgnore, CGF.ReturnValue); addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest); // Collect all the allocas currently in the function. This is // probably way too aggressive. llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock(); for (llvm::BasicBlock::iterator I = Entry.begin(), E = Entry.end(); I != E; ++I) if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I)) Locals.push_back(&*I); } llvm::FunctionType *FragileHazards::GetAsmFnType() { SmallVector<llvm::Type *, 16> tys(Locals.size()); for (unsigned i = 0, e = Locals.size(); i != e; ++i) tys[i] = Locals[i]->getType(); return llvm::FunctionType::get(CGF.VoidTy, tys, false); } /* Objective-C setjmp-longjmp (sjlj) Exception Handling -- A catch buffer is a setjmp buffer plus: - a pointer to the exception that was caught - a pointer to the previous exception data buffer - two pointers of reserved storage Therefore catch buffers form a stack, with a pointer to the top of the stack kept in thread-local storage. objc_exception_try_enter pushes a catch buffer onto the EH stack. objc_exception_try_exit pops the given catch buffer, which is required to be the top of the EH stack. objc_exception_throw pops the top of the EH stack, writes the thrown exception into the appropriate field, and longjmps to the setjmp buffer. It crashes the process (with a printf and an abort()) if there are no catch buffers on the stack. objc_exception_extract just reads the exception pointer out of the catch buffer. There's no reason an implementation couldn't use a light-weight setjmp here --- something like __builtin_setjmp, but API-compatible with the heavyweight setjmp. This will be more important if we ever want to implement correct ObjC/C++ exception interactions for the fragile ABI. Note that for this use of setjmp/longjmp to be correct, we may need to mark some local variables volatile: if a non-volatile local variable is modified between the setjmp and the longjmp, it has indeterminate value. For the purposes of LLVM IR, it may be sufficient to make loads and stores within the @try (to variables declared outside the @try) volatile. This is necessary for optimized correctness, but is not currently being done; this is being tracked as rdar://problem/8160285 The basic framework for a @try-catch-finally is as follows: { objc_exception_data d; id _rethrow = null; bool _call_try_exit = true; objc_exception_try_enter(&d); if (!setjmp(d.jmp_buf)) { ... try body ... } else { // exception path id _caught = objc_exception_extract(&d); // enter new try scope for handlers if (!setjmp(d.jmp_buf)) { ... match exception and execute catch blocks ... // fell off end, rethrow. _rethrow = _caught; ... jump-through-finally to finally_rethrow ... } else { // exception in catch block _rethrow = objc_exception_extract(&d); _call_try_exit = false; ... jump-through-finally to finally_rethrow ... } } ... jump-through-finally to finally_end ... finally: if (_call_try_exit) objc_exception_try_exit(&d); ... finally block .... ... dispatch to finally destination ... finally_rethrow: objc_exception_throw(_rethrow); finally_end: } This framework differs slightly from the one gcc uses, in that gcc uses _rethrow to determine if objc_exception_try_exit should be called and if the object should be rethrown. This breaks in the face of throwing nil and introduces unnecessary branches. We specialize this framework for a few particular circumstances: - If there are no catch blocks, then we avoid emitting the second exception handling context. - If there is a catch-all catch block (i.e. @catch(...) or @catch(id e)) we avoid emitting the code to rethrow an uncaught exception. - FIXME: If there is no @finally block we can do a few more simplifications. Rethrows and Jumps-Through-Finally -- '@throw;' is supported by pushing the currently-caught exception onto ObjCEHStack while the @catch blocks are emitted. Branches through the @finally block are handled with an ordinary normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC exceptions are not compatible with C++ exceptions, and this is hardly the only place where this will go wrong. @synchronized(expr) { stmt; } is emitted as if it were: id synch_value = expr; objc_sync_enter(synch_value); @try { stmt; } @finally { objc_sync_exit(synch_value); } */ void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S) { bool isTry = isa<ObjCAtTryStmt>(S); // A destination for the fall-through edges of the catch handlers to // jump to. CodeGenFunction::JumpDest FinallyEnd = CGF.getJumpDestInCurrentScope("finally.end"); // A destination for the rethrow edge of the catch handlers to jump // to. CodeGenFunction::JumpDest FinallyRethrow = CGF.getJumpDestInCurrentScope("finally.rethrow"); // For @synchronized, call objc_sync_enter(sync.expr). The // evaluation of the expression must occur before we enter the // @synchronized. We can't avoid a temp here because we need the // value to be preserved. If the backend ever does liveness // correctly after setjmp, this will be unnecessary. Address SyncArgSlot = Address::invalid(); if (!isTry) { llvm::Value *SyncArg = CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr()); SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy); CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg); SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), CGF.getPointerAlign(), "sync.arg"); CGF.Builder.CreateStore(SyncArg, SyncArgSlot); } // Allocate memory for the setjmp buffer. This needs to be kept // live throughout the try and catch blocks. Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy, CGF.getPointerAlign(), "exceptiondata.ptr"); // Create the fragile hazards. Note that this will not capture any // of the allocas required for exception processing, but will // capture the current basic block (which extends all the way to the // setjmp call) as "before the @try". FragileHazards Hazards(CGF); // Create a flag indicating whether the cleanup needs to call // objc_exception_try_exit. This is true except when // - no catches match and we're branching through the cleanup // just to rethrow the exception, or // - a catch matched and we're falling out of the catch handler. // The setjmp-safety rule here is that we should always store to this // variable in a place that dominates the branch through the cleanup // without passing through any setjmps. Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(), "_call_try_exit"); // A slot containing the exception to rethrow. Only needed when we // have both a @catch and a @finally. Address PropagatingExnVar = Address::invalid(); // Push a normal cleanup to leave the try scope. CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S, SyncArgSlot, CallTryExitVar, ExceptionData, &ObjCTypes); // Enter a try block: // - Call objc_exception_try_enter to push ExceptionData on top of // the EH stack. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData.getPointer()); // - Call setjmp on the exception data buffer. llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0); llvm::Value *GEPIndexes[] = { Zero, Zero, Zero }; llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP( ObjCTypes.ExceptionDataTy, ExceptionData.getPointer(), GEPIndexes, "setjmp_buffer"); llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall( ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result"); SetJmpResult->setCanReturnTwice(); // If setjmp returned 0, enter the protected block; otherwise, // branch to the handler. llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try"); llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler"); llvm::Value *DidCatch = CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception"); CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock); // Emit the protected block. CGF.EmitBlock(TryBlock); CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar); CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody() : cast<ObjCAtSynchronizedStmt>(S).getSynchBody()); CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP(); // Emit the exception handler block. CGF.EmitBlock(TryHandler); // Don't optimize loads of the in-scope locals across this point. Hazards.emitWriteHazard(); // For a @synchronized (or a @try with no catches), just branch // through the cleanup to the rethrow block. if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) { // Tell the cleanup not to re-pop the exit. CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar); CGF.EmitBranchThroughCleanup(FinallyRethrow); // Otherwise, we have to match against the caught exceptions. } else { // Retrieve the exception object. We may emit multiple blocks but // nothing can cross this so the value is already in SSA form. llvm::CallInst *Caught = CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(), ExceptionData.getPointer(), "caught"); // Push the exception to rethrow onto the EH value stack for the // benefit of any @throws in the handlers. CGF.ObjCEHValueStack.push_back(Caught); const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S); bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr); llvm::BasicBlock *CatchBlock = nullptr; llvm::BasicBlock *CatchHandler = nullptr; if (HasFinally) { // Save the currently-propagating exception before // objc_exception_try_enter clears the exception slot. PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(), CGF.getPointerAlign(), "propagating_exception"); CGF.Builder.CreateStore(Caught, PropagatingExnVar); // Enter a new exception try block (in case a @catch block // throws an exception). CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData.getPointer()); llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp.result"); SetJmpResult->setCanReturnTwice(); llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception"); CatchBlock = CGF.createBasicBlock("catch"); CatchHandler = CGF.createBasicBlock("catch_for_catch"); CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock); CGF.EmitBlock(CatchBlock); } CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar); // Handle catch list. As a special case we check if everything is // matched and avoid generating code for falling off the end if // so. bool AllMatched = false; for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) { const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I); const VarDecl *CatchParam = CatchStmt->getCatchParamDecl(); const ObjCObjectPointerType *OPT = nullptr; // catch(...) always matches. if (!CatchParam) { AllMatched = true; } else { OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>(); // catch(id e) always matches under this ABI, since only // ObjC exceptions end up here in the first place. // FIXME: For the time being we also match id<X>; this should // be rejected by Sema instead. if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType())) AllMatched = true; } // If this is a catch-all, we don't need to test anything. if (AllMatched) { CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF); if (CatchParam) { CGF.EmitAutoVarDecl(*CatchParam); assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); // These types work out because ConvertType(id) == i8*. EmitInitOfCatchParam(CGF, Caught, CatchParam); } CGF.EmitStmt(CatchStmt->getCatchBody()); // The scope of the catch variable ends right here. CatchVarCleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(FinallyEnd); break; } assert(OPT && "Unexpected non-object pointer type in @catch"); const ObjCObjectType *ObjTy = OPT->getObjectType(); // FIXME: @catch (Class c) ? ObjCInterfaceDecl *IDecl = ObjTy->getInterface(); assert(IDecl && "Catch parameter must have Objective-C type!"); // Check if the @catch block matches the exception object. llvm::Value *Class = EmitClassRef(CGF, IDecl); llvm::Value *matchArgs[] = { Class, Caught }; llvm::CallInst *Match = CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(), matchArgs, "match"); llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match"); llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next"); CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"), MatchedBlock, NextCatchBlock); // Emit the @catch block. CGF.EmitBlock(MatchedBlock); // Collect any cleanups for the catch variable. The scope lasts until // the end of the catch body. CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF); CGF.EmitAutoVarDecl(*CatchParam); assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?"); // Initialize the catch variable. llvm::Value *Tmp = CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType())); EmitInitOfCatchParam(CGF, Tmp, CatchParam); CGF.EmitStmt(CatchStmt->getCatchBody()); // We're done with the catch variable. CatchVarCleanups.ForceCleanup(); CGF.EmitBranchThroughCleanup(FinallyEnd); CGF.EmitBlock(NextCatchBlock); } CGF.ObjCEHValueStack.pop_back(); // If nothing wanted anything to do with the caught exception, // kill the extract call. if (Caught->use_empty()) Caught->eraseFromParent(); if (!AllMatched) CGF.EmitBranchThroughCleanup(FinallyRethrow); if (HasFinally) { // Emit the exception handler for the @catch blocks. CGF.EmitBlock(CatchHandler); // In theory we might now need a write hazard, but actually it's // unnecessary because there's no local-accessing code between // the try's write hazard and here. //Hazards.emitWriteHazard(); // Extract the new exception and save it to the // propagating-exception slot. assert(PropagatingExnVar.isValid()); llvm::CallInst *NewCaught = CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(), ExceptionData.getPointer(), "caught"); CGF.Builder.CreateStore(NewCaught, PropagatingExnVar); // Don't pop the catch handler; the throw already did. CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar); CGF.EmitBranchThroughCleanup(FinallyRethrow); } } // Insert read hazards as required in the new blocks. Hazards.emitHazardsInNewBlocks(); // Pop the cleanup. CGF.Builder.restoreIP(TryFallthroughIP); if (CGF.HaveInsertPoint()) CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar); CGF.PopCleanupBlock(); CGF.EmitBlock(FinallyEnd.getBlock(), true); // Emit the rethrow block. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP(); CGF.EmitBlock(FinallyRethrow.getBlock(), true); if (CGF.HaveInsertPoint()) { // If we have a propagating-exception variable, check it. llvm::Value *PropagatingExn; if (PropagatingExnVar.isValid()) { PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar); // Otherwise, just look in the buffer for the exception to throw. } else { llvm::CallInst *Caught = CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(), ExceptionData.getPointer()); PropagatingExn = Caught; } CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(), PropagatingExn); CGF.Builder.CreateUnreachable(); } CGF.Builder.restoreIP(SavedIP); } void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint) { llvm::Value *ExceptionAsObject; if (const Expr *ThrowExpr = S.getThrowExpr()) { llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); ExceptionAsObject = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy); } else { assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && "Unexpected rethrow outside @catch block."); ExceptionAsObject = CGF.ObjCEHValueStack.back(); } CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject) ->setDoesNotReturn(); CGF.Builder.CreateUnreachable(); // Clear the insertion point to indicate we are in unreachable code. if (ClearInsertionPoint) CGF.Builder.ClearInsertionPoint(); } /// EmitObjCWeakRead - Code gen for loading value of a __weak /// object: objc_read_weak (id *src) /// llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, Address AddrWeakObj) { llvm::Type* DestTy = AddrWeakObj.getElementType(); AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); llvm::Value *read_weak = CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(), AddrWeakObj.getPointer(), "weakread"); read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); return read_weak; } /// EmitObjCWeakAssign - Code gen for assigning to a __weak object. /// objc_assign_weak (id src, id *dst) /// void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty) : CGF.Builder.CreateBitCast(src, CGM.Int64Ty); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer() }; CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(), args, "weakassign"); } /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. /// objc_assign_global (id src, id *dst) /// void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst, bool threadlocal) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty) : CGF.Builder.CreateBitCast(src, CGM.Int64Ty); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer() }; if (!threadlocal) CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(), args, "globalassign"); else CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(), args, "threadlocalassign"); } /// EmitObjCIvarAssign - Code gen for assigning to a __strong object. /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset) /// void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst, llvm::Value *ivarOffset) { assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL"); llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty) : CGF.Builder.CreateBitCast(src, CGM.Int64Ty); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer(), ivarOffset }; CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args); } /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. /// objc_assign_strongCast (id src, id *dst) /// void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty) : CGF.Builder.CreateBitCast(src, CGM.Int64Ty); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer() }; CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(), args, "strongassign"); } void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, Address DestPtr, Address SrcPtr, llvm::Value *size) { SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy); DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy); llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), size }; CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args); } /// EmitObjCValueForIvar - Code Gen for ivar reference. /// LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers) { const ObjCInterfaceDecl *ID = ObjectTy->castAs<ObjCObjectType>()->getInterface(); return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, EmitIvarOffset(CGF, ID, Ivar)); } llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) { uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar); return llvm::ConstantInt::get( CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset); } /* *** Private Interface *** */ std::string CGObjCCommonMac::GetSectionName(StringRef Section, StringRef MachOAttributes) { switch (CGM.getTriple().getObjectFormat()) { case llvm::Triple::UnknownObjectFormat: llvm_unreachable("unexpected object file format"); case llvm::Triple::MachO: { if (MachOAttributes.empty()) return ("__DATA," + Section).str(); return ("__DATA," + Section + "," + MachOAttributes).str(); } case llvm::Triple::ELF: assert(Section.substr(0, 2) == "__" && "expected the name to begin with __"); return Section.substr(2).str(); case llvm::Triple::COFF: assert(Section.substr(0, 2) == "__" && "expected the name to begin with __"); return ("." + Section.substr(2) + "$B").str(); case llvm::Triple::Wasm: case llvm::Triple::XCOFF: llvm::report_fatal_error( "Objective-C support is unimplemented for object file format."); } llvm_unreachable("Unhandled llvm::Triple::ObjectFormatType enum"); } /// EmitImageInfo - Emit the image info marker used to encode some module /// level information. /// /// See: <rdr://4810609&4810587&4810587> /// struct IMAGE_INFO { /// unsigned version; /// unsigned flags; /// }; enum ImageInfoFlags { eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang. eImageInfo_GarbageCollected = (1 << 1), eImageInfo_GCOnly = (1 << 2), eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache. // A flag indicating that the module has no instances of a @synthesize of a // superclass variable. <rdar://problem/6803242> eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang. eImageInfo_ImageIsSimulated = (1 << 5), eImageInfo_ClassProperties = (1 << 6) }; void CGObjCCommonMac::EmitImageInfo() { unsigned version = 0; // Version is unused? std::string Section = (ObjCABI == 1) ? "__OBJC,__image_info,regular" : GetSectionName("__objc_imageinfo", "regular,no_dead_strip"); // Generate module-level named metadata to convey this information to the // linker and code-gen. llvm::Module &Mod = CGM.getModule(); // Add the ObjC ABI version to the module flags. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI); Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version", version); Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section", llvm::MDString::get(VMContext, Section)); if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { // Non-GC overrides those files which specify GC. Mod.addModuleFlag(llvm::Module::Override, "Objective-C Garbage Collection", (uint32_t)0); } else { // Add the ObjC garbage collection value. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Garbage Collection", eImageInfo_GarbageCollected); if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) { // Add the ObjC GC Only value. Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only", eImageInfo_GCOnly); // Require that GC be specified and set to eImageInfo_GarbageCollected. llvm::Metadata *Ops[2] = { llvm::MDString::get(VMContext, "Objective-C Garbage Collection"), llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))}; Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only", llvm::MDNode::get(VMContext, Ops)); } } // Indicate whether we're compiling this to run on a simulator. if (CGM.getTarget().getTriple().isSimulatorEnvironment()) Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated", eImageInfo_ImageIsSimulated); // Indicate whether we are generating class properties. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties", eImageInfo_ClassProperties); } // struct objc_module { // unsigned long version; // unsigned long size; // const char *name; // Symtab symtab; // }; // FIXME: Get from somewhere static const int ModuleVersion = 7; void CGObjCMac::EmitModuleInfo() { uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ModuleTy); values.addInt(ObjCTypes.LongTy, ModuleVersion); values.addInt(ObjCTypes.LongTy, Size); // This used to be the filename, now it is unused. <rdr://4327263> values.add(GetClassName(StringRef(""))); values.add(EmitModuleSymbols()); CreateMetadataVar("OBJC_MODULES", values, "__OBJC,__module_info,regular,no_dead_strip", CGM.getPointerAlign(), true); } llvm::Constant *CGObjCMac::EmitModuleSymbols() { unsigned NumClasses = DefinedClasses.size(); unsigned NumCategories = DefinedCategories.size(); // Return null if no symbols were defined. if (!NumClasses && !NumCategories) return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); values.addInt(ObjCTypes.LongTy, 0); values.addNullPointer(ObjCTypes.SelectorPtrTy); values.addInt(ObjCTypes.ShortTy, NumClasses); values.addInt(ObjCTypes.ShortTy, NumCategories); // The runtime expects exactly the list of defined classes followed // by the list of defined categories, in a single array. auto array = values.beginArray(ObjCTypes.Int8PtrTy); for (unsigned i=0; i<NumClasses; i++) { const ObjCInterfaceDecl *ID = ImplementedClasses[i]; assert(ID); if (ObjCImplementationDecl *IMP = ID->getImplementation()) // We are implementing a weak imported interface. Give it external linkage if (ID->isWeakImported() && !IMP->isWeakImported()) DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage); array.addBitCast(DefinedClasses[i], ObjCTypes.Int8PtrTy); } for (unsigned i=0; i<NumCategories; i++) array.addBitCast(DefinedCategories[i], ObjCTypes.Int8PtrTy); array.finishAndAddTo(values); llvm::GlobalVariable *GV = CreateMetadataVar( "OBJC_SYMBOLS", values, "__OBJC,__symbols,regular,no_dead_strip", CGM.getPointerAlign(), true); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy); } llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II) { LazySymbols.insert(II); llvm::GlobalVariable *&Entry = ClassReferences[II]; if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetClassName(II->getName()), ObjCTypes.ClassPtrTy); Entry = CreateMetadataVar( "OBJC_CLASS_REFERENCES_", Casted, "__OBJC,__cls_refs,literal_pointers,no_dead_strip", CGM.getPointerAlign(), true); } return CGF.Builder.CreateAlignedLoad(Entry, CGF.getPointerAlign()); } llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { // If the class has the objc_runtime_visible attribute, we need to // use the Objective-C runtime to get the class. if (ID->hasAttr<ObjCRuntimeVisibleAttr>()) return EmitClassRefViaRuntime(CGF, ID, ObjCTypes); IdentifierInfo *RuntimeName = &CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString()); return EmitClassRefFromId(CGF, RuntimeName); } llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) { IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool"); return EmitClassRefFromId(CGF, II); } llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) { return CGF.Builder.CreateLoad(EmitSelectorAddr(Sel)); } Address CGObjCMac::EmitSelectorAddr(Selector Sel) { CharUnits Align = CGM.getPointerAlign(); llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), ObjCTypes.SelectorPtrTy); Entry = CreateMetadataVar( "OBJC_SELECTOR_REFERENCES_", Casted, "__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true); Entry->setExternallyInitialized(true); } return Address(Entry, Align); } llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) { llvm::GlobalVariable *&Entry = ClassNames[RuntimeName]; if (!Entry) Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName); return getConstantGEP(VMContext, Entry, 0, 0); } llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) { llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator I = MethodDefinitions.find(MD); if (I != MethodDefinitions.end()) return I->second; return nullptr; } /// GetIvarLayoutName - Returns a unique constant for the given /// ivar layout bitmap. llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident, const ObjCCommonTypesHelper &ObjCTypes) { return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy); } void IvarLayoutBuilder::visitRecord(const RecordType *RT, CharUnits offset) { const RecordDecl *RD = RT->getDecl(); // If this is a union, remember that we had one, because it might mess // up the ordering of layout entries. if (RD->isUnion()) IsDisordered = true; const ASTRecordLayout *recLayout = nullptr; visitAggregate(RD->field_begin(), RD->field_end(), offset, [&](const FieldDecl *field) -> CharUnits { if (!recLayout) recLayout = &CGM.getContext().getASTRecordLayout(RD); auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex()); return CGM.getContext().toCharUnitsFromBits(offsetInBits); }); } template <class Iterator, class GetOffsetFn> void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end, CharUnits aggregateOffset, const GetOffsetFn &getOffset) { for (; begin != end; ++begin) { auto field = *begin; // Skip over bitfields. if (field->isBitField()) { continue; } // Compute the offset of the field within the aggregate. CharUnits fieldOffset = aggregateOffset + getOffset(field); visitField(field, fieldOffset); } } /// Collect layout information for the given fields into IvarsInfo. void IvarLayoutBuilder::visitField(const FieldDecl *field, CharUnits fieldOffset) { QualType fieldType = field->getType(); // Drill down into arrays. uint64_t numElts = 1; if (auto arrayType = CGM.getContext().getAsIncompleteArrayType(fieldType)) { numElts = 0; fieldType = arrayType->getElementType(); } // Unlike incomplete arrays, constant arrays can be nested. while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) { numElts *= arrayType->getSize().getZExtValue(); fieldType = arrayType->getElementType(); } assert(!fieldType->isArrayType() && "ivar of non-constant array type?"); // If we ended up with a zero-sized array, we've done what we can do within // the limits of this layout encoding. if (numElts == 0) return; // Recurse if the base element type is a record type. if (auto recType = fieldType->getAs<RecordType>()) { size_t oldEnd = IvarsInfo.size(); visitRecord(recType, fieldOffset); // If we have an array, replicate the first entry's layout information. auto numEltEntries = IvarsInfo.size() - oldEnd; if (numElts != 1 && numEltEntries != 0) { CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType); for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) { // Copy the last numEltEntries onto the end of the array, adjusting // each for the element size. for (size_t i = 0; i != numEltEntries; ++i) { auto firstEntry = IvarsInfo[oldEnd + i]; IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize, firstEntry.SizeInWords)); } } } return; } // Classify the element type. Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType); // If it matches what we're looking for, add an entry. if ((ForStrongLayout && GCAttr == Qualifiers::Strong) || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) { assert(CGM.getContext().getTypeSizeInChars(fieldType) == CGM.getPointerSize()); IvarsInfo.push_back(IvarInfo(fieldOffset, numElts)); } } /// buildBitmap - This routine does the horsework of taking the offsets of /// strong/weak references and creating a bitmap. The bitmap is also /// returned in the given buffer, suitable for being passed to \c dump(). llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC, llvm::SmallVectorImpl<unsigned char> &buffer) { // The bitmap is a series of skip/scan instructions, aligned to word // boundaries. The skip is performed first. const unsigned char MaxNibble = 0xF; const unsigned char SkipMask = 0xF0, SkipShift = 4; const unsigned char ScanMask = 0x0F, ScanShift = 0; assert(!IvarsInfo.empty() && "generating bitmap for no data"); // Sort the ivar info on byte position in case we encounterred a // union nested in the ivar list. if (IsDisordered) { // This isn't a stable sort, but our algorithm should handle it fine. llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end()); } else { assert(std::is_sorted(IvarsInfo.begin(), IvarsInfo.end())); } assert(IvarsInfo.back().Offset < InstanceEnd); assert(buffer.empty()); // Skip the next N words. auto skip = [&](unsigned numWords) { assert(numWords > 0); // Try to merge into the previous byte. Since scans happen second, we // can't do this if it includes a scan. if (!buffer.empty() && !(buffer.back() & ScanMask)) { unsigned lastSkip = buffer.back() >> SkipShift; if (lastSkip < MaxNibble) { unsigned claimed = std::min(MaxNibble - lastSkip, numWords); numWords -= claimed; lastSkip += claimed; buffer.back() = (lastSkip << SkipShift); } } while (numWords >= MaxNibble) { buffer.push_back(MaxNibble << SkipShift); numWords -= MaxNibble; } if (numWords) { buffer.push_back(numWords << SkipShift); } }; // Scan the next N words. auto scan = [&](unsigned numWords) { assert(numWords > 0); // Try to merge into the previous byte. Since scans happen second, we can // do this even if it includes a skip. if (!buffer.empty()) { unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift; if (lastScan < MaxNibble) { unsigned claimed = std::min(MaxNibble - lastScan, numWords); numWords -= claimed; lastScan += claimed; buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift); } } while (numWords >= MaxNibble) { buffer.push_back(MaxNibble << ScanShift); numWords -= MaxNibble; } if (numWords) { buffer.push_back(numWords << ScanShift); } }; // One past the end of the last scan. unsigned endOfLastScanInWords = 0; const CharUnits WordSize = CGM.getPointerSize(); // Consider all the scan requests. for (auto &request : IvarsInfo) { CharUnits beginOfScan = request.Offset - InstanceBegin; // Ignore scan requests that don't start at an even multiple of the // word size. We can't encode them. if ((beginOfScan % WordSize) != 0) continue; // Ignore scan requests that start before the instance start. // This assumes that scans never span that boundary. The boundary // isn't the true start of the ivars, because in the fragile-ARC case // it's rounded up to word alignment, but the test above should leave // us ignoring that possibility. if (beginOfScan.isNegative()) { assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin); continue; } unsigned beginOfScanInWords = beginOfScan / WordSize; unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords; // If the scan starts some number of words after the last one ended, // skip forward. if (beginOfScanInWords > endOfLastScanInWords) { skip(beginOfScanInWords - endOfLastScanInWords); // Otherwise, start scanning where the last left off. } else { beginOfScanInWords = endOfLastScanInWords; // If that leaves us with nothing to scan, ignore this request. if (beginOfScanInWords >= endOfScanInWords) continue; } // Scan to the end of the request. assert(beginOfScanInWords < endOfScanInWords); scan(endOfScanInWords - beginOfScanInWords); endOfLastScanInWords = endOfScanInWords; } if (buffer.empty()) return llvm::ConstantPointerNull::get(CGM.Int8PtrTy); // For GC layouts, emit a skip to the end of the allocation so that we // have precise information about the entire thing. This isn't useful // or necessary for the ARC-style layout strings. if (CGM.getLangOpts().getGC() != LangOptions::NonGC) { unsigned lastOffsetInWords = (InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize; if (lastOffsetInWords > endOfLastScanInWords) { skip(lastOffsetInWords - endOfLastScanInWords); } } // Null terminate the string. buffer.push_back(0); auto *Entry = CGObjC.CreateCStringLiteral( reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName); return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0); } /// BuildIvarLayout - Builds ivar layout bitmap for the class /// implementation for the __strong or __weak case. /// The layout map displays which words in ivar list must be skipped /// and which must be scanned by GC (see below). String is built of bytes. /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count /// of words to skip and right nibble is count of words to scan. So, each /// nibble represents up to 15 workds to skip or scan. Skipping the rest is /// represented by a 0x00 byte which also ends the string. /// 1. when ForStrongLayout is true, following ivars are scanned: /// - id, Class /// - object * /// - __strong anything /// /// 2. When ForStrongLayout is false, following ivars are scanned: /// - __weak anything /// llvm::Constant * CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD, CharUnits beginOffset, CharUnits endOffset, bool ForStrongLayout, bool HasMRCWeakIvars) { // If this is MRC, and we're either building a strong layout or there // are no weak ivars, bail out early. llvm::Type *PtrTy = CGM.Int8PtrTy; if (CGM.getLangOpts().getGC() == LangOptions::NonGC && !CGM.getLangOpts().ObjCAutoRefCount && (ForStrongLayout || !HasMRCWeakIvars)) return llvm::Constant::getNullValue(PtrTy); const ObjCInterfaceDecl *OI = OMD->getClassInterface(); SmallVector<const ObjCIvarDecl*, 32> ivars; // GC layout strings include the complete object layout, possibly // inaccurately in the non-fragile ABI; the runtime knows how to fix this // up. // // ARC layout strings only include the class's ivars. In non-fragile // runtimes, that means starting at InstanceStart, rounded up to word // alignment. In fragile runtimes, there's no InstanceStart, so it means // starting at the offset of the first ivar, rounded up to word alignment. // // MRC weak layout strings follow the ARC style. CharUnits baseOffset; if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) ivars.push_back(IVD); if (isNonFragileABI()) { baseOffset = beginOffset; // InstanceStart } else if (!ivars.empty()) { baseOffset = CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0])); } else { baseOffset = CharUnits::Zero(); } baseOffset = baseOffset.alignTo(CGM.getPointerAlign()); } else { CGM.getContext().DeepCollectObjCIvars(OI, true, ivars); baseOffset = CharUnits::Zero(); } if (ivars.empty()) return llvm::Constant::getNullValue(PtrTy); IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout); builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(), [&](const ObjCIvarDecl *ivar) -> CharUnits { return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar)); }); if (!builder.hasBitmapData()) return llvm::Constant::getNullValue(PtrTy); llvm::SmallVector<unsigned char, 4> buffer; llvm::Constant *C = builder.buildBitmap(*this, buffer); if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) { printf("\n%s ivar layout for class '%s': ", ForStrongLayout ? "strong" : "weak", OMD->getClassInterface()->getName().str().c_str()); builder.dump(buffer); } return C; } llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) { llvm::GlobalVariable *&Entry = MethodVarNames[Sel]; // FIXME: Avoid std::string in "Sel.getAsString()" if (!Entry) Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName); return getConstantGEP(VMContext, Entry, 0, 0); } // FIXME: Merge into a single cstring creation function. llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) { return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID)); } llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) { std::string TypeStr; CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field); llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; if (!Entry) Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType); return getConstantGEP(VMContext, Entry, 0, 0); } llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D, bool Extended) { std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(D, Extended); llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr]; if (!Entry) Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType); return getConstantGEP(VMContext, Entry, 0, 0); } // FIXME: Merge into a single cstring creation function. llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) { llvm::GlobalVariable *&Entry = PropertyNames[Ident]; if (!Entry) Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName); return getConstantGEP(VMContext, Entry, 0, 0); } // FIXME: Merge into a single cstring creation function. // FIXME: This Decl should be more precise. llvm::Constant * CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD, const Decl *Container) { std::string TypeStr = CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container); return GetPropertyName(&CGM.getContext().Idents.get(TypeStr)); } void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D, const ObjCContainerDecl *CD, SmallVectorImpl<char> &Name, bool ignoreCategoryNamespace) { llvm::raw_svector_ostream OS(Name); assert (CD && "Missing container decl in GetNameForMethod"); OS << '\01' << (D->isInstanceMethod() ? '-' : '+') << '[' << CD->getName(); if (!ignoreCategoryNamespace) if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) OS << '(' << *CID << ')'; OS << ' ' << D->getSelector().getAsString() << ']'; } void CGObjCMac::FinishModule() { EmitModuleInfo(); // Emit the dummy bodies for any protocols which were referenced but // never defined. for (auto &entry : Protocols) { llvm::GlobalVariable *global = entry.second; if (global->hasInitializer()) continue; ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ProtocolTy); values.addNullPointer(ObjCTypes.ProtocolExtensionPtrTy); values.add(GetClassName(entry.first->getName())); values.addNullPointer(ObjCTypes.ProtocolListPtrTy); values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy); values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy); values.finishAndSetAsInitializer(global); CGM.addCompilerUsedGlobal(global); } // Add assembler directives to add lazy undefined symbol references // for classes which are referenced but not defined. This is // important for correct linker interaction. // // FIXME: It would be nice if we had an LLVM construct for this. if ((!LazySymbols.empty() || !DefinedSymbols.empty()) && CGM.getTriple().isOSBinFormatMachO()) { SmallString<256> Asm; Asm += CGM.getModule().getModuleInlineAsm(); if (!Asm.empty() && Asm.back() != '\n') Asm += '\n'; llvm::raw_svector_ostream OS(Asm); for (const auto *Sym : DefinedSymbols) OS << "\t.objc_class_name_" << Sym->getName() << "=0\n" << "\t.globl .objc_class_name_" << Sym->getName() << "\n"; for (const auto *Sym : LazySymbols) OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n"; for (const auto &Category : DefinedCategoryNames) OS << "\t.objc_category_name_" << Category << "=0\n" << "\t.globl .objc_category_name_" << Category << "\n"; CGM.getModule().setModuleInlineAsm(OS.str()); } } CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr), ObjCEmptyVtableVar(nullptr) { ObjCABI = 2; } /* *** */ ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm) : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr) { CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); ShortTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.ShortTy)); IntTy = CGM.IntTy; LongTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.LongTy)); Int8PtrTy = CGM.Int8PtrTy; Int8PtrPtrTy = CGM.Int8PtrPtrTy; // arm64 targets use "int" ivar offset variables. All others, // including OS X x86_64 and Windows x86_64, use "long" ivar offsets. if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64) IvarOffsetVarTy = IntTy; else IvarOffsetVarTy = LongTy; ObjectPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCIdType())); PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy); SelectorPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCSelType())); // I'm not sure I like this. The implicit coordination is a bit // gross. We should solve this in a reasonable fashion because this // is a pretty common task (match some runtime data structure with // an LLVM data structure). // FIXME: This is leaked. // FIXME: Merge with rewriter code? // struct _objc_super { // id self; // Class cls; // } RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), &Ctx.Idents.get("_objc_super")); RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), nullptr, Ctx.getObjCIdType(), nullptr, nullptr, false, ICIS_NoInit)); RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), nullptr, Ctx.getObjCClassType(), nullptr, nullptr, false, ICIS_NoInit)); RD->completeDefinition(); SuperCTy = Ctx.getTagDeclType(RD); SuperPtrCTy = Ctx.getPointerType(SuperCTy); SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy)); SuperPtrTy = llvm::PointerType::getUnqual(SuperTy); // struct _prop_t { // char *name; // char *attributes; // } PropertyTy = llvm::StructType::create("struct._prop_t", Int8PtrTy, Int8PtrTy); // struct _prop_list_t { // uint32_t entsize; // sizeof(struct _prop_t) // uint32_t count_of_properties; // struct _prop_t prop_list[count_of_properties]; // } PropertyListTy = llvm::StructType::create( "struct._prop_list_t", IntTy, IntTy, llvm::ArrayType::get(PropertyTy, 0)); // struct _prop_list_t * PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy); // struct _objc_method { // SEL _cmd; // char *method_type; // char *_imp; // } MethodTy = llvm::StructType::create("struct._objc_method", SelectorPtrTy, Int8PtrTy, Int8PtrTy); // struct _objc_cache * CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache"); CachePtrTy = llvm::PointerType::getUnqual(CacheTy); } ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm) : ObjCCommonTypesHelper(cgm) { // struct _objc_method_description { // SEL name; // char *types; // } MethodDescriptionTy = llvm::StructType::create( "struct._objc_method_description", SelectorPtrTy, Int8PtrTy); // struct _objc_method_description_list { // int count; // struct _objc_method_description[1]; // } MethodDescriptionListTy = llvm::StructType::create("struct._objc_method_description_list", IntTy, llvm::ArrayType::get(MethodDescriptionTy, 0)); // struct _objc_method_description_list * MethodDescriptionListPtrTy = llvm::PointerType::getUnqual(MethodDescriptionListTy); // Protocol description structures // struct _objc_protocol_extension { // uint32_t size; // sizeof(struct _objc_protocol_extension) // struct _objc_method_description_list *optional_instance_methods; // struct _objc_method_description_list *optional_class_methods; // struct _objc_property_list *instance_properties; // const char ** extendedMethodTypes; // struct _objc_property_list *class_properties; // } ProtocolExtensionTy = llvm::StructType::create( "struct._objc_protocol_extension", IntTy, MethodDescriptionListPtrTy, MethodDescriptionListPtrTy, PropertyListPtrTy, Int8PtrPtrTy, PropertyListPtrTy); // struct _objc_protocol_extension * ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy); // Handle recursive construction of Protocol and ProtocolList types ProtocolTy = llvm::StructType::create(VMContext, "struct._objc_protocol"); ProtocolListTy = llvm::StructType::create(VMContext, "struct._objc_protocol_list"); ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), LongTy, llvm::ArrayType::get(ProtocolTy, 0)); // struct _objc_protocol { // struct _objc_protocol_extension *isa; // char *protocol_name; // struct _objc_protocol **_objc_protocol_list; // struct _objc_method_description_list *instance_methods; // struct _objc_method_description_list *class_methods; // } ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy, llvm::PointerType::getUnqual(ProtocolListTy), MethodDescriptionListPtrTy, MethodDescriptionListPtrTy); // struct _objc_protocol_list * ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy); ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy); // Class description structures // struct _objc_ivar { // char *ivar_name; // char *ivar_type; // int ivar_offset; // } IvarTy = llvm::StructType::create("struct._objc_ivar", Int8PtrTy, Int8PtrTy, IntTy); // struct _objc_ivar_list * IvarListTy = llvm::StructType::create(VMContext, "struct._objc_ivar_list"); IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy); // struct _objc_method_list * MethodListTy = llvm::StructType::create(VMContext, "struct._objc_method_list"); MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy); // struct _objc_class_extension * ClassExtensionTy = llvm::StructType::create( "struct._objc_class_extension", IntTy, Int8PtrTy, PropertyListPtrTy); ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy); ClassTy = llvm::StructType::create(VMContext, "struct._objc_class"); // struct _objc_class { // Class isa; // Class super_class; // char *name; // long version; // long info; // long instance_size; // struct _objc_ivar_list *ivars; // struct _objc_method_list *methods; // struct _objc_cache *cache; // struct _objc_protocol_list *protocols; // char *ivar_layout; // struct _objc_class_ext *ext; // }; ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy), llvm::PointerType::getUnqual(ClassTy), Int8PtrTy, LongTy, LongTy, LongTy, IvarListPtrTy, MethodListPtrTy, CachePtrTy, ProtocolListPtrTy, Int8PtrTy, ClassExtensionPtrTy); ClassPtrTy = llvm::PointerType::getUnqual(ClassTy); // struct _objc_category { // char *category_name; // char *class_name; // struct _objc_method_list *instance_method; // struct _objc_method_list *class_method; // struct _objc_protocol_list *protocols; // uint32_t size; // sizeof(struct _objc_category) // struct _objc_property_list *instance_properties;// category's @property // struct _objc_property_list *class_properties; // } CategoryTy = llvm::StructType::create( "struct._objc_category", Int8PtrTy, Int8PtrTy, MethodListPtrTy, MethodListPtrTy, ProtocolListPtrTy, IntTy, PropertyListPtrTy, PropertyListPtrTy); // Global metadata structures // struct _objc_symtab { // long sel_ref_cnt; // SEL *refs; // short cls_def_cnt; // short cat_def_cnt; // char *defs[cls_def_cnt + cat_def_cnt]; // } SymtabTy = llvm::StructType::create("struct._objc_symtab", LongTy, SelectorPtrTy, ShortTy, ShortTy, llvm::ArrayType::get(Int8PtrTy, 0)); SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy); // struct _objc_module { // long version; // long size; // sizeof(struct _objc_module) // char *name; // struct _objc_symtab* symtab; // } ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy, Int8PtrTy, SymtabPtrTy); // FIXME: This is the size of the setjmp buffer and should be target // specific. 18 is what's used on 32-bit X86. uint64_t SetJmpBufferSize = 18; // Exceptions llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4); ExceptionDataTy = llvm::StructType::create( "struct._objc_exception_data", llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy); } ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm) : ObjCCommonTypesHelper(cgm) { // struct _method_list_t { // uint32_t entsize; // sizeof(struct _objc_method) // uint32_t method_count; // struct _objc_method method_list[method_count]; // } MethodListnfABITy = llvm::StructType::create("struct.__method_list_t", IntTy, IntTy, llvm::ArrayType::get(MethodTy, 0)); // struct method_list_t * MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy); // struct _protocol_t { // id isa; // NULL // const char * const protocol_name; // const struct _protocol_list_t * protocol_list; // super protocols // const struct method_list_t * const instance_methods; // const struct method_list_t * const class_methods; // const struct method_list_t *optionalInstanceMethods; // const struct method_list_t *optionalClassMethods; // const struct _prop_list_t * properties; // const uint32_t size; // sizeof(struct _protocol_t) // const uint32_t flags; // = 0 // const char ** extendedMethodTypes; // const char *demangledName; // const struct _prop_list_t * class_properties; // } // Holder for struct _protocol_list_t * ProtocolListnfABITy = llvm::StructType::create(VMContext, "struct._objc_protocol_list"); ProtocolnfABITy = llvm::StructType::create( "struct._protocol_t", ObjectPtrTy, Int8PtrTy, llvm::PointerType::getUnqual(ProtocolListnfABITy), MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, Int8PtrTy, PropertyListPtrTy); // struct _protocol_t* ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy); // struct _protocol_list_t { // long protocol_count; // Note, this is 32/64 bit // struct _protocol_t *[protocol_count]; // } ProtocolListnfABITy->setBody(LongTy, llvm::ArrayType::get(ProtocolnfABIPtrTy, 0)); // struct _objc_protocol_list* ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy); // struct _ivar_t { // unsigned [long] int *offset; // pointer to ivar offset location // char *name; // char *type; // uint32_t alignment; // uint32_t size; // } IvarnfABITy = llvm::StructType::create( "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy), Int8PtrTy, Int8PtrTy, IntTy, IntTy); // struct _ivar_list_t { // uint32 entsize; // sizeof(struct _ivar_t) // uint32 count; // struct _iver_t list[count]; // } IvarListnfABITy = llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy, llvm::ArrayType::get(IvarnfABITy, 0)); IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy); // struct _class_ro_t { // uint32_t const flags; // uint32_t const instanceStart; // uint32_t const instanceSize; // uint32_t const reserved; // only when building for 64bit targets // const uint8_t * const ivarLayout; // const char *const name; // const struct _method_list_t * const baseMethods; // const struct _objc_protocol_list *const baseProtocols; // const struct _ivar_list_t *const ivars; // const uint8_t * const weakIvarLayout; // const struct _prop_list_t * const properties; // } // FIXME. Add 'reserved' field in 64bit abi mode! ClassRonfABITy = llvm::StructType::create( "struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy, MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy, Int8PtrTy, PropertyListPtrTy); // ImpnfABITy - LLVM for id (*)(id, SEL, ...) llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy }; ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false) ->getPointerTo(); // struct _class_t { // struct _class_t *isa; // struct _class_t * const superclass; // void *cache; // IMP *vtable; // struct class_ro_t *ro; // } ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t"); ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy), llvm::PointerType::getUnqual(ClassnfABITy), CachePtrTy, llvm::PointerType::getUnqual(ImpnfABITy), llvm::PointerType::getUnqual(ClassRonfABITy)); // LLVM for struct _class_t * ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy); // struct _category_t { // const char * const name; // struct _class_t *const cls; // const struct _method_list_t * const instance_methods; // const struct _method_list_t * const class_methods; // const struct _protocol_list_t * const protocols; // const struct _prop_list_t * const properties; // const struct _prop_list_t * const class_properties; // const uint32_t size; // } CategorynfABITy = llvm::StructType::create( "struct._category_t", Int8PtrTy, ClassnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, PropertyListPtrTy, PropertyListPtrTy, IntTy); // New types for nonfragile abi messaging. CodeGen::CodeGenTypes &Types = CGM.getTypes(); ASTContext &Ctx = CGM.getContext(); // MessageRefTy - LLVM for: // struct _message_ref_t { // IMP messenger; // SEL name; // }; // First the clang type for struct _message_ref_t RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), &Ctx.Idents.get("_message_ref_t")); RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false, ICIS_NoInit)); RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), nullptr, Ctx.getObjCSelType(), nullptr, nullptr, false, ICIS_NoInit)); RD->completeDefinition(); MessageRefCTy = Ctx.getTagDeclType(RD); MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy); MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy)); // MessageRefPtrTy - LLVM for struct _message_ref_t* MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy); // SuperMessageRefTy - LLVM for: // struct _super_message_ref_t { // SUPER_IMP messenger; // SEL name; // }; SuperMessageRefTy = llvm::StructType::create("struct._super_message_ref_t", ImpnfABITy, SelectorPtrTy); // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t* SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy); // struct objc_typeinfo { // const void** vtable; // objc_ehtype_vtable + 2 // const char* name; // c++ typeinfo string // Class cls; // }; EHTypeTy = llvm::StructType::create("struct._objc_typeinfo", llvm::PointerType::getUnqual(Int8PtrTy), Int8PtrTy, ClassnfABIPtrTy); EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy); } llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() { FinishNonFragileABIModule(); return nullptr; } void CGObjCNonFragileABIMac::AddModuleClassList( ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName, StringRef SectionName) { unsigned NumClasses = Container.size(); if (!NumClasses) return; SmallVector<llvm::Constant*, 8> Symbols(NumClasses); for (unsigned i=0; i<NumClasses; i++) Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i], ObjCTypes.Int8PtrTy); llvm::Constant *Init = llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Symbols.size()), Symbols); // Section name is obtained by calling GetSectionName, which returns // sections in the __DATA segment on MachO. assert((!CGM.getTriple().isOSBinFormatMachO() || SectionName.startswith("__DATA")) && "SectionName expected to start with __DATA on MachO"); llvm::GlobalValue::LinkageTypes LT = getLinkageTypeForObjCMetadata(CGM, SectionName); llvm::GlobalVariable *GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, LT, Init, SymbolName); GV->setAlignment( llvm::Align(CGM.getDataLayout().getABITypeAlignment(Init->getType()))); GV->setSection(SectionName); CGM.addCompilerUsedGlobal(GV); } void CGObjCNonFragileABIMac::FinishNonFragileABIModule() { // nonfragile abi has no module definition. // Build list of all implemented class addresses in array // L_OBJC_LABEL_CLASS_$. for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) { const ObjCInterfaceDecl *ID = ImplementedClasses[i]; assert(ID); if (ObjCImplementationDecl *IMP = ID->getImplementation()) // We are implementing a weak imported interface. Give it external linkage if (ID->isWeakImported() && !IMP->isWeakImported()) { DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage); DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage); } } AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$", GetSectionName("__objc_classlist", "regular,no_dead_strip")); AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$", GetSectionName("__objc_nlclslist", "regular,no_dead_strip")); // Build list of all implemented category addresses in array // L_OBJC_LABEL_CATEGORY_$. AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$", GetSectionName("__objc_catlist", "regular,no_dead_strip")); AddModuleClassList(DefinedStubCategories, "OBJC_LABEL_STUB_CATEGORY_$", GetSectionName("__objc_catlist2", "regular,no_dead_strip")); AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$", GetSectionName("__objc_nlcatlist", "regular,no_dead_strip")); EmitImageInfo(); } /// isVTableDispatchedSelector - Returns true if SEL is not in the list of /// VTableDispatchMethods; false otherwise. What this means is that /// except for the 19 selectors in the list, we generate 32bit-style /// message dispatch call for all the rest. bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) { // At various points we've experimented with using vtable-based // dispatch for all methods. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) { case CodeGenOptions::Legacy: return false; case CodeGenOptions::NonLegacy: return true; case CodeGenOptions::Mixed: break; } // If so, see whether this selector is in the white-list of things which must // use the new dispatch convention. We lazily build a dense set for this. if (VTableDispatchMethods.empty()) { VTableDispatchMethods.insert(GetNullarySelector("alloc")); VTableDispatchMethods.insert(GetNullarySelector("class")); VTableDispatchMethods.insert(GetNullarySelector("self")); VTableDispatchMethods.insert(GetNullarySelector("isFlipped")); VTableDispatchMethods.insert(GetNullarySelector("length")); VTableDispatchMethods.insert(GetNullarySelector("count")); // These are vtable-based if GC is disabled. // Optimistically use vtable dispatch for hybrid compiles. if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) { VTableDispatchMethods.insert(GetNullarySelector("retain")); VTableDispatchMethods.insert(GetNullarySelector("release")); VTableDispatchMethods.insert(GetNullarySelector("autorelease")); } VTableDispatchMethods.insert(GetUnarySelector("allocWithZone")); VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass")); VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector")); VTableDispatchMethods.insert(GetUnarySelector("objectForKey")); VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex")); VTableDispatchMethods.insert(GetUnarySelector("isEqualToString")); VTableDispatchMethods.insert(GetUnarySelector("isEqual")); // These are vtable-based if GC is enabled. // Optimistically use vtable dispatch for hybrid compiles. if (CGM.getLangOpts().getGC() != LangOptions::NonGC) { VTableDispatchMethods.insert(GetNullarySelector("hash")); VTableDispatchMethods.insert(GetUnarySelector("addObject")); // "countByEnumeratingWithState:objects:count" IdentifierInfo *KeyIdents[] = { &CGM.getContext().Idents.get("countByEnumeratingWithState"), &CGM.getContext().Idents.get("objects"), &CGM.getContext().Idents.get("count") }; VTableDispatchMethods.insert( CGM.getContext().Selectors.getSelector(3, KeyIdents)); } } return VTableDispatchMethods.count(Sel); } /// BuildClassRoTInitializer - generate meta-data for: /// struct _class_ro_t { /// uint32_t const flags; /// uint32_t const instanceStart; /// uint32_t const instanceSize; /// uint32_t const reserved; // only when building for 64bit targets /// const uint8_t * const ivarLayout; /// const char *const name; /// const struct _method_list_t * const baseMethods; /// const struct _protocol_list_t *const baseProtocols; /// const struct _ivar_list_t *const ivars; /// const uint8_t * const weakIvarLayout; /// const struct _prop_list_t * const properties; /// } /// llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer( unsigned flags, unsigned InstanceStart, unsigned InstanceSize, const ObjCImplementationDecl *ID) { std::string ClassName = std::string(ID->getObjCRuntimeNameAsString()); CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart); CharUnits endInstance = CharUnits::fromQuantity(InstanceSize); bool hasMRCWeak = false; if (CGM.getLangOpts().ObjCAutoRefCount) flags |= NonFragileABI_Class_CompiledByARC; else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID))) flags |= NonFragileABI_Class_HasMRCWeakIvars; ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ClassRonfABITy); values.addInt(ObjCTypes.IntTy, flags); values.addInt(ObjCTypes.IntTy, InstanceStart); values.addInt(ObjCTypes.IntTy, InstanceSize); values.add((flags & NonFragileABI_Class_Meta) ? GetIvarLayoutName(nullptr, ObjCTypes) : BuildStrongIvarLayout(ID, beginInstance, endInstance)); values.add(GetClassName(ID->getObjCRuntimeNameAsString())); // const struct _method_list_t * const baseMethods; SmallVector<const ObjCMethodDecl*, 16> methods; if (flags & NonFragileABI_Class_Meta) { for (const auto *MD : ID->class_methods()) if (!MD->isDirectMethod()) methods.push_back(MD); } else { for (const auto *MD : ID->instance_methods()) if (!MD->isDirectMethod()) methods.push_back(MD); } values.add(emitMethodList(ID->getObjCRuntimeNameAsString(), (flags & NonFragileABI_Class_Meta) ? MethodListType::ClassMethods : MethodListType::InstanceMethods, methods)); const ObjCInterfaceDecl *OID = ID->getClassInterface(); assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer"); values.add(EmitProtocolList("_OBJC_CLASS_PROTOCOLS_$_" + OID->getObjCRuntimeNameAsString(), OID->all_referenced_protocol_begin(), OID->all_referenced_protocol_end())); if (flags & NonFragileABI_Class_Meta) { values.addNullPointer(ObjCTypes.IvarListnfABIPtrTy); values.add(GetIvarLayoutName(nullptr, ObjCTypes)); values.add(EmitPropertyList( "_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(), ID, ID->getClassInterface(), ObjCTypes, true)); } else { values.add(EmitIvarList(ID)); values.add(BuildWeakIvarLayout(ID, beginInstance, endInstance, hasMRCWeak)); values.add(EmitPropertyList( "_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(), ID, ID->getClassInterface(), ObjCTypes, false)); } llvm::SmallString<64> roLabel; llvm::raw_svector_ostream(roLabel) << ((flags & NonFragileABI_Class_Meta) ? "_OBJC_METACLASS_RO_$_" : "_OBJC_CLASS_RO_$_") << ClassName; return finishAndCreateGlobal(values, roLabel, CGM); } /// Build the metaclass object for a class. /// /// struct _class_t { /// struct _class_t *isa; /// struct _class_t * const superclass; /// void *cache; /// IMP *vtable; /// struct class_ro_t *ro; /// } /// llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassObject(const ObjCInterfaceDecl *CI, bool isMetaclass, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV, llvm::Constant *ClassRoGV, bool HiddenVisibility) { ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ClassnfABITy); values.add(IsAGV); if (SuperClassGV) { values.add(SuperClassGV); } else { values.addNullPointer(ObjCTypes.ClassnfABIPtrTy); } values.add(ObjCEmptyCacheVar); values.add(ObjCEmptyVtableVar); values.add(ClassRoGV); llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetClassGlobal(CI, isMetaclass, ForDefinition)); values.finishAndSetAsInitializer(GV); if (CGM.getTriple().isOSBinFormatMachO()) GV->setSection("__DATA, __objc_data"); GV->setAlignment(llvm::Align( CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy))); if (!CGM.getTriple().isOSBinFormatCOFF()) if (HiddenVisibility) GV->setVisibility(llvm::GlobalValue::HiddenVisibility); return GV; } bool CGObjCNonFragileABIMac::ImplementationIsNonLazy( const ObjCImplDecl *OD) const { return OD->getClassMethod(GetNullarySelector("load")) != nullptr || OD->getClassInterface()->hasAttr<ObjCNonLazyClassAttr>() || OD->hasAttr<ObjCNonLazyClassAttr>(); } void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID, uint32_t &InstanceStart, uint32_t &InstanceSize) { const ASTRecordLayout &RL = CGM.getContext().getASTObjCImplementationLayout(OID); // InstanceSize is really instance end. InstanceSize = RL.getDataSize().getQuantity(); // If there are no fields, the start is the same as the end. if (!RL.getFieldCount()) InstanceStart = InstanceSize; else InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth(); } static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM, StringRef Name) { IdentifierInfo &II = CGM.getContext().Idents.get(Name); TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl(); DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); const VarDecl *VD = nullptr; for (const auto &Result : DC->lookup(&II)) if ((VD = dyn_cast<VarDecl>(Result))) break; if (!VD) return llvm::GlobalValue::DLLImportStorageClass; if (VD->hasAttr<DLLExportAttr>()) return llvm::GlobalValue::DLLExportStorageClass; if (VD->hasAttr<DLLImportAttr>()) return llvm::GlobalValue::DLLImportStorageClass; return llvm::GlobalValue::DefaultStorageClass; } void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) { if (!ObjCEmptyCacheVar) { ObjCEmptyCacheVar = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, "_objc_empty_cache"); if (CGM.getTriple().isOSBinFormatCOFF()) ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache")); // Only OS X with deployment version <10.9 use the empty vtable symbol const llvm::Triple &Triple = CGM.getTarget().getTriple(); if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9)) ObjCEmptyVtableVar = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false, llvm::GlobalValue::ExternalLinkage, nullptr, "_objc_empty_vtable"); else ObjCEmptyVtableVar = llvm::ConstantPointerNull::get(ObjCTypes.ImpnfABITy->getPointerTo()); } // FIXME: Is this correct (that meta class size is never computed)? uint32_t InstanceStart = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy); uint32_t InstanceSize = InstanceStart; uint32_t flags = NonFragileABI_Class_Meta; llvm::Constant *SuperClassGV, *IsAGV; const auto *CI = ID->getClassInterface(); assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0"); // Build the flags for the metaclass. bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF()) ? !CI->hasAttr<DLLExportAttr>() : CI->getVisibility() == HiddenVisibility; if (classIsHidden) flags |= NonFragileABI_Class_Hidden; // FIXME: why is this flag set on the metaclass? // ObjC metaclasses have no fields and don't really get constructed. if (ID->hasNonZeroConstructors() || ID->hasDestructors()) { flags |= NonFragileABI_Class_HasCXXStructors; if (!ID->hasNonZeroConstructors()) flags |= NonFragileABI_Class_HasCXXDestructorOnly; } if (!CI->getSuperClass()) { // class is root flags |= NonFragileABI_Class_Root; SuperClassGV = GetClassGlobal(CI, /*metaclass*/ false, NotForDefinition); IsAGV = GetClassGlobal(CI, /*metaclass*/ true, NotForDefinition); } else { // Has a root. Current class is not a root. const ObjCInterfaceDecl *Root = ID->getClassInterface(); while (const ObjCInterfaceDecl *Super = Root->getSuperClass()) Root = Super; const auto *Super = CI->getSuperClass(); IsAGV = GetClassGlobal(Root, /*metaclass*/ true, NotForDefinition); SuperClassGV = GetClassGlobal(Super, /*metaclass*/ true, NotForDefinition); } llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID); llvm::GlobalVariable *MetaTClass = BuildClassObject(CI, /*metaclass*/ true, IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden); CGM.setGVProperties(MetaTClass, CI); DefinedMetaClasses.push_back(MetaTClass); // Metadata for the class flags = 0; if (classIsHidden) flags |= NonFragileABI_Class_Hidden; if (ID->hasNonZeroConstructors() || ID->hasDestructors()) { flags |= NonFragileABI_Class_HasCXXStructors; // Set a flag to enable a runtime optimization when a class has // fields that require destruction but which don't require // anything except zero-initialization during construction. This // is most notably true of __strong and __weak types, but you can // also imagine there being C++ types with non-trivial default // constructors that merely set all fields to null. if (!ID->hasNonZeroConstructors()) flags |= NonFragileABI_Class_HasCXXDestructorOnly; } if (hasObjCExceptionAttribute(CGM.getContext(), CI)) flags |= NonFragileABI_Class_Exception; if (!CI->getSuperClass()) { flags |= NonFragileABI_Class_Root; SuperClassGV = nullptr; } else { // Has a root. Current class is not a root. const auto *Super = CI->getSuperClass(); SuperClassGV = GetClassGlobal(Super, /*metaclass*/ false, NotForDefinition); } GetClassSizeInfo(ID, InstanceStart, InstanceSize); CLASS_RO_GV = BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID); llvm::GlobalVariable *ClassMD = BuildClassObject(CI, /*metaclass*/ false, MetaTClass, SuperClassGV, CLASS_RO_GV, classIsHidden); CGM.setGVProperties(ClassMD, CI); DefinedClasses.push_back(ClassMD); ImplementedClasses.push_back(CI); // Determine if this class is also "non-lazy". if (ImplementationIsNonLazy(ID)) DefinedNonLazyClasses.push_back(ClassMD); // Force the definition of the EHType if necessary. if (flags & NonFragileABI_Class_Exception) (void) GetInterfaceEHType(CI, ForDefinition); // Make sure method definition entries are all clear for next implementation. MethodDefinitions.clear(); } /// GenerateProtocolRef - This routine is called to generate code for /// a protocol reference expression; as in: /// @code /// @protocol(Proto1); /// @endcode /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1 /// which will hold address of the protocol meta-data. /// llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF, const ObjCProtocolDecl *PD) { // This routine is called for @protocol only. So, we must build definition // of protocol's meta-data (not a reference to it!) // llvm::Constant *Init = llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD), ObjCTypes.getExternalProtocolPtrTy()); std::string ProtocolName("_OBJC_PROTOCOL_REFERENCE_$_"); ProtocolName += PD->getObjCRuntimeNameAsString(); CharUnits Align = CGF.getPointerAlign(); llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName); if (PTGV) return CGF.Builder.CreateAlignedLoad(PTGV, Align); PTGV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false, llvm::GlobalValue::WeakAnyLinkage, Init, ProtocolName); PTGV->setSection(GetSectionName("__objc_protorefs", "coalesced,no_dead_strip")); PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); PTGV->setAlignment(Align.getAsAlign()); if (!CGM.getTriple().isOSBinFormatMachO()) PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolName)); CGM.addUsedGlobal(PTGV); return CGF.Builder.CreateAlignedLoad(PTGV, Align); } /// GenerateCategory - Build metadata for a category implementation. /// struct _category_t { /// const char * const name; /// struct _class_t *const cls; /// const struct _method_list_t * const instance_methods; /// const struct _method_list_t * const class_methods; /// const struct _protocol_list_t * const protocols; /// const struct _prop_list_t * const properties; /// const struct _prop_list_t * const class_properties; /// const uint32_t size; /// } /// void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) { const ObjCInterfaceDecl *Interface = OCD->getClassInterface(); const char *Prefix = "_OBJC_$_CATEGORY_"; llvm::SmallString<64> ExtCatName(Prefix); ExtCatName += Interface->getObjCRuntimeNameAsString(); ExtCatName += "_$_"; ExtCatName += OCD->getNameAsString(); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.CategorynfABITy); values.add(GetClassName(OCD->getIdentifier()->getName())); // meta-class entry symbol values.add(GetClassGlobal(Interface, /*metaclass*/ false, NotForDefinition)); std::string listName = (Interface->getObjCRuntimeNameAsString() + "_$_" + OCD->getName()).str(); SmallVector<const ObjCMethodDecl *, 16> instanceMethods; SmallVector<const ObjCMethodDecl *, 8> classMethods; for (const auto *MD : OCD->methods()) { if (MD->isDirectMethod()) continue; if (MD->isInstanceMethod()) { instanceMethods.push_back(MD); } else { classMethods.push_back(MD); } } values.add(emitMethodList(listName, MethodListType::CategoryInstanceMethods, instanceMethods)); values.add(emitMethodList(listName, MethodListType::CategoryClassMethods, classMethods)); const ObjCCategoryDecl *Category = Interface->FindCategoryDeclaration(OCD->getIdentifier()); if (Category) { SmallString<256> ExtName; llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_" << OCD->getName(); values.add(EmitProtocolList("_OBJC_CATEGORY_PROTOCOLS_$_" + Interface->getObjCRuntimeNameAsString() + "_$_" + Category->getName(), Category->protocol_begin(), Category->protocol_end())); values.add(EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(), OCD, Category, ObjCTypes, false)); values.add(EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(), OCD, Category, ObjCTypes, true)); } else { values.addNullPointer(ObjCTypes.ProtocolListnfABIPtrTy); values.addNullPointer(ObjCTypes.PropertyListPtrTy); values.addNullPointer(ObjCTypes.PropertyListPtrTy); } unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy); values.addInt(ObjCTypes.IntTy, Size); llvm::GlobalVariable *GCATV = finishAndCreateGlobal(values, ExtCatName.str(), CGM); CGM.addCompilerUsedGlobal(GCATV); if (Interface->hasAttr<ObjCClassStubAttr>()) DefinedStubCategories.push_back(GCATV); else DefinedCategories.push_back(GCATV); // Determine if this category is also "non-lazy". if (ImplementationIsNonLazy(OCD)) DefinedNonLazyCategories.push_back(GCATV); // method definition entries must be clear for next implementation. MethodDefinitions.clear(); } /// emitMethodConstant - Return a struct objc_method constant. If /// forProtocol is true, the implementation will be null; otherwise, /// the method must have a definition registered with the runtime. /// /// struct _objc_method { /// SEL _cmd; /// char *method_type; /// char *_imp; /// } void CGObjCNonFragileABIMac::emitMethodConstant(ConstantArrayBuilder &builder, const ObjCMethodDecl *MD, bool forProtocol) { auto method = builder.beginStruct(ObjCTypes.MethodTy); method.addBitCast(GetMethodVarName(MD->getSelector()), ObjCTypes.SelectorPtrTy); method.add(GetMethodVarType(MD)); if (forProtocol) { // Protocol methods have no implementation. So, this entry is always NULL. method.addNullPointer(ObjCTypes.Int8PtrTy); } else { llvm::Function *fn = GetMethodDefinition(MD); assert(fn && "no definition for method?"); if (const auto &schema = CGM.getCodeGenOpts().PointerAuth.ObjCMethodListFunctionPointers) { auto *bitcast = llvm::ConstantExpr::getBitCast(fn, ObjCTypes.Int8PtrTy); method.addSignedPointer(bitcast, schema, GlobalDecl(), QualType()); } else { method.addBitCast(fn, ObjCTypes.Int8PtrTy); } } method.finishAndAddTo(builder); } /// Build meta-data for method declarations. /// /// struct _method_list_t { /// uint32_t entsize; // sizeof(struct _objc_method) /// uint32_t method_count; /// struct _objc_method method_list[method_count]; /// } /// llvm::Constant * CGObjCNonFragileABIMac::emitMethodList(Twine name, MethodListType kind, ArrayRef<const ObjCMethodDecl *> methods) { // Return null for empty list. if (methods.empty()) return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy); StringRef prefix; bool forProtocol; switch (kind) { case MethodListType::CategoryInstanceMethods: prefix = "_OBJC_$_CATEGORY_INSTANCE_METHODS_"; forProtocol = false; break; case MethodListType::CategoryClassMethods: prefix = "_OBJC_$_CATEGORY_CLASS_METHODS_"; forProtocol = false; break; case MethodListType::InstanceMethods: prefix = "_OBJC_$_INSTANCE_METHODS_"; forProtocol = false; break; case MethodListType::ClassMethods: prefix = "_OBJC_$_CLASS_METHODS_"; forProtocol = false; break; case MethodListType::ProtocolInstanceMethods: prefix = "_OBJC_$_PROTOCOL_INSTANCE_METHODS_"; forProtocol = true; break; case MethodListType::ProtocolClassMethods: prefix = "_OBJC_$_PROTOCOL_CLASS_METHODS_"; forProtocol = true; break; case MethodListType::OptionalProtocolInstanceMethods: prefix = "_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"; forProtocol = true; break; case MethodListType::OptionalProtocolClassMethods: prefix = "_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"; forProtocol = true; break; } ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); // sizeof(struct _objc_method) unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy); values.addInt(ObjCTypes.IntTy, Size); // method_count values.addInt(ObjCTypes.IntTy, methods.size()); auto methodArray = values.beginArray(ObjCTypes.MethodTy); for (auto MD : methods) emitMethodConstant(methodArray, MD, forProtocol); methodArray.finishAndAddTo(values); llvm::GlobalVariable *GV = finishAndCreateGlobal(values, prefix + name, CGM); CGM.addCompilerUsedGlobal(GV); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy); } /// ObjCIvarOffsetVariable - Returns the ivar offset variable for /// the given ivar. llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar) { const ObjCInterfaceDecl *Container = Ivar->getContainingInterface(); llvm::SmallString<64> Name("OBJC_IVAR_$_"); Name += Container->getObjCRuntimeNameAsString(); Name += "."; Name += Ivar->getName(); llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name); if (!IvarOffsetGV) { IvarOffsetGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, Name.str()); if (CGM.getTriple().isOSBinFormatCOFF()) { bool IsPrivateOrPackage = Ivar->getAccessControl() == ObjCIvarDecl::Private || Ivar->getAccessControl() == ObjCIvarDecl::Package; const ObjCInterfaceDecl *ContainingID = Ivar->getContainingInterface(); if (ContainingID->hasAttr<DLLImportAttr>()) IvarOffsetGV ->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); else if (ContainingID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage) IvarOffsetGV ->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); } } return IvarOffsetGV; } llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar, unsigned long int Offset) { llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar); IvarOffsetGV->setInitializer( llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset)); IvarOffsetGV->setAlignment(llvm::Align( CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy))); if (!CGM.getTriple().isOSBinFormatCOFF()) { // FIXME: This matches gcc, but shouldn't the visibility be set on the use // as well (i.e., in ObjCIvarOffsetVariable). if (Ivar->getAccessControl() == ObjCIvarDecl::Private || Ivar->getAccessControl() == ObjCIvarDecl::Package || ID->getVisibility() == HiddenVisibility) IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility); else IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility); } // If ID's layout is known, then make the global constant. This serves as a // useful assertion: we'll never use this variable to calculate ivar offsets, // so if the runtime tries to patch it then we should crash. if (isClassLayoutKnownStatically(ID)) IvarOffsetGV->setConstant(true); if (CGM.getTriple().isOSBinFormatMachO()) IvarOffsetGV->setSection("__DATA, __objc_ivar"); return IvarOffsetGV; } /// EmitIvarList - Emit the ivar list for the given /// implementation. The return value has type /// IvarListnfABIPtrTy. /// struct _ivar_t { /// unsigned [long] int *offset; // pointer to ivar offset location /// char *name; /// char *type; /// uint32_t alignment; /// uint32_t size; /// } /// struct _ivar_list_t { /// uint32 entsize; // sizeof(struct _ivar_t) /// uint32 count; /// struct _iver_t list[count]; /// } /// llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList( const ObjCImplementationDecl *ID) { ConstantInitBuilder builder(CGM); auto ivarList = builder.beginStruct(); ivarList.addInt(ObjCTypes.IntTy, CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy)); auto ivarCountSlot = ivarList.addPlaceholder(); auto ivars = ivarList.beginArray(ObjCTypes.IvarnfABITy); const ObjCInterfaceDecl *OID = ID->getClassInterface(); assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface"); // FIXME. Consolidate this with similar code in GenerateClass. for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); IVD; IVD = IVD->getNextIvar()) { // Ignore unnamed bit-fields. if (!IVD->getDeclName()) continue; auto ivar = ivars.beginStruct(ObjCTypes.IvarnfABITy); ivar.add(EmitIvarOffsetVar(ID->getClassInterface(), IVD, ComputeIvarBaseOffset(CGM, ID, IVD))); ivar.add(GetMethodVarName(IVD->getIdentifier())); ivar.add(GetMethodVarType(IVD)); llvm::Type *FieldTy = CGM.getTypes().ConvertTypeForMem(IVD->getType()); unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy); unsigned Align = CGM.getContext().getPreferredTypeAlign( IVD->getType().getTypePtr()) >> 3; Align = llvm::Log2_32(Align); ivar.addInt(ObjCTypes.IntTy, Align); // NOTE. Size of a bitfield does not match gcc's, because of the // way bitfields are treated special in each. But I am told that // 'size' for bitfield ivars is ignored by the runtime so it does // not matter. If it matters, there is enough info to get the // bitfield right! ivar.addInt(ObjCTypes.IntTy, Size); ivar.finishAndAddTo(ivars); } // Return null for empty list. if (ivars.empty()) { ivars.abandon(); ivarList.abandon(); return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy); } auto ivarCount = ivars.size(); ivars.finishAndAddTo(ivarList); ivarList.fillPlaceholderWithInt(ivarCountSlot, ObjCTypes.IntTy, ivarCount); const char *Prefix = "_OBJC_$_INSTANCE_VARIABLES_"; llvm::GlobalVariable *GV = finishAndCreateGlobal( ivarList, Prefix + OID->getObjCRuntimeNameAsString(), CGM); CGM.addCompilerUsedGlobal(GV); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy); } llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef( const ObjCProtocolDecl *PD) { llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()]; if (!Entry) { // We use the initializer as a marker of whether this is a forward // reference or not. At module finalization we add the empty // contents for protocols which were referenced but never defined. llvm::SmallString<64> Protocol; llvm::raw_svector_ostream(Protocol) << "_OBJC_PROTOCOL_$_" << PD->getObjCRuntimeNameAsString(); Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false, llvm::GlobalValue::ExternalLinkage, nullptr, Protocol); if (!CGM.getTriple().isOSBinFormatMachO()) Entry->setComdat(CGM.getModule().getOrInsertComdat(Protocol)); } return Entry; } /// GetOrEmitProtocol - Generate the protocol meta-data: /// @code /// struct _protocol_t { /// id isa; // NULL /// const char * const protocol_name; /// const struct _protocol_list_t * protocol_list; // super protocols /// const struct method_list_t * const instance_methods; /// const struct method_list_t * const class_methods; /// const struct method_list_t *optionalInstanceMethods; /// const struct method_list_t *optionalClassMethods; /// const struct _prop_list_t * properties; /// const uint32_t size; // sizeof(struct _protocol_t) /// const uint32_t flags; // = 0 /// const char ** extendedMethodTypes; /// const char *demangledName; /// const struct _prop_list_t * class_properties; /// } /// @endcode /// llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol( const ObjCProtocolDecl *PD) { llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()]; // Early exit if a defining object has already been generated. if (Entry && Entry->hasInitializer()) return Entry; // Use the protocol definition, if there is one. if (const ObjCProtocolDecl *Def = PD->getDefinition()) PD = Def; auto methodLists = ProtocolMethodLists::get(PD); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.ProtocolnfABITy); // isa is NULL values.addNullPointer(ObjCTypes.ObjectPtrTy); values.add(GetClassName(PD->getObjCRuntimeNameAsString())); values.add(EmitProtocolList("_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(), PD->protocol_begin(), PD->protocol_end())); values.add(methodLists.emitMethodList(this, PD, ProtocolMethodLists::RequiredInstanceMethods)); values.add(methodLists.emitMethodList(this, PD, ProtocolMethodLists::RequiredClassMethods)); values.add(methodLists.emitMethodList(this, PD, ProtocolMethodLists::OptionalInstanceMethods)); values.add(methodLists.emitMethodList(this, PD, ProtocolMethodLists::OptionalClassMethods)); values.add(EmitPropertyList( "_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(), nullptr, PD, ObjCTypes, false)); uint32_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy); values.addInt(ObjCTypes.IntTy, Size); values.addInt(ObjCTypes.IntTy, 0); values.add(EmitProtocolMethodTypes("_OBJC_$_PROTOCOL_METHOD_TYPES_" + PD->getObjCRuntimeNameAsString(), methodLists.emitExtendedTypesArray(this), ObjCTypes)); // const char *demangledName; values.addNullPointer(ObjCTypes.Int8PtrTy); values.add(EmitPropertyList( "_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(), nullptr, PD, ObjCTypes, true)); if (Entry) { // Already created, fix the linkage and update the initializer. Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage); values.finishAndSetAsInitializer(Entry); } else { llvm::SmallString<64> symbolName; llvm::raw_svector_ostream(symbolName) << "_OBJC_PROTOCOL_$_" << PD->getObjCRuntimeNameAsString(); Entry = values.finishAndCreateGlobal(symbolName, CGM.getPointerAlign(), /*constant*/ false, llvm::GlobalValue::WeakAnyLinkage); if (!CGM.getTriple().isOSBinFormatMachO()) Entry->setComdat(CGM.getModule().getOrInsertComdat(symbolName)); Protocols[PD->getIdentifier()] = Entry; } Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); CGM.addUsedGlobal(Entry); // Use this protocol meta-data to build protocol list table in section // __DATA, __objc_protolist llvm::SmallString<64> ProtocolRef; llvm::raw_svector_ostream(ProtocolRef) << "_OBJC_LABEL_PROTOCOL_$_" << PD->getObjCRuntimeNameAsString(); llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy, false, llvm::GlobalValue::WeakAnyLinkage, Entry, ProtocolRef); if (!CGM.getTriple().isOSBinFormatMachO()) PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolRef)); PTGV->setAlignment(llvm::Align( CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy))); PTGV->setSection(GetSectionName("__objc_protolist", "coalesced,no_dead_strip")); PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility); CGM.addUsedGlobal(PTGV); return Entry; } /// EmitProtocolList - Generate protocol list meta-data: /// @code /// struct _protocol_list_t { /// long protocol_count; // Note, this is 32/64 bit /// struct _protocol_t[protocol_count]; /// } /// @endcode /// llvm::Constant * CGObjCNonFragileABIMac::EmitProtocolList(Twine Name, ObjCProtocolDecl::protocol_iterator begin, ObjCProtocolDecl::protocol_iterator end) { SmallVector<llvm::Constant *, 16> ProtocolRefs; // Just return null for empty protocol lists if (begin == end) return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy); // FIXME: We shouldn't need to do this lookup here, should we? SmallString<256> TmpName; Name.toVector(TmpName); llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(TmpName.str(), true); if (GV) return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); auto countSlot = values.addPlaceholder(); // A null-terminated array of protocols. auto array = values.beginArray(ObjCTypes.ProtocolnfABIPtrTy); for (; begin != end; ++begin) array.add(GetProtocolRef(*begin)); // Implemented??? auto count = array.size(); array.addNullPointer(ObjCTypes.ProtocolnfABIPtrTy); array.finishAndAddTo(values); values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count); GV = finishAndCreateGlobal(values, Name, CGM); CGM.addCompilerUsedGlobal(GV); return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy); } /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference. /// This code gen. amounts to generating code for: /// @code /// (type *)((char *)base + _OBJC_IVAR_$_.ivar; /// @encode /// LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar( CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers) { ObjCInterfaceDecl *ID = ObjectTy->castAs<ObjCObjectType>()->getInterface(); llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar); return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers, Offset); } llvm::Value * CGObjCNonFragileABIMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar) { llvm::Value *IvarOffsetValue; if (isClassLayoutKnownStatically(Interface)) { IvarOffsetValue = llvm::ConstantInt::get( ObjCTypes.IvarOffsetVarTy, ComputeIvarBaseOffset(CGM, Interface->getImplementation(), Ivar)); } else { llvm::GlobalVariable *GV = ObjCIvarOffsetVariable(Interface, Ivar); IvarOffsetValue = CGF.Builder.CreateAlignedLoad(GV, CGF.getSizeAlign(), "ivar"); if (IsIvarOffsetKnownIdempotent(CGF, Ivar)) cast<llvm::LoadInst>(IvarOffsetValue) ->setMetadata(CGM.getModule().getMDKindID("invariant.load"), llvm::MDNode::get(VMContext, None)); } // This could be 32bit int or 64bit integer depending on the architecture. // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value // as this is what caller always expects. if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy) IvarOffsetValue = CGF.Builder.CreateIntCast( IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv"); return IvarOffsetValue; } static void appendSelectorForMessageRefTable(std::string &buffer, Selector selector) { if (selector.isUnarySelector()) { buffer += selector.getNameForSlot(0); return; } for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) { buffer += selector.getNameForSlot(i); buffer += '_'; } } /// Emit a "vtable" message send. We emit a weak hidden-visibility /// struct, initially containing the selector pointer and a pointer to /// a "fixup" variant of the appropriate objc_msgSend. To call, we /// load and call the function pointer, passing the address of the /// struct as the second parameter. The runtime determines whether /// the selector is currently emitted using vtable dispatch; if so, it /// substitutes a stub function which simply tail-calls through the /// appropriate vtable slot, and if not, it substitues a stub function /// which tail-calls objc_msgSend. Both stubs adjust the selector /// argument to correctly point to the selector. RValue CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF, ReturnValueSlot returnSlot, QualType resultType, Selector selector, llvm::Value *arg0, QualType arg0Type, bool isSuper, const CallArgList &formalArgs, const ObjCMethodDecl *method) { // Compute the actual arguments. CallArgList args; // First argument: the receiver / super-call structure. if (!isSuper) arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy); args.add(RValue::get(arg0), arg0Type); // Second argument: a pointer to the message ref structure. Leave // the actual argument value blank for now. args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy); args.insert(args.end(), formalArgs.begin(), formalArgs.end()); MessageSendInfo MSI = getMessageSendInfo(method, resultType, args); NullReturnState nullReturn; // Find the function to call and the mangled name for the message // ref structure. Using a different mangled name wouldn't actually // be a problem; it would just be a waste. // // The runtime currently never uses vtable dispatch for anything // except normal, non-super message-sends. // FIXME: don't use this for that. llvm::FunctionCallee fn = nullptr; std::string messageRefName("_"); if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) { if (isSuper) { fn = ObjCTypes.getMessageSendSuper2StretFixupFn(); messageRefName += "objc_msgSendSuper2_stret_fixup"; } else { nullReturn.init(CGF, arg0); fn = ObjCTypes.getMessageSendStretFixupFn(); messageRefName += "objc_msgSend_stret_fixup"; } } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) { fn = ObjCTypes.getMessageSendFpretFixupFn(); messageRefName += "objc_msgSend_fpret_fixup"; } else { if (isSuper) { fn = ObjCTypes.getMessageSendSuper2FixupFn(); messageRefName += "objc_msgSendSuper2_fixup"; } else { fn = ObjCTypes.getMessageSendFixupFn(); messageRefName += "objc_msgSend_fixup"; } } assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend"); messageRefName += '_'; // Append the selector name, except use underscores anywhere we // would have used colons. appendSelectorForMessageRefTable(messageRefName, selector); llvm::GlobalVariable *messageRef = CGM.getModule().getGlobalVariable(messageRefName); if (!messageRef) { // Build the message ref structure. ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(); values.add(cast<llvm::Constant>(fn.getCallee())); values.add(GetMethodVarName(selector)); messageRef = values.finishAndCreateGlobal(messageRefName, CharUnits::fromQuantity(16), /*constant*/ false, llvm::GlobalValue::WeakAnyLinkage); messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility); messageRef->setSection(GetSectionName("__objc_msgrefs", "coalesced")); } bool requiresnullCheck = false; if (CGM.getLangOpts().ObjCAutoRefCount && method) for (const auto *ParamDecl : method->parameters()) { if (ParamDecl->hasAttr<NSConsumedAttr>()) { if (!nullReturn.NullBB) nullReturn.init(CGF, arg0); requiresnullCheck = true; break; } } Address mref = Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy), CGF.getPointerAlign()); // Update the message ref argument. args[1].setRValue(RValue::get(mref.getPointer())); // Load the function to call from the message ref table. Address calleeAddr = CGF.Builder.CreateStructGEP(mref, 0); llvm::Value *calleePtr = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn"); calleePtr = CGF.Builder.CreateBitCast(calleePtr, MSI.MessengerType); CGPointerAuthInfo pointerAuth; // This code path is unsupported. CGCallee callee(CGCalleeInfo(), calleePtr, pointerAuth); RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args); return nullReturn.complete(CGF, returnSlot, result, resultType, formalArgs, requiresnullCheck ? method : nullptr); } /// Generate code for a message send expression in the nonfragile abi. CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, llvm::Value *Receiver, const CallArgList &CallArgs, const ObjCInterfaceDecl *Class, const ObjCMethodDecl *Method) { return isVTableDispatchedSelector(Sel) ? EmitVTableMessageSend(CGF, Return, ResultType, Sel, Receiver, CGF.getContext().getObjCIdType(), false, CallArgs, Method) : EmitMessageSend(CGF, Return, ResultType, Sel, Receiver, CGF.getContext().getObjCIdType(), false, CallArgs, Method, Class, ObjCTypes); } llvm::Constant * CGObjCNonFragileABIMac::GetClassGlobal(const ObjCInterfaceDecl *ID, bool metaclass, ForDefinition_t isForDefinition) { auto prefix = (metaclass ? getMetaclassSymbolPrefix() : getClassSymbolPrefix()); return GetClassGlobal((prefix + ID->getObjCRuntimeNameAsString()).str(), isForDefinition, ID->isWeakImported(), !isForDefinition && CGM.getTriple().isOSBinFormatCOFF() && ID->hasAttr<DLLImportAttr>()); } llvm::Constant * CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name, ForDefinition_t IsForDefinition, bool Weak, bool DLLImport) { llvm::GlobalValue::LinkageTypes L = Weak ? llvm::GlobalValue::ExternalWeakLinkage : llvm::GlobalValue::ExternalLinkage; llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name); if (!GV || GV->getType() != ObjCTypes.ClassnfABITy->getPointerTo()) { auto *NewGV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, L, nullptr, Name); if (DLLImport) NewGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); if (GV) { GV->replaceAllUsesWith( llvm::ConstantExpr::getBitCast(NewGV, GV->getType())); GV->eraseFromParent(); } GV = NewGV; CGM.getModule().getGlobalList().push_back(GV); } assert(GV->getLinkage() == L); if (IsForDefinition || GV->getValueType() == ObjCTypes.ClassnfABITy) return GV; return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ClassnfABIPtrTy); } llvm::Constant * CGObjCNonFragileABIMac::GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID) { llvm::Constant *ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition); if (!ID->hasAttr<ObjCClassStubAttr>()) return ClassGV; ClassGV = llvm::ConstantExpr::getPointerCast(ClassGV, ObjCTypes.Int8PtrTy); // Stub classes are pointer-aligned. Classrefs pointing at stub classes // must set the least significant bit set to 1. auto *Idx = llvm::ConstantInt::get(CGM.Int32Ty, 1); return llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, ClassGV, Idx); } llvm::Value * CGObjCNonFragileABIMac::EmitLoadOfClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID, llvm::GlobalVariable *Entry) { if (ID && ID->hasAttr<ObjCClassStubAttr>()) { // Classrefs pointing at Objective-C stub classes must be loaded by calling // a special runtime function. return CGF.EmitRuntimeCall( ObjCTypes.getLoadClassrefFn(), Entry, "load_classref_result"); } CharUnits Align = CGF.getPointerAlign(); return CGF.Builder.CreateAlignedLoad(Entry, Align); } llvm::Value * CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF, IdentifierInfo *II, const ObjCInterfaceDecl *ID) { llvm::GlobalVariable *&Entry = ClassReferences[II]; if (!Entry) { llvm::Constant *ClassGV; if (ID) { ClassGV = GetClassGlobalForClassRef(ID); } else { ClassGV = GetClassGlobal((getClassSymbolPrefix() + II->getName()).str(), NotForDefinition); assert(ClassGV->getType() == ObjCTypes.ClassnfABIPtrTy && "classref was emitted with the wrong type?"); } std::string SectionName = GetSectionName("__objc_classrefs", "regular,no_dead_strip"); Entry = new llvm::GlobalVariable( CGM.getModule(), ClassGV->getType(), false, getLinkageTypeForObjCMetadata(CGM, SectionName), ClassGV, "OBJC_CLASSLIST_REFERENCES_$_"); Entry->setAlignment(CGF.getPointerAlign().getAsAlign()); if (!ID || !ID->hasAttr<ObjCClassStubAttr>()) Entry->setSection(SectionName); CGM.addCompilerUsedGlobal(Entry); } return EmitLoadOfClassRef(CGF, ID, Entry); } llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { // If the class has the objc_runtime_visible attribute, we need to // use the Objective-C runtime to get the class. if (ID->hasAttr<ObjCRuntimeVisibleAttr>()) return EmitClassRefViaRuntime(CGF, ID, ObjCTypes); return EmitClassRefFromId(CGF, ID->getIdentifier(), ID); } llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef( CodeGenFunction &CGF) { IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool"); return EmitClassRefFromId(CGF, II, nullptr); } llvm::Value * CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()]; if (!Entry) { llvm::Constant *ClassGV = GetClassGlobalForClassRef(ID); std::string SectionName = GetSectionName("__objc_superrefs", "regular,no_dead_strip"); Entry = new llvm::GlobalVariable( CGM.getModule(), ClassGV->getType(), false, getLinkageTypeForObjCMetadata(CGM, SectionName), ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_"); Entry->setAlignment(CGF.getPointerAlign().getAsAlign()); Entry->setSection(SectionName); CGM.addCompilerUsedGlobal(Entry); } return EmitLoadOfClassRef(CGF, ID, Entry); } /// EmitMetaClassRef - Return a Value * of the address of _class_t /// meta-data /// llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID, bool Weak) { CharUnits Align = CGF.getPointerAlign(); llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()]; if (!Entry) { auto MetaClassGV = GetClassGlobal(ID, /*metaclass*/ true, NotForDefinition); std::string SectionName = GetSectionName("__objc_superrefs", "regular,no_dead_strip"); Entry = new llvm::GlobalVariable( CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, false, getLinkageTypeForObjCMetadata(CGM, SectionName), MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_"); Entry->setAlignment(Align.getAsAlign()); Entry->setSection(SectionName); CGM.addCompilerUsedGlobal(Entry); } return CGF.Builder.CreateAlignedLoad(Entry, Align); } /// GetClass - Return a reference to the class for the given interface /// decl. llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF, const ObjCInterfaceDecl *ID) { if (ID->isWeakImported()) { llvm::Constant *ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition); (void)ClassGV; assert(!isa<llvm::GlobalVariable>(ClassGV) || cast<llvm::GlobalVariable>(ClassGV)->hasExternalWeakLinkage()); } return EmitClassRef(CGF, ID); } /// Generates a message send where the super is the receiver. This is /// a message send to self with special delivery semantics indicating /// which class's method should be called. CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class, bool isCategoryImpl, llvm::Value *Receiver, bool IsClassMessage, const CodeGen::CallArgList &CallArgs, const ObjCMethodDecl *Method) { // ... // Create and init a super structure; this is a (receiver, class) // pair we will pass to objc_msgSendSuper. Address ObjCSuper = CGF.CreateTempAlloca(ObjCTypes.SuperTy, CGF.getPointerAlign(), "objc_super"); llvm::Value *ReceiverAsObject = CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy); CGF.Builder.CreateStore(ReceiverAsObject, CGF.Builder.CreateStructGEP(ObjCSuper, 0)); // If this is a class message the metaclass is passed as the target. llvm::Value *Target; if (IsClassMessage) Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported()); else Target = EmitSuperClassRef(CGF, Class); // FIXME: We shouldn't need to do this cast, rectify the ASTContext and // ObjCTypes types. llvm::Type *ClassTy = CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType()); Target = CGF.Builder.CreateBitCast(Target, ClassTy); CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1)); return (isVTableDispatchedSelector(Sel)) ? EmitVTableMessageSend(CGF, Return, ResultType, Sel, ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy, true, CallArgs, Method) : EmitMessageSend(CGF, Return, ResultType, Sel, ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy, true, CallArgs, Method, Class, ObjCTypes); } llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) { Address Addr = EmitSelectorAddr(Sel); llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr); LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), llvm::MDNode::get(VMContext, None)); return LI; } Address CGObjCNonFragileABIMac::EmitSelectorAddr(Selector Sel) { llvm::GlobalVariable *&Entry = SelectorReferences[Sel]; CharUnits Align = CGM.getPointerAlign(); if (!Entry) { llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel), ObjCTypes.SelectorPtrTy); std::string SectionName = GetSectionName("__objc_selrefs", "literal_pointers,no_dead_strip"); Entry = new llvm::GlobalVariable( CGM.getModule(), ObjCTypes.SelectorPtrTy, false, getLinkageTypeForObjCMetadata(CGM, SectionName), Casted, "OBJC_SELECTOR_REFERENCES_"); Entry->setExternallyInitialized(true); Entry->setSection(SectionName); Entry->setAlignment(Align.getAsAlign()); CGM.addCompilerUsedGlobal(Entry); } return Address(Entry, Align); } /// EmitObjCIvarAssign - Code gen for assigning to a __strong object. /// objc_assign_ivar (id src, id *dst, ptrdiff_t) /// void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst, llvm::Value *ivarOffset) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer(), ivarOffset }; CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args); } /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object. /// objc_assign_strongCast (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign( CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer() }; CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(), args, "weakassign"); } void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable( CodeGen::CodeGenFunction &CGF, Address DestPtr, Address SrcPtr, llvm::Value *Size) { SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy); DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy); llvm::Value *args[] = { DestPtr.getPointer(), SrcPtr.getPointer(), Size }; CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args); } /// EmitObjCWeakRead - Code gen for loading value of a __weak /// object: objc_read_weak (id *src) /// llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead( CodeGen::CodeGenFunction &CGF, Address AddrWeakObj) { llvm::Type *DestTy = AddrWeakObj.getElementType(); AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy); llvm::Value *read_weak = CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(), AddrWeakObj.getPointer(), "weakread"); read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy); return read_weak; } /// EmitObjCWeakAssign - Code gen for assigning to a __weak object. /// objc_assign_weak (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer() }; CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(), args, "weakassign"); } /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object. /// objc_assign_global (id src, id *dst) /// void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dst, bool threadlocal) { llvm::Type * SrcTy = src->getType(); if (!isa<llvm::PointerType>(SrcTy)) { unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy); assert(Size <= 8 && "does not support size > 8"); src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy) : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy)); src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy); } src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy); dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy); llvm::Value *args[] = { src, dst.getPointer() }; if (!threadlocal) CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(), args, "globalassign"); else CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(), args, "threadlocalassign"); } void CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtSynchronizedStmt &S) { EmitAtSynchronizedStmt(CGF, S, ObjCTypes.getSyncEnterFn(), ObjCTypes.getSyncExitFn()); } llvm::Constant * CGObjCNonFragileABIMac::GetEHType(QualType T) { // There's a particular fixed type info for 'id'. if (T->isObjCIdType() || T->isObjCQualifiedIdType()) { auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id"); if (!IDEHType) { IDEHType = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, "OBJC_EHTYPE_id"); if (CGM.getTriple().isOSBinFormatCOFF()) IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id")); } return IDEHType; } // All other types should be Objective-C interface pointer types. const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); assert(PT && "Invalid @catch type."); const ObjCInterfaceType *IT = PT->getInterfaceType(); assert(IT && "Invalid @catch type."); return GetInterfaceEHType(IT->getDecl(), NotForDefinition); } void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtTryStmt &S) { EmitTryCatchStmt(CGF, S, ObjCTypes.getObjCBeginCatchFn(), ObjCTypes.getObjCEndCatchFn(), ObjCTypes.getExceptionRethrowFn()); } /// EmitThrowStmt - Generate code for a throw statement. void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint) { if (const Expr *ThrowExpr = S.getThrowExpr()) { llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr); Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy); llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception); Call->setDoesNotReturn(); } else { llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn()); Call->setDoesNotReturn(); } CGF.Builder.CreateUnreachable(); if (ClearInsertionPoint) CGF.Builder.ClearInsertionPoint(); } llvm::Constant * CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID, ForDefinition_t IsForDefinition) { llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()]; StringRef ClassName = ID->getObjCRuntimeNameAsString(); // If we don't need a definition, return the entry if found or check // if we use an external reference. if (!IsForDefinition) { if (Entry) return Entry; // If this type (or a super class) has the __objc_exception__ // attribute, emit an external reference. if (hasObjCExceptionAttribute(CGM.getContext(), ID)) { std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str(); Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, EHTypeName); CGM.setGVProperties(Entry, ID); return Entry; } } // Otherwise we need to either make a new entry or fill in the initializer. assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition"); std::string VTableName = "objc_ehtype_vtable"; auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName); if (!VTableGV) { VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false, llvm::GlobalValue::ExternalLinkage, nullptr, VTableName); if (CGM.getTriple().isOSBinFormatCOFF()) VTableGV->setDLLStorageClass(getStorage(CGM, VTableName)); } llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2); llvm::Constant *VTablePtr = llvm::ConstantExpr::getInBoundsGetElementPtr( VTableGV->getValueType(), VTableGV, VTableIdx); ConstantInitBuilder builder(CGM); auto values = builder.beginStruct(ObjCTypes.EHTypeTy); if (auto &Schema = CGM.getCodeGenOpts().PointerAuth.CXXVTablePointers) { values.addSignedPointer(VTablePtr, Schema, GlobalDecl(), QualType()); } else { values.add(VTablePtr); } values.add(GetClassName(ClassName)); values.add(GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition)); llvm::GlobalValue::LinkageTypes L = IsForDefinition ? llvm::GlobalValue::ExternalLinkage : llvm::GlobalValue::WeakAnyLinkage; if (Entry) { values.finishAndSetAsInitializer(Entry); Entry->setAlignment(CGM.getPointerAlign().getAsAlign()); } else { Entry = values.finishAndCreateGlobal("OBJC_EHTYPE_$_" + ClassName, CGM.getPointerAlign(), /*constant*/ false, L); if (hasObjCExceptionAttribute(CGM.getContext(), ID)) CGM.setGVProperties(Entry, ID); } assert(Entry->getLinkage() == L); if (!CGM.getTriple().isOSBinFormatCOFF()) if (ID->getVisibility() == HiddenVisibility) Entry->setVisibility(llvm::GlobalValue::HiddenVisibility); if (IsForDefinition) if (CGM.getTriple().isOSBinFormatMachO()) Entry->setSection("__DATA,__objc_const"); return Entry; } /* *** */ CodeGen::CGObjCRuntime * CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) { switch (CGM.getLangOpts().ObjCRuntime.getKind()) { case ObjCRuntime::FragileMacOSX: return new CGObjCMac(CGM); case ObjCRuntime::MacOSX: case ObjCRuntime::iOS: case ObjCRuntime::WatchOS: return new CGObjCNonFragileABIMac(CGM); case ObjCRuntime::GNUstep: case ObjCRuntime::GCC: case ObjCRuntime::ObjFW: llvm_unreachable("these runtimes are not Mac runtimes"); } llvm_unreachable("bad runtime"); }
ORG 0000H SETB P3.5 CLR P1.2 MOV P2, #00H MOV TMOD, #01100010B ; Counter-1 Mode-2 & Timer-0 Mode-1 MOV TH1, #00H CLR A SETB TR1 INC A HERE: MOV A, TL1 MOV P2, A ; Gives the value of TL1 to P2 CPL P3.5 MOV R7, #255 ACALL DELAY CJNE A, #0AH, HERE ; 10 number of counts done CLR TF1 CLR TR1 AGAIN: MOV TH0, #0FEH MOV TL0, #32H SETB TR0 CPL P1.2 LOOP: JNB TF0, LOOP CLR TR0 CLR TF0 SJMP AGAIN DELAY: DJNZ R7, DELAY RET END
.NOLIST #define EQU .equ #define equ .equ #define END .end #define end .end #include "ti83plus.inc" .LIST .org 9D93h .db $BB,$6D ld a,0 ld (CURCOL),a ld (CURROW),a ld hl,text B_CALL(_PutS) B_CALL(_NewLine) ret text: .db "Hello World",0 .end end
LDA #$03 JMP there BRK BRK BRK there: STA $0200
// #include <eosio/transaction.hpp> // #include <eosio.system/native.hpp> #include "exchange_state.hpp" #include "../src/exchange_state.cpp" #include <eosio/crypto.hpp> uint128_t combine_ids(const uint64_t &x, const uint64_t &y) { return (uint128_t{x} << 64) | y; }; /*! \brief Структура основных параметров конфигурации Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] spiral{ uint64_t id; uint64_t size_of_pool; uint64_t quants_precision = 0; uint64_t overlap; uint64_t profit_growth; uint64_t base_rate; uint64_t loss_percent; uint64_t pool_limit; uint64_t pool_timeout; uint64_t priority_seconds; uint64_t primary_key() const {return id;} EOSLIB_SERIALIZE(spiral, (id)(size_of_pool)(quants_precision)(overlap)(profit_growth)(base_rate)(loss_percent)(pool_limit)(pool_timeout)(priority_seconds)) }; typedef eosio::multi_index<"spiral"_n, spiral> spiral_index; /*! \brief Структура компенсационных параметров конфигурации Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] spiral2 { uint64_t id; uint64_t compensator_percent; uint64_t primary_key() const {return id;} EOSLIB_SERIALIZE(spiral2, (id)(compensator_percent)) }; typedef eosio::multi_index<"spiral2"_n, spiral2> spiral2_index; /*! \brief Структура курсов реализации внутренней конвертационной единицы и их возврата Протоколу. */ struct [[eosio::table, eosio::contract("unicore")]] rate { uint64_t pool_id; uint64_t buy_rate=0; uint64_t sell_rate=0; uint64_t convert_rate=0; eosio::asset quant_buy_rate; eosio::asset quant_sell_rate; eosio::asset quant_convert_rate; eosio::asset client_income; eosio::asset delta; eosio::asset pool_cost; eosio::asset total_in_box; // eosio::asset total_on_convert; eosio::asset payment_to_wins; eosio::asset payment_to_loss; eosio::asset system_income; eosio::asset live_balance_for_sale; eosio::asset live_balance_for_convert; uint64_t primary_key() const{return pool_id;} EOSLIB_SERIALIZE(rate, (pool_id)(buy_rate)(sell_rate)(convert_rate)(quant_buy_rate)(quant_sell_rate)(quant_convert_rate)(client_income)(delta)(pool_cost)(total_in_box)(payment_to_wins)(payment_to_loss)(system_income)(live_balance_for_sale)(live_balance_for_convert)) }; typedef eosio::multi_index<"rate"_n, rate> rate_index; /*! \brief Структура хоста Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] hosts{ eosio::name username; eosio::time_point_sec registered_at; eosio::name architect; eosio::name hoperator; eosio::name type; eosio::name chat_mode; uint64_t consensus_percent; uint64_t referral_percent; uint64_t dacs_percent; uint64_t cfund_percent; uint64_t hfund_percent; uint64_t sys_percent; std::vector<uint64_t> levels; std::vector<eosio::name> gsponsor_model; bool direct_goal_withdraw = false; uint64_t dac_mode; uint64_t total_dacs_weight; eosio::name ahost; std::vector<eosio::name> chosts; bool sale_is_enabled = false; eosio::name sale_mode; eosio::name sale_token_contract; eosio::asset asset_on_sale; uint64_t asset_on_sale_precision; std::string asset_on_sale_symbol; int64_t sale_shift = 0; //Метод добавления хоста в фонд //Метод включения сейла хостом bool non_active_chost = false; bool need_switch = false; uint64_t fhosts_mode; std::vector<eosio::name> fhosts; std::string title; std::string purpose; bool voting_only_up = false; eosio::name power_market_id; uint64_t total_shares; eosio::asset quote_amount; eosio::name quote_token_contract; std::string quote_symbol; uint64_t quote_precision; eosio::name root_token_contract; eosio::asset root_token; std::string symbol; uint64_t precision; eosio::asset to_pay; bool payed = false; uint64_t cycle_start_id = 0; uint64_t current_pool_id = 0; uint64_t current_cycle_num = 1; uint64_t current_pool_num = 1; bool parameters_setted = false; bool activated = false; bool priority_flag = false; uint64_t total_goals = 0; uint64_t achieved_goals = 0; uint64_t total_tasks = 0; uint64_t completed_tasks = 0; uint64_t total_reports = 0; uint64_t approved_reports = 0; std::string meta; EOSLIB_SERIALIZE( hosts, (username)(registered_at)(architect)(hoperator)(type)(chat_mode)(consensus_percent)(referral_percent) (dacs_percent)(cfund_percent)(hfund_percent)(sys_percent)(levels)(gsponsor_model)(direct_goal_withdraw)(dac_mode)(total_dacs_weight)(ahost)(chosts) (sale_is_enabled)(sale_mode)(sale_token_contract)(asset_on_sale)(asset_on_sale_precision)(asset_on_sale_symbol)(sale_shift) (non_active_chost)(need_switch)(fhosts_mode)(fhosts) (title)(purpose)(voting_only_up)(power_market_id)(total_shares)(quote_amount)(quote_token_contract)(quote_symbol)(quote_precision)(root_token_contract)(root_token)(symbol)(precision) (to_pay)(payed)(cycle_start_id)(current_pool_id) (current_cycle_num)(current_pool_num)(parameters_setted)(activated)(priority_flag)(total_goals)(achieved_goals)(total_tasks)(completed_tasks)(total_reports)(approved_reports)(meta)) uint64_t primary_key()const { return username.value; } // eosoi::name gsponsor_model_is_exist(eosio::name model) const { // auto it = std::find(gsponsor_model.begin(), gsponsor_model.end(), model); // if (it == gsponsor_model.end()) // return false; // else // return true; // } eosio::name get_ahost() const { if (ahost == username) return username; else return ahost; } eosio::symbol get_root_symbol() const { return root_token.symbol; } // bool is_account_in_whitelist(eosio::name username) const { // auto it = std::find(whitelist.begin(), whitelist.end(), username); // if (it == whitelist.end()) // return false; // else // return true; // } }; typedef eosio::multi_index <"hosts"_n, hosts> account_index; /*! \brief Расширение структуры хоста Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] hosts2 { eosio::name username; eosio::time_point_sec sale_price_updated_at; uint64_t sale_price; EOSLIB_SERIALIZE( hosts2, (username)(sale_price_updated_at)(sale_price)) uint64_t primary_key()const { return username.value; } }; typedef eosio::multi_index <"hosts2"_n, hosts2> account2_index; /*! \brief Структура командных ролей протокола. */ struct [[eosio::table, eosio::contract("unicore")]] roles { uint64_t role_id; eosio::name model; eosio::name lang; std::string title; std::string descriptor; eosio::name suggester; bool approved = false; uint64_t primary_key() const {return role_id;} EOSLIB_SERIALIZE(roles, (role_id)(model)(lang)(title)(descriptor)(suggester)(approved)) }; typedef eosio::multi_index <"roles"_n, roles> roles_index; /*! \brief Структура вакансии хоста Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] vacs { uint64_t id; eosio::name creator; bool approved; bool closed = false; eosio::name limit_type; eosio::asset income_limit; uint64_t proposals; uint64_t weight; std::string role; std::string description; uint64_t primary_key() const {return id;} uint64_t bycreator() const {return creator.value;} EOSLIB_SERIALIZE(vacs, (id)(creator)(approved)(closed)(limit_type)(income_limit)(proposals)(weight)(role)(description)) }; typedef eosio::multi_index <"vacs"_n, vacs, eosio::indexed_by<"bycreator"_n, eosio::const_mem_fun<vacs, uint64_t, &vacs::bycreator>> > vacs_index; /*! \brief Структура заявки на вакансию хоста Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] vproposal { uint64_t id; uint64_t vac_id; eosio::name creator; eosio::name limit_type; eosio::name income_limit; uint64_t weight; bool closed = false; std::string why_me; std::string contacts; int64_t votes; uint64_t primary_key() const {return id;} uint64_t byusername() const {return creator.value;} uint64_t byvacid() const {return vac_id;} uint64_t byvotes() const {return votes;} EOSLIB_SERIALIZE(vproposal, (id)(vac_id)(creator)(limit_type)(income_limit)(weight)(closed)(why_me)(contacts)(votes)) }; typedef eosio::multi_index <"vproposal"_n, vproposal, eosio::indexed_by<"byusername"_n, eosio::const_mem_fun<vproposal, uint64_t, &vproposal::byusername>>, eosio::indexed_by<"byvacid"_n, eosio::const_mem_fun<vproposal, uint64_t, &vproposal::byvacid>>, eosio::indexed_by<"byvotes"_n, eosio::const_mem_fun<vproposal, uint64_t, &vproposal::byvotes>> > vproposal_index; /*! \brief Структура команды хоста Двойной Спирали. */ struct [[eosio::table, eosio::contract("unicore")]] dacs { eosio::name dac; eosio::name limit_type; uint64_t weight; eosio::asset income; uint128_t income_in_segments; eosio::asset withdrawed; eosio::asset income_limit; eosio::time_point_sec last_pay_at; eosio::time_point_sec created_at; std::string role; std::string description; uint64_t primary_key() const {return dac.value;} uint64_t bylimittype() const {return limit_type.value;} EOSLIB_SERIALIZE(dacs, (dac)(limit_type)(weight)(income)(income_in_segments)(withdrawed)(income_limit)(last_pay_at)(created_at)(role)(description)) }; typedef eosio::multi_index <"dacs"_n, dacs> dacs_index; /*! \brief Структура параметров эмиссии целевого фонда хоста Двойной Спирали */ struct [[eosio::table, eosio::contract("unicore")]] emission { eosio::name host; uint64_t percent; uint64_t gtop; eosio::asset fund; uint64_t primary_key() const {return host.value;} EOSLIB_SERIALIZE(emission, (host)(percent)(gtop)(fund)) }; typedef eosio::multi_index<"emission"_n, emission> emission_index; /*! \brief Структура глобальных фондов владельцев жетонов, помещенных на распределение. */ struct [[eosio::table, eosio::contract("unicore")]] funds{ uint64_t id; eosio::name issuer; eosio::name token_contract; eosio::asset fund; std::string descriptor; uint64_t primary_key()const { return id; } uint64_t byissuer()const { return issuer.value; } uint128_t codeandsmbl() const {return combine_ids(token_contract.value, fund.symbol.code().raw());} EOSLIB_SERIALIZE(funds, (id)(issuer)(token_contract)(fund)(descriptor)) }; typedef eosio::multi_index<"funds"_n, funds, eosio::indexed_by<"codeandsmbl"_n, eosio::const_mem_fun<funds, uint128_t, &funds::codeandsmbl>>, eosio::indexed_by<"byissuer"_n, eosio::const_mem_fun<funds, uint64_t, &funds::byissuer>> > funds_index; // struct [[eosio::table, eosio::contract("unicore")]] histoffund{ // uint64_t id; // uint64_t fund_id; // eosio::name type; // eosio::asset quantity; // std::string memo; // uint64_t primary_key()const { return id; } // EOSLIB_SERIALIZE(histoffund, (id)(fund_id)(type)(quantity)(memo)) // } /*! \brief Структура хостов Двойной Спирали, подключенных к глобальным фондам распределения. */ struct [[eosio::table, eosio::contract("unicore")]] hostsonfunds{ uint64_t id; uint64_t fund_id; eosio::name host; uint64_t primary_key()const { return id; } uint128_t fundandhost() const {return combine_ids(fund_id, host.value);} EOSLIB_SERIALIZE(hostsonfunds, (id)(fund_id)(host)) }; typedef eosio::multi_index<"hostsonfunds"_n, hostsonfunds, eosio::indexed_by<"fundandhost"_n, eosio::const_mem_fun<hostsonfunds, uint128_t, &hostsonfunds::fundandhost>> > hostsonfunds_index;
; A323048: Sums of no more than two 5-smooth numbers. ; 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100 mov $1,$0 add $0,1 div $0,36 mul $0,2 div $0,4 add $0,$1
; A131878: Row sums of triangle A131876. ; 1,22,57,106,169,246,337,442,561,694,841,988,1163,1352,1555,1772,2003,2248,2507,2780,3067,3368,3683,4012,4355,4712,5083,5468,5867,6280,6707,7148,7603,8072,8569,9066,9577,10102,10641 mov $2,1 mov $3,$0 mov $7,$0 add $0,1 add $2,$3 mul $3,2 mov $6,2 lpb $0,1 mov $0,$3 sub $0,29 mov $3,$2 log $3,24 sub $6,6 add $0,$6 mul $2,$1 add $2,4 pow $2,2 add $2,5 lpe add $2,$0 mov $1,$2 sub $1,1 mov $4,$7 mov $5,$7 mul $5,12 add $1,$5 mul $4,$7 mov $5,$4 mul $5,7 add $1,$5
; ; Generic pseudo graphics routines for text-only platforms ; Version for the 2x3 graphics symbols ; ; Written by Stefano Bodrato 19/12/2006 ; ; ; Invert pixel at (x,y) coordinate. ; ; ; $Id: xorpixl.asm,v 1.4 2015/01/19 01:32:51 pauloscustodio Exp $ ; INCLUDE "graphics/grafix.inc" PUBLIC xorpixel EXTERN textpixl EXTERN div3 EXTERN coords EXTERN base_graphics .xorpixel ld a,h cp maxx ret nc ld a,l cp maxy ret nc ; y0 out of range inc a ld (coords),hl push bc ld c,a ; y ld b,h ; x push bc ld hl,div3 ld d,0 ld e,c adc hl,de ld a,(hl) ld c,a ; y/3 srl b ; x/2 ld hl,(base_graphics) ld a,c ld c,b ; !! and a ld de,maxx/2 sbc hl,de jr z,r_zero ld b,a .r_loop add hl,de djnz r_loop .r_zero ; hl = char address ld b,a ; keep y/3 ld e,c add hl,de ld a,(hl) ; get current symbol from screen ld e,a ; ..and its copy push hl ; char address push bc ; keep y/3 ld hl,textpixl ld e,0 ld b,64 ; whole symbol table size .ckmap cp (hl) ; compare symbol with the one in map jr z,chfound inc hl inc e djnz ckmap ld e,0 .chfound ld a,e pop bc ; restore y/3 in b pop hl ; char address ex (sp),hl ; save char address <=> restore x,y (y=h, x=l) ld c,a ; keep the symbol ld a,l inc a inc a sub b sub b sub b ; we get the remainder of y/3 ld l,a ld a,1 ; the pixel we want to draw jr z,iszero bit 0,l jr nz,is1 add a,a add a,a .is1 add a,a add a,a .iszero bit 0,h jr z,evenrow add a,a ; move down the bit .evenrow xor c ld hl,textpixl ld d,0 ld e,a add hl,de ld a,(hl) pop hl ld (hl),a pop bc ret
/* Copyright 2019-2021 Canaan Inc. * * 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 <nncase/ir/visitor.h> #include <queue> using namespace nncase; using namespace nncase::ir; void ir_visitor::visit(graph &graph) { visit(graph.outputs()); } void ir_visitor::visit(std::span<output_node *> outputs) { visited_.clear(); for (auto &&out : outputs) { if (visit_strategy(*out)) return; } } bool ir_visitor::visited(node &node) const noexcept { return visited_.find(&node) != visited_.end(); } void ir_visitor::mark_visit(node &node) { visited_.emplace(&node); } bool ir_visitor::visit([[maybe_unused]] node &node) { return false; } bool dfs_ir_pre_order_visitor::visit_strategy(node &node) { if (!visited(node)) { mark_visit(node); if (visit(node)) return true; for (auto in : node.inputs()) { if (in->connection()) { if (visit_strategy(in->connection()->owner())) return true; } } } return false; } bool dfs_ir_post_order_visitor::visit_strategy(node &node) { if (!visited(node)) { mark_visit(node); for (auto in : node.inputs()) { if (in->connection()) { if (visit_strategy(in->connection()->owner())) return true; } } if (visit(node)) return true; } return false; } bool bfs_ir_pre_order_visitor::visit_strategy(node &node) { std::queue<nncase::ir::node *> nodes; nodes.push(&node); while (!nodes.empty()) { auto p = nodes.front(); nodes.pop(); mark_visit(*p); visit(*p); for (auto in : p->inputs()) { if (in->connection()) { auto &in_node = in->connection()->owner(); if (!visited(in_node)) nodes.push(&in_node); } } } return false; }
; A024920: a(n) = Sum_{k=1..n} (n-k) * floor(n/k). ; 0,2,7,17,29,51,71,104,138,183,220,293,340,409,486,580,646,767,843,981,1099,1221,1317,1525,1653,1802,1961,2168,2297,2568,2709,2951,3154,3359,3578,3942,4118,4352,4598,4978,5176,5576,5786,6136,6504,6798,7030,7574,7862,8270,8609,9034,9303,9834,10209,10768,11155,11540,11845,12646,12967,13382,13923,14517,14973,15641,15999,16575,17055,17775,18157,19140,19538,20048,20706,21360,21916,22720,23154,24126,24778,25353,25812,26975,27598,28205,28832,29759,30258,31517,32194,33007,33686,34357,35060,36407,36962 mov $2,$0 add $0,2 lpb $2 sub $0,1 add $3,1 mov $4,$0 lpb $4 add $1,$2 trn $4,$3 lpe sub $2,1 lpe mov $0,$1
; A189461: n+[nr/s]+[nt/s]; r=2, s=sqrt(5), t=1+sqrt(5). ; Submitted by Jon Maiga ; 2,5,9,12,16,19,23,26,30,32,35,39,42,46,49,53,56,60,62,65,69,72,76,79,83,86,90,93,95,99,102,106,109,113,116,120,123,125,129,132,136,139,143,146,150,153,157,159,162,166,169,173,176,180,183,187,189,192,196,199,203,206,210,213,217,220,222,226,229,233,236,240,243,247,250,252,256,259,263,266,270,273,277,280,284,286,289,293,296,300,303,307,310,314,316,319,323,326,330,333 mov $1,$0 seq $0,330185 ; a(n) = n + floor(ns/r) + floor(nt/r), where r = tau - 1/2, s = tau, t = tau + 1/2, tau = golden ratio = (1+sqrt(5))/2. sub $0,$1 sub $0,1
; A021622: Decimal expansion of 1/618. ; Submitted by Christian Krause ; 0,0,1,6,1,8,1,2,2,9,7,7,3,4,6,2,7,8,3,1,7,1,5,2,1,0,3,5,5,9,8,7,0,5,5,0,1,6,1,8,1,2,2,9,7,7,3,4,6,2,7,8,3,1,7,1,5,2,1,0,3,5,5,9,8,7,0,5,5,0,1,6,1,8,1,2,2,9,7,7,3,4,6,2,7,8,3,1,7,1,5,2,1,0,3,5,5,9,8 seq $0,246057 ; a(n) = (5*10^n - 2)/3. div $0,103 mod $0,10
/* * Copyright 2015 Facebook, Inc. * * 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 <gtest/gtest.h> #include <folly/IPAddressV6.h> #include <folly/MacAddress.h> using folly::MacAddress; using folly::IPAddressV6; using folly::StringPiece; void testMAC(const std::string& str, uint64_t expectedHBO) { SCOPED_TRACE(str); MacAddress addr(str); // Make sure parsing returned the expected value. EXPECT_EQ(expectedHBO, addr.u64HBO()); // Perform additional checks on the MacAddress // Check using operator==() EXPECT_EQ(MacAddress::fromHBO(expectedHBO), addr); // Check using operator==() when passing in non-zero padding bytes EXPECT_EQ(MacAddress::fromHBO(expectedHBO | 0xa5a5000000000000), addr); // Similar checks after converting to network byte order uint64_t expectedNBO = folly::Endian::big(expectedHBO); EXPECT_EQ(expectedNBO, addr.u64NBO()); EXPECT_EQ(MacAddress::fromNBO(expectedNBO), addr); uint64_t nboWithPad = folly::Endian::big(expectedHBO | 0xa5a5000000000000); EXPECT_EQ(MacAddress::fromNBO(nboWithPad), addr); // Check they value returned by bytes() uint8_t expectedBytes[8]; memcpy(expectedBytes, &expectedNBO, 8); for (int n = 0; n < 6; ++n) { EXPECT_EQ(expectedBytes[n + 2], addr.bytes()[n]); } } TEST(MacAddress, parse) { testMAC("12:34:56:78:9a:bc", 0x123456789abc); testMAC("00-11-22-33-44-55", 0x1122334455); testMAC("abcdef123456", 0xabcdef123456); testMAC("1:2:3:4:5:6", 0x010203040506); testMAC("0:0:0:0:0:0", 0); testMAC("0:0:5e:0:1:1", 0x00005e000101); EXPECT_THROW(MacAddress(""), std::invalid_argument); EXPECT_THROW(MacAddress("0"), std::invalid_argument); EXPECT_THROW(MacAddress("12:34"), std::invalid_argument); EXPECT_THROW(MacAddress("12:3"), std::invalid_argument); EXPECT_THROW(MacAddress("12:"), std::invalid_argument); EXPECT_THROW(MacAddress("12:x4:56:78:9a:bc"), std::invalid_argument); EXPECT_THROW(MacAddress("12x34:56:78:9a:bc"), std::invalid_argument); EXPECT_THROW(MacAddress("12:34:56:78:9a:bc:de"), std::invalid_argument); EXPECT_THROW(MacAddress("12:34:56:78:9a:bcde"), std::invalid_argument); EXPECT_THROW(MacAddress("12:34:56:78:9a:bc "), std::invalid_argument); EXPECT_THROW(MacAddress(" 12:34:56:78:9a:bc"), std::invalid_argument); EXPECT_THROW(MacAddress("12:34:56:78:-1:bc"), std::invalid_argument); } void testFromBinary(const char* str, uint64_t expectedHBO) { StringPiece bin(str, 6); auto mac = MacAddress::fromBinary(bin); SCOPED_TRACE(mac.toString()); EXPECT_EQ(expectedHBO, mac.u64HBO()); } TEST(MacAddress, fromBinary) { testFromBinary("\0\0\0\0\0\0", 0); testFromBinary("\x12\x34\x56\x78\x9a\xbc", 0x123456789abc); testFromBinary("\x11\x22\x33\x44\x55\x66", 0x112233445566); StringPiece empty(""); EXPECT_THROW(MacAddress::fromBinary(empty), std::invalid_argument); StringPiece tooShort("\x11", 1); EXPECT_THROW(MacAddress::fromBinary(tooShort), std::invalid_argument); StringPiece tooLong("\x11\x22\x33\x44\x55\x66\x77", 7); EXPECT_THROW(MacAddress::fromBinary(tooLong), std::invalid_argument); } TEST(MacAddress, toString) { EXPECT_EQ("12:34:56:78:9a:bc", MacAddress::fromHBO(0x123456789abc).toString()); EXPECT_EQ("12:34:56:78:9a:bc", MacAddress("12:34:56:78:9a:bc").toString()); EXPECT_EQ("01:23:45:67:89:ab", MacAddress("01-23-45-67-89-ab").toString()); EXPECT_EQ("01:23:45:67:89:ab", MacAddress("0123456789ab").toString()); } TEST(MacAddress, attributes) { EXPECT_TRUE(MacAddress("ff:ff:ff:ff:ff:ff").isBroadcast()); EXPECT_FALSE(MacAddress("7f:ff:ff:ff:ff:ff").isBroadcast()); EXPECT_FALSE(MacAddress("7f:ff:ff:ff:ff:fe").isBroadcast()); EXPECT_FALSE(MacAddress("00:00:00:00:00:00").isBroadcast()); EXPECT_TRUE(MacAddress::fromNBO(0xffffffffffffffffU).isBroadcast()); EXPECT_TRUE(MacAddress("ff:ff:ff:ff:ff:ff").isMulticast()); EXPECT_TRUE(MacAddress("01:00:00:00:00:00").isMulticast()); EXPECT_FALSE(MacAddress("00:00:00:00:00:00").isMulticast()); EXPECT_FALSE(MacAddress("fe:ff:ff:ff:ff:ff").isMulticast()); EXPECT_FALSE(MacAddress("00:00:5e:00:01:01").isMulticast()); EXPECT_FALSE(MacAddress("ff:ff:ff:ff:ff:ff").isUnicast()); EXPECT_FALSE(MacAddress("01:00:00:00:00:00").isUnicast()); EXPECT_TRUE(MacAddress("00:00:00:00:00:00").isUnicast()); EXPECT_TRUE(MacAddress("fe:ff:ff:ff:ff:ff").isUnicast()); EXPECT_TRUE(MacAddress("00:00:5e:00:01:01").isUnicast()); EXPECT_TRUE(MacAddress("ff:ff:ff:ff:ff:ff").isLocallyAdministered()); EXPECT_TRUE(MacAddress("02:00:00:00:00:00").isLocallyAdministered()); EXPECT_FALSE(MacAddress("01:00:00:00:00:00").isLocallyAdministered()); EXPECT_FALSE(MacAddress("00:00:00:00:00:00").isLocallyAdministered()); EXPECT_FALSE(MacAddress("fd:ff:ff:ff:ff:ff").isLocallyAdministered()); EXPECT_TRUE(MacAddress("fe:ff:ff:ff:ff:ff").isLocallyAdministered()); EXPECT_FALSE(MacAddress("00:00:5e:00:01:01").isLocallyAdministered()); EXPECT_TRUE(MacAddress("02:12:34:56:78:9a").isLocallyAdministered()); } TEST(MacAddress, createMulticast) { EXPECT_EQ(MacAddress("33:33:00:01:00:03"), MacAddress::createMulticast(IPAddressV6("ff02:dead:beef::1:3"))); EXPECT_EQ(MacAddress("33:33:12:34:56:78"), MacAddress::createMulticast(IPAddressV6("ff02::abcd:1234:5678"))); } void testCmp(const char* str1, const char* str2) { SCOPED_TRACE(folly::to<std::string>(str1, " < ", str2)); MacAddress m1(str1); MacAddress m2(str2); // Test the comparison operators EXPECT_TRUE(m1 < m2); EXPECT_FALSE(m1 < m1); EXPECT_TRUE(m1 <= m2); EXPECT_TRUE(m2 > m1); EXPECT_TRUE(m2 >= m1); EXPECT_TRUE(m1 != m2); EXPECT_TRUE(m1 == (m1)); EXPECT_FALSE(m1 == m2); // Also test the copy constructor and assignment operator MacAddress copy(m1); EXPECT_EQ(copy, m1); copy = m2; EXPECT_EQ(copy, m2); } TEST(MacAddress, ordering) { testCmp("00:00:00:00:00:00", "00:00:00:00:00:01"); testCmp("00:00:00:00:00:01", "00:00:00:00:00:02"); testCmp("01:00:00:00:00:00", "02:00:00:00:00:00"); testCmp("00:00:00:00:00:01", "00:00:00:00:01:00"); }