text,length,is_long_context,metric_val,label_metric "// license:GPL-2.0+ // copyright-holders:Angelo Salese, Jonathan Edwards, Christopher Edwards,Robbbert /************************************************************************************** Basic Master Level 3 (MB-689x) (c) 1980 Hitachi Driver by Angelo Salese, Jonathan Edwards and Christopher Edwards TODO: - implement sound as a bml3bus slot device - account for hardware differences between MB-6890, MB-6891 and MB-6892 (e.g. custom font support on the MB-6892) **************************************************************************************/ #include ""emu.h"" #include ""cpu/m6809/m6809.h"" #include ""imagedev/cassette.h"" #include ""machine/6821pia.h"" #include ""machine/6850acia.h"" #include ""machine/clock.h"" #include ""machine/timer.h"" #include ""sound/2203intf.h"" #include ""sound/spkrdev.h"" #include ""sound/wave.h"" #include ""video/mc6845.h"" #include ""bus/bml3/bml3bus.h"" #include ""bus/bml3/bml3mp1802.h"" #include ""bus/bml3/bml3mp1805.h"" #include ""bus/bml3/bml3kanji.h"" #include ""screen.h"" #include ""speaker.h"" // System clock definitions, from the MB-6890 servce manual, p.48: #define MASTER_CLOCK ( 32256000 ) // Master clock crystal (X1) frequency, 32.256 MHz. ""fx"" in the manual. #define D80_CLOCK ( MASTER_CLOCK / 2 ) // Graphics dot clock in 80-column mode. ~16 MHz. #define D40_CLOCK ( D80_CLOCK / 2 ) // Graphics dot clock in 40-column mode. ~8 MHz. #define CPU_EXT_CLOCK ( D40_CLOCK / 2 ) // IC37, 4.032 MHz signal to EXTAL on the 6809 MPU. #define CPU_CLOCK ( CPU_EXT_CLOCK / 4 ) // Actual MPU clock frequency (""fE"" in the manual). The division yielding CPU_CLOCK is done in the 6809 itself. Also used as the 40-column character clock. #define C80_CLOCK ( CPU_EXT_CLOCK / 2 ) // 80-column character mode. IC37, ""80CHRCK""; ~2 MHz. #define C40_CLOCK ( CPU_CLOCK ) // 40-column character mode; same as MPU clock. ""40CHRCK""; ~1 MHz. // Video signal clocks from the HD4650SSP CRTC (IC36) // In the real hardware, the 80-/40-column Mode switch changes the CRTC character clock input source. However, it just uses a different divider, so the end result is the same horizontal vsync frequency. #define H_CLOCK ( C80_CLOCK / 128 ) // in 80-column mode //#define H_CLOCK ( C40_CLOCK / 64 ) // in 40-column mode (either way the frequency is the same: 15.75 kHz) #define V_CLOCK ( 2 * H_CLOCK / 525 ) // Vertical refresh rate comes out at exactly 60 Hz. // TODO: ACIA RS-232C and cassette interface clocks (service manual p.67); perhaps reverse the order and simply divide by 2 from each previous frequency. // IC111 (74LS157P) takes 16.128 MHz and 1.008 MHz TTL clock inputs. The RS/C SW input line determines the mode (high -> RS-232C). // Frequencies for RS-232C mode: // D80_CLOCK / 840.0 // 19200 Hz // D80_CLOCK / 420 // 38400 Hz // D80_CLOCK / 210 // 76800 Hz // D80_CLOCK / 105.0 // 153600 Hz // Frequencies for cassette mode: // / 13440 //1200 // / 6720 // 2400 // / 3360 // 4800 // / 1680 // 9600 class bml3_state : public driver_device { public: bml3_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, ""maincpu"") , m_p_videoram(*this, ""vram"") , m_p_chargen(*this, ""chargen"") , m_bml3bus(*this, ""bml3bus"") , m_crtc(*this, ""crtc"") , m_cass(*this, ""cassette"") , m_speaker(*this, ""speaker"") , m_ym2203(*this, ""ym2203"") , m_acia(*this, ""acia"") , m_palette(*this, ""palette"") { } DECLARE_READ8_MEMBER(bml3_6845_r); DECLARE_WRITE8_MEMBER(bml3_6845_w); DECLARE_READ8_MEMBER(bml3_keyboard_r); DECLARE_WRITE8_MEMBER(bml3_keyboard_w); DECLARE_WRITE8_MEMBER(bml3_hres_reg_w); DECLARE_WRITE8_MEMBER(bml3_vres_reg_w); DECLARE_READ8_MEMBER(bml3_vram_r); DECLARE_WRITE8_MEMBER(bml3_vram_w); DECLARE_READ8_MEMBER(bml3_psg_latch_r); DECLARE_WRITE8_MEMBER(bml3_psg_latch_w); DECLARE_READ8_MEMBER(bml3_vram_attr_r); DECLARE_WRITE8_MEMBER(bml3_vram_attr_w); DECLARE_READ8_MEMBER(bml3_beep_r); DECLARE_WRITE8_MEMBER(bml3_beep_w); DECLARE_WRITE8_MEMBER(bml3_piaA_w); DECLARE_READ8_MEMBER(bml3_keyb_nmi_r); DECLARE_WRITE8_MEMBER(bml3_firq_mask_w); DECLARE_READ8_MEMBER(bml3_firq_status_r); DECLARE_WRITE8_MEMBER(relay_w); DECLARE_WRITE_LINE_MEMBER(bml3bus_nmi_w); DECLARE_WRITE_LINE_MEMBER(bml3bus_irq_w); DECLARE_WRITE_LINE_MEMBER(bml3bus_firq_w); DECLARE_WRITE_LINE_MEMBER(bml3_acia_tx_w); DECLARE_WRITE_LINE_MEMBER(bml3_acia_rts_w); DECLARE_WRITE_LINE_MEMBER(bml3_acia_irq_w); DECLARE_READ8_MEMBER(bml3_a000_r); DECLARE_WRITE8_MEMBER(bml3_a000_w); DECLARE_READ8_MEMBER(bml3_c000_r); DECLARE_WRITE8_MEMBER(bml3_c000_w); DECLARE_READ8_MEMBER(bml3_e000_r); DECLARE_WRITE8_MEMBER(bml3_e000_w); DECLARE_READ8_MEMBER(bml3_f000_r); DECLARE_WRITE8_MEMBER(bml3_f000_w); DECLARE_READ8_MEMBER(bml3_fff0_r); DECLARE_WRITE8_MEMBER(bml3_fff0_w); MC6845_UPDATE_ROW(crtc_update_row); // INTERRUPT_GEN_MEMBER(bml3_irq); INTERRUPT_GEN_MEMBER(bml3_timer_firq); TIMER_DEVICE_CALLBACK_MEMBER(bml3_c); TIMER_DEVICE_CALLBACK_MEMBER(bml3_p); TIMER_DEVICE_CALLBACK_MEMBER(keyboard_callback); DECLARE_READ8_MEMBER(bml3_ym2203_r); DECLARE_WRITE8_MEMBER(bml3_ym2203_w); void bml3mk2(machine_config &config); void bml3mk5(machine_config &config); void bml3(machine_config &config); void bml3_common(machine_config &config); void bml3_mem(address_map &map); void bml3mk2_mem(address_map &map); void bml3mk5_mem(address_map &map); private: u8 m_hres_reg; u8 m_crtc_vreg[0x100]; u8 m_psg_latch; u8 m_attr_latch; u8 m_vres_reg; bool m_keyb_interrupt_disabled; bool m_keyb_nmi_disabled; // not used yet bool m_keyb_counter_operation_disabled; u8 m_keyb_empty_scan; u8 m_keyb_scancode; bool m_keyb_capslock_led_on; bool m_keyb_hiragana_led_on; bool m_keyb_katakana_led_on; bool m_cassbit; bool m_cassold; u8 m_cass_data[4]; virtual void machine_reset() override; virtual void machine_start() override; void m6845_change_clock(u8 setting); u8 m_crtc_index; std::unique_ptr m_extram; u8 m_firq_mask; u8 m_firq_status; required_device m_maincpu; required_region_ptr m_p_videoram; required_region_ptr m_p_chargen; required_device m_bml3bus; required_device m_crtc; required_device m_cass; required_device m_speaker; optional_device m_ym2203; required_device m_acia; required_device m_palette; }; #define mc6845_h_char_total (m_crtc_vreg[0]) #define mc6845_h_display (m_crtc_vreg[1]) #define mc6845_h_sync_pos (m_crtc_vreg[2]) #define mc6845_sync_width (m_crtc_vreg[3]) #define mc6845_v_char_total (m_crtc_vreg[4]) #define mc6845_v_total_adj (m_crtc_vreg[5]) #define mc6845_v_display (m_crtc_vreg[6]) #define mc6845_v_sync_pos (m_crtc_vreg[7]) #define mc6845_mode_ctrl (m_crtc_vreg[8]) #define mc6845_tile_height (m_crtc_vreg[9]+1) #define mc6845_cursor_y_start (m_crtc_vreg[0x0a]) #define mc6845_cursor_y_end (m_crtc_vreg[0x0b]) #define mc6845_start_addr (((m_crtc_vreg[0x0c]<<8) & 0x3f00) | (m_crtc_vreg[0x0d] & 0xff)) #define mc6845_cursor_addr (((m_crtc_vreg[0x0e]<<8) & 0x3f00) | (m_crtc_vreg[0x0f] & 0xff)) #define mc6845_light_pen_addr (((m_crtc_vreg[0x10]<<8) & 0x3f00) | (m_crtc_vreg[0x11] & 0xff)) #define mc6845_update_addr (((m_crtc_vreg[0x12]<<8) & 0x3f00) | (m_crtc_vreg[0x13] & 0xff)) READ8_MEMBER( bml3_state::bml3_6845_r ) { if (offset) return m_crtc->register_r(space, 0); else return m_crtc->status_r(space, 0); } WRITE8_MEMBER( bml3_state::bml3_6845_w ) { if(offset == 0) { m_crtc_index = data; m_crtc->address_w(space, 0, data); } else { m_crtc_vreg[m_crtc_index] = data; m_crtc->register_w(space, 0, data); } } READ8_MEMBER( bml3_state::bml3_keyboard_r ) { u8 ret = m_keyb_scancode; m_keyb_scancode &= 0x7f; return ret; } WRITE8_MEMBER( bml3_state::bml3_keyboard_w ) { m_keyb_katakana_led_on = BIT(data, 0); m_keyb_hiragana_led_on = BIT(data, 1); m_keyb_capslock_led_on = BIT(data, 2); m_keyb_counter_operation_disabled = BIT(data, 3); m_keyb_interrupt_disabled = !BIT(data, 6); m_keyb_nmi_disabled = !BIT(data, 7); } void bml3_state::m6845_change_clock(u8 setting) { int m6845_clock = CPU_CLOCK; // CRTC and MPU are synchronous by default switch(setting & 0x88) { case 0x00: m6845_clock = C40_CLOCK; break; //320 x 200 case 0x08: m6845_clock = C40_CLOCK; break; //320 x 200, interlace case 0x80: m6845_clock = C80_CLOCK; break; //640 x 200 case 0x88: m6845_clock = C80_CLOCK; break; //640 x 200, interlace } m_crtc->set_clock(m6845_clock); } WRITE8_MEMBER( bml3_state::bml3_hres_reg_w ) { // MODE SEL register (see service manual p.43). /* x--- ---- ""W"" bit: 0 = 40 columns, 1 = 80 columns -x-- ---- ""HR"" bit: 0 = high resolution, 1 = normal --x- ---- ""C"" bit - ACIA mode: 0 = cassette, 1 = RS-232C ---- -RGB Background colour */ m_hres_reg = data; m6845_change_clock((m_hres_reg & 0x80) | (m_vres_reg & 0x08)); } WRITE8_MEMBER( bml3_state::bml3_vres_reg_w ) { // The MB-6890 had an interlaced video mode which was used for displaying Japanese (Hiragana and Katakana) text (8x16 character glyph bitmaps). /* ---- x--- Interlace select: 0 = non-interlace, 1 = interlace */ m_vres_reg = data; m6845_change_clock((m_hres_reg & 0x80) | (m_vres_reg & 0x08)); } READ8_MEMBER( bml3_state::bml3_vram_r ) { // Bit 7 masks reading back to the latch if (!BIT(m_attr_latch, 7)) { m_attr_latch = m_p_videoram[offset+0x4000]; } return m_p_videoram[offset]; } WRITE8_MEMBER( bml3_state::bml3_vram_w ) { m_p_videoram[offset] = data; // color ram is 5-bit m_p_videoram[offset+0x4000] = m_attr_latch & 0x1F; } READ8_MEMBER( bml3_state::bml3_psg_latch_r) { return 0x7f; } WRITE8_MEMBER( bml3_state::bml3_psg_latch_w) { m_psg_latch = data; } READ8_MEMBER(bml3_state::bml3_ym2203_r) { u8 dev_offs = ((m_psg_latch & 3) != 3); return m_ym2203->read(space, dev_offs); } WRITE8_MEMBER(bml3_state::bml3_ym2203_w) { u8 dev_offs = ((m_psg_latch & 3) != 3); m_ym2203->write(space, dev_offs, data); } READ8_MEMBER( bml3_state::bml3_vram_attr_r) { // C-REG-SELECT register // Reads from a VRAM address copy the corresponding 'colour RAM' address to the low-order 5 bits of this register as a side-effect // (unless MK bit indicates 'prohibit write') return m_attr_latch; } WRITE8_MEMBER( bml3_state::bml3_vram_attr_w) { // C-REG-SELECT register // Writes to a VRAM address copy the low-order 5 bits of this register to the corresponding 'colour RAM' address as a side-effect /* x--- ---- ""MK"" bit: 0 = enable write, 1 = prohibit write ---x ---- ""GC"" bit: 0 = character, 1 = graphic ---- x--- ""RV"" bit: 0 = normal, 1 - reverse ---- -RGB Foreground colour */ m_attr_latch = data; } READ8_MEMBER( bml3_state::bml3_beep_r) { return -1; // BEEP status read? } WRITE8_MEMBER( bml3_state::bml3_beep_w) { m_speaker->level_w(BIT(data, 7)); } WRITE8_MEMBER( bml3_state::relay_w ) { m_cass->change_state( BIT(data,7) ? CASSETTE_MOTOR_ENABLED : CASSETTE_MOTOR_DISABLED, CASSETTE_MASK_MOTOR); } READ8_MEMBER( bml3_state::bml3_a000_r) { return m_extram[offset + 0xa000]; } WRITE8_MEMBER( bml3_state::bml3_a000_w) { m_extram[offset + 0xa000] = data; } READ8_MEMBER( bml3_state::bml3_c000_r) { return m_extram[offset + 0xc000]; } WRITE8_MEMBER( bml3_state::bml3_c000_w) { m_extram[offset + 0xc000] = data; } READ8_MEMBER( bml3_state::bml3_e000_r) { return m_extram[offset + 0xe000]; } WRITE8_MEMBER( bml3_state::bml3_e000_w) { m_extram[offset + 0xe000] = data; } READ8_MEMBER( bml3_state::bml3_f000_r) { return m_extram[offset + 0xf000]; } WRITE8_MEMBER( bml3_state::bml3_f000_w) { m_extram[offset + 0xf000] = data; } READ8_MEMBER( bml3_state::bml3_fff0_r) { return m_extram[offset + 0xfff0]; } WRITE8_MEMBER( bml3_state::bml3_fff0_w) { m_extram[offset + 0xfff0] = data; } READ8_MEMBER( bml3_state::bml3_keyb_nmi_r) { return 0; // bit 7 used to signal a BREAK key pressure } WRITE8_MEMBER( bml3_state::bml3_firq_mask_w) { m_firq_mask = data & 0x80; if(m_firq_mask) { m_firq_status = 0; // clear pending firq m_maincpu->set_input_line(M6809_FIRQ_LINE, CLEAR_LINE); } } READ8_MEMBER( bml3_state::bml3_firq_status_r ) { u8 res = m_firq_status << 7; m_firq_status = 0; m_maincpu->set_input_line(M6809_FIRQ_LINE, CLEAR_LINE); return res; } WRITE_LINE_MEMBER(bml3_state::bml3bus_nmi_w) { m_maincpu->set_input_line(INPUT_LINE_NMI, state); } WRITE_LINE_MEMBER(bml3_state::bml3bus_irq_w) { m_maincpu->set_input_line(M6809_IRQ_LINE, state); } WRITE_LINE_MEMBER(bml3_state::bml3bus_firq_w) { m_maincpu->set_input_line(M6809_FIRQ_LINE, state); } void bml3_state::bml3_mem(address_map &map) { map.unmap_value_high(); map(0x0000, 0x03ff).ram(); map(0x0400, 0x43ff).rw(this, FUNC(bml3_state::bml3_vram_r), FUNC(bml3_state::bml3_vram_w)); map(0x4400, 0x9fff).ram(); map(0xff40, 0xff46).noprw(); // lots of unknown reads and writes map(0xffc0, 0xffc3).rw(""pia"", FUNC(pia6821_device::read), FUNC(pia6821_device::write)); map(0xffc4, 0xffc5).rw(m_acia, FUNC(acia6850_device::read), FUNC(acia6850_device::write)); map(0xffc6, 0xffc7).rw(this, FUNC(bml3_state::bml3_6845_r), FUNC(bml3_state::bml3_6845_w)); // KBNMI - Keyboard ""Break"" key non-maskable interrupt map(0xffc8, 0xffc8).r(this, FUNC(bml3_state::bml3_keyb_nmi_r)); // keyboard nmi // DIPSW - DIP switches on system mainboard map(0xffc9, 0xffc9).portr(""DSW""); // TIMER - System timer enable map(0xffca, 0xffca).r(this, FUNC(bml3_state::bml3_firq_status_r)); // timer irq // LPFLG - Light pen interrupt // AM_RANGE(0xffcb, 0xffcb) // MODE_SEL - Graphics mode select map(0xffd0, 0xffd0).w(this, FUNC(bml3_state::bml3_hres_reg_w)); // TRACE - Trace counter // AM_RANGE(0xffd1, 0xffd1) // REMOTE - Remote relay control for cassette - bit 7 map(0xffd2, 0xffd2).w(this, FUNC(bml3_state::relay_w)); // MUSIC_SEL - Music select: toggle audio output level when rising map(0xffd3, 0xffd3).rw(this, FUNC(bml3_state::bml3_beep_r), FUNC(bml3_state::bml3_beep_w)); // TIME_MASK - Prohibit timer IRQ map(0xffd4, 0xffd4).w(this, FUNC(bml3_state::bml3_firq_mask_w)); // LPENBL - Light pen operation enable map(0xffd5, 0xffd5).noprw(); // INTERLACE_SEL - Interlaced video mode (manual has ""INTERACE SEL""!) map(0xffd6, 0xffd6).w(this, FUNC(bml3_state::bml3_vres_reg_w)); // AM_RANGE(0xffd7, 0xffd7) baud select // C_REG_SEL - Attribute register (character/video mode and colours) map(0xffd8, 0xffd8).rw(this, FUNC(bml3_state::bml3_vram_attr_r), FUNC(bml3_state::bml3_vram_attr_w)); // KB - Keyboard mode register, interrupt control, keyboard LEDs map(0xffe0, 0xffe0).rw(this, FUNC(bml3_state::bml3_keyboard_r), FUNC(bml3_state::bml3_keyboard_w)); // AM_RANGE(0xffe8, 0xffe8) bank register // AM_RANGE(0xffe9, 0xffe9) IG mode register // AM_RANGE(0xffea, 0xffea) IG enable register map(0xa000, 0xfeff).rom().region(""maincpu"", 0xa000); map(0xfff0, 0xffff).rom().region(""maincpu"", 0xfff0); map(0xa000, 0xbfff).w(this, FUNC(bml3_state::bml3_a000_w)); map(0xc000, 0xdfff).w(this, FUNC(bml3_state::bml3_c000_w)); map(0xe000, 0xefff).w(this, FUNC(bml3_state::bml3_e000_w)); map(0xf000, 0xfeff).w(this, FUNC(bml3_state::bml3_f000_w)); map(0xfff0, 0xffff).w(this, FUNC(bml3_state::bml3_fff0_w)); #if 0 map(0xff00, 0xff00).rw(this, FUNC(bml3_state::bml3_ym2203_r), FUNC(bml3_state::bml3_ym2203_w)); map(0xff02, 0xff02).rw(this, FUNC(bml3_state::bml3_psg_latch_r), FUNC(bml3_state::bml3_psg_latch_w)); // PSG address/data select #endif } void bml3_state::bml3mk2_mem(address_map &map) { bml3_mem(map); // TODO: anything to add here? } void bml3_state::bml3mk5_mem(address_map &map) { bml3_mem(map); // TODO: anything to add here? } /* Input ports */ static INPUT_PORTS_START( bml3 ) // DIP switches (service manual p.88) // Note the NEWON command reboots with a soft override for the DIP switch PORT_START(""DSW"") PORT_DIPNAME( 0x01, 0x01, ""BASIC/terminal mode"") PORT_DIPSETTING(0x00, ""Terminal mode"") PORT_DIPSETTING(0x01, ""BASIC mode"") PORT_DIPNAME( 0x02, 0x02, ""Interlaced video"") PORT_DIPSETTING(0x00, DEF_STR( Off ) ) PORT_DIPSETTING(0x02, DEF_STR( On )) // This is overridden by the 'Mode' toggle button PORT_DIPNAME( 0x04, 0x04, ""40-/80-column"") PORT_DIPSETTING(0x00, ""40 chars/line"") PORT_DIPSETTING(0x04, ""80 chars/line"") PORT_DIPNAME( 0x08, 0x00, ""Video resolution"") PORT_DIPSETTING(0x00, ""High"") PORT_DIPSETTING(0x08, ""Low"") PORT_DIPNAME( 0x10, 0x00, ""Show PF key content"") PORT_DIPSETTING(0x00, DEF_STR ( Off ) ) PORT_DIPSETTING(0x10, DEF_STR ( On )) PORT_DIPNAME( 0x20, 0x00, ""Terminal duplex"") PORT_DIPSETTING(0x00, ""Full duplex"") PORT_DIPSETTING(0x20, ""Half duplex"") PORT_DIPNAME( 0x40, 0x00, ""Terminal bits"") PORT_DIPSETTING(0x00, ""8 bits/char"") PORT_DIPSETTING(0x40, ""7 bits/char"") PORT_DIPNAME( 0x80, 0x00, ""Hiragana->Katakana"") PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x80, DEF_STR( On ) ) // TODO: also model the CS jumper block? // RAM expansion configurations (see service manual p.76) /* PORT_START(""RAM"") PORT_DIPNAME( 0x0003, 0x0002, ""RAM size"" ) PORT_DIPSETTING( 0x0000, ""32 kiB (standard)"" ) PORT_DIPSETTING( 0x0001, ""40 kiB (32 kiB + 8 kiB)"" ) PORT_DIPSETTING( 0x0002, ""60 kiB (32 kiB + 28 kiB)"" ) */ PORT_START(""key1"") //0x00-0x1f PORT_BIT(0x00000001,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Space"") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_BIT(0x00000002,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Up"") PORT_CODE(KEYCODE_UP) PORT_BIT(0x00000004,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""? PAD"") PORT_CHAR('?') PORT_BIT(0x00000008,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Left"") PORT_CODE(KEYCODE_LEFT) PORT_BIT(0x00000010,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Down"") PORT_CODE(KEYCODE_DOWN) PORT_BIT(0x00000020,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Right"") PORT_CODE(KEYCODE_RIGHT) PORT_BIT(0x00000040,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Control"") PORT_CODE(KEYCODE_LCONTROL) PORT_BIT(0x00000080,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Shift"")PORT_CODE(KEYCODE_LSHIFT) PORT_BIT(0x00000100,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""X2"") // ??? PORT_BIT(0x00000200,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Caps Lock"") PORT_CODE(KEYCODE_CAPSLOCK) PORT_BIT(0x00000400,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Kana Lock"") PORT_CODE(KEYCODE_NUMLOCK) PORT_BIT(0x00000800,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Kana Shift"") PORT_CODE(KEYCODE_LALT) PORT_BIT(0x00001000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""ESC"") PORT_CODE(KEYCODE_ESC) PORT_BIT(0x00002000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""8 PAD"") PORT_CODE(KEYCODE_8_PAD) PORT_CHAR('8') PORT_BIT(0x00004000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""9 PAD"") PORT_CODE(KEYCODE_9_PAD) PORT_CHAR('9') PORT_BIT(0x00008000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""*"") PORT_CODE(KEYCODE_ASTERISK) PORT_CHAR('*') PORT_BIT(0x00010000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""7"") PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_BIT(0x00020000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""4"") PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_BIT(0x00040000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""6"") PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_BIT(0x00080000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""8"") PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_BIT(0x00100000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""0"") PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_BIT(0x00200000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""^"") PORT_CODE(KEYCODE_BACKSLASH) PORT_BIT(0x00400000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""-"") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_BIT(0x00800000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""3"") PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_BIT(0x01000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Delete"") PORT_CODE(KEYCODE_BACKSPACE) PORT_BIT(0x02000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""5"") PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_BIT(0x04000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""1"") PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_BIT(0x08000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""2"") PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_BIT(0x10000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""9"") PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_BIT(0x20000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""7 PAD"") PORT_CODE(KEYCODE_7_PAD) PORT_CHAR('7') PORT_BIT(0x40000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Delete PAD"") //backspace PORT_BIT(0x80000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""\\xC2\\xA5"") PORT_CODE(KEYCODE_TAB) // yen sign PORT_START(""key2"") //0x20-0x3f PORT_BIT(0x00000001,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""U"") PORT_CODE(KEYCODE_U) PORT_BIT(0x00000002,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""R"") PORT_CODE(KEYCODE_R) PORT_BIT(0x00000004,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Y"") PORT_CODE(KEYCODE_Y) PORT_BIT(0x00000008,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""I"") PORT_CODE(KEYCODE_I) PORT_BIT(0x00000010,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""P"") PORT_CODE(KEYCODE_P) PORT_BIT(0x00000020,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""["") PORT_CODE(KEYCODE_OPENBRACE) PORT_BIT(0x00000040,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""@"") PORT_CODE(KEYCODE_EQUALS) PORT_BIT(0x00000080,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""0 PAD"") PORT_CODE(KEYCODE_0_PAD) PORT_CHAR('0') PORT_BIT(0x00000100,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Q"") PORT_CODE(KEYCODE_Q) PORT_BIT(0x00000200,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""T"") PORT_CODE(KEYCODE_T) PORT_BIT(0x00000400,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""W"") PORT_CODE(KEYCODE_W) PORT_BIT(0x00000800,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""E"") PORT_CODE(KEYCODE_E) PORT_BIT(0x00001000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""O"") PORT_CODE(KEYCODE_O) PORT_BIT(0x00002000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME("". PAD"") PORT_CODE(KEYCODE_DEL_PAD) PORT_CHAR('.') PORT_BIT(0x00004000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""HOME"") PORT_CODE(KEYCODE_HOME) //or cls? PORT_BIT(0x00008000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""ENTER"") PORT_CODE(KEYCODE_ENTER) PORT_BIT(0x00010000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""J"") PORT_CODE(KEYCODE_J) PORT_BIT(0x00020000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""F"") PORT_CODE(KEYCODE_F) PORT_BIT(0x00040000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""H"") PORT_CODE(KEYCODE_H) PORT_BIT(0x00080000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""K"") PORT_CODE(KEYCODE_K) PORT_BIT(0x00100000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME("";"") PORT_CODE(KEYCODE_COLON) PORT_BIT(0x00200000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""]"") PORT_CODE(KEYCODE_CLOSEBRACE) PORT_BIT(0x00400000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME("":"") PORT_CODE(KEYCODE_QUOTE) PORT_BIT(0x00800000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""4 PAD"") PORT_CODE(KEYCODE_4_PAD) PORT_CHAR('4') PORT_BIT(0x01000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""A"") PORT_CODE(KEYCODE_A) PORT_BIT(0x02000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""G"") PORT_CODE(KEYCODE_G) PORT_BIT(0x04000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""S"") PORT_CODE(KEYCODE_S) PORT_BIT(0x08000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""D"") PORT_CODE(KEYCODE_D) PORT_BIT(0x10000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""L"") PORT_CODE(KEYCODE_L) PORT_BIT(0x20000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""5 PAD"") PORT_CODE(KEYCODE_5_PAD) PORT_CHAR('5') PORT_BIT(0x40000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""6 PAD"") PORT_CODE(KEYCODE_6_PAD) PORT_CHAR('6') PORT_BIT(0x80000000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""- PAD"") PORT_CODE(KEYCODE_MINUS_PAD) PORT_CHAR('-') PORT_START(""key3"") //0x40-0x5f PORT_BIT(0x00000001,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""M"") PORT_CODE(KEYCODE_M) PORT_BIT(0x00000002,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""V"") PORT_CODE(KEYCODE_V) PORT_BIT(0x00000004,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""N"") PORT_CODE(KEYCODE_N) PORT_BIT(0x00000008,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME("","") PORT_CODE(KEYCODE_COMMA) PORT_BIT(0x00000010,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""/"") PORT_CODE(KEYCODE_SLASH) PORT_BIT(0x00000020,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""/ PAD"") PORT_CODE(KEYCODE_SLASH_PAD) PORT_CHAR('/') PORT_BIT(0x00000040,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""_"") PORT_CODE(KEYCODE_TILDE) PORT_BIT(0x00000080,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""1 PAD"") PORT_CODE(KEYCODE_1_PAD) PORT_CHAR('1') PORT_BIT(0x00000100,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""Z"") PORT_CODE(KEYCODE_Z) PORT_BIT(0x00000200,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""B"") PORT_CODE(KEYCODE_B) PORT_BIT(0x00000400,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""X"") PORT_CODE(KEYCODE_X) PORT_BIT(0x00000800,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""C"") PORT_CODE(KEYCODE_C) PORT_BIT(0x00001000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""."") PORT_CODE(KEYCODE_STOP) PORT_BIT(0x00002000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""2 PAD"") PORT_CODE(KEYCODE_2_PAD) PORT_CHAR('2') PORT_BIT(0x00004000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""3 PAD"") PORT_CODE(KEYCODE_3_PAD) PORT_CHAR('3') PORT_BIT(0x00008000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""+"") PORT_CODE(KEYCODE_PLUS_PAD) PORT_BIT(0x00010000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""PF1"") PORT_CODE(KEYCODE_F1) PORT_BIT(0x00020000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""PF2"") PORT_CODE(KEYCODE_F2) PORT_BIT(0x00040000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""PF3"") PORT_CODE(KEYCODE_F3) PORT_BIT(0x00080000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""PF4"") PORT_CODE(KEYCODE_F4) PORT_BIT(0x00100000,IP_ACTIVE_HIGH,IPT_KEYBOARD) PORT_NAME(""PF5"") PORT_CODE(KEYCODE_F5) PORT_BIT(0xffe00000,IP_ACTIVE_HIGH,IPT_UNKNOWN) INPUT_PORTS_END MC6845_UPDATE_ROW( bml3_state::crtc_update_row ) { const rgb_t *palette = m_palette->palette()->entry_list_raw(); // The MB-6890 has a 5-bit colour RAM region. The meaning of the bits are: // 0: blue // 1: red // 2: green // 3: reverse/inverse video // 4: graphic (not character) u8 x=0,hf=0,xi=0,interlace=0,bgcolor=0,rawbits=0,dots[2],color=0,pen=0; bool reverse=0,graphic=0,lowres=0; u16 mem=0; interlace = (m_crtc_vreg[8] & 3) ? 1 : 0; lowres = BIT(m_hres_reg, 6); bgcolor = m_hres_reg & 7; if (interlace) { ra >>= 1; if (y > 0x176) return; } // redundant initializers to keep compiler happy dots[0] = dots[1] = 0; for(x=0; x> ra/2 & 0x11) * 0xf; } else { dots[0] = dots[1] = rawbits; } } else { // character mode int tile = rawbits & 0x7f; int tile_bank = BIT(rawbits, 7); if (interlace) { dots[0] = m_p_chargen[(tile_bank<<11)|(tile<<4)|(ra<<1)]; dots[1] = m_p_chargen[(tile_bank<<11)|(tile<<4)|(ra<<1)|tile_bank]; } else { dots[0] = dots[1] = m_p_chargen[(tile<<4)|(ra<<1)|tile_bank]; } } for(hf=0;hf<=interlace;hf++) { for(xi=0;xi<8;xi++) { if(reverse) pen = (dots[hf] >> (7-xi) & 1) ? bgcolor : color; else pen = (dots[hf] >> (7-xi) & 1) ? color : bgcolor; bitmap.pix32(y, x*8+xi) = palette[pen]; // when the mc6845 device gains full interlace&video support, replace the line above with the line below // bitmap.pix32(y*(interlace+1)+hf, x*8+xi) = palette[pen]; } } } } TIMER_DEVICE_CALLBACK_MEMBER(bml3_state::keyboard_callback) { static const char *const portnames[3] = { ""key1"",""key2"",""key3"" }; int i,port_i; bool trigger = false; if(!(m_keyb_scancode & 0x80)) { m_keyb_scancode = (m_keyb_scancode + 1) & 0x7F; if (m_keyb_counter_operation_disabled) { m_keyb_scancode &= 0x7; } if (m_keyb_scancode == 0x7F) { if (m_keyb_empty_scan == 1) { // full scan completed with no keypress trigger = true; } if (m_keyb_empty_scan > 0) m_keyb_empty_scan--; } else if (m_keyb_scancode < 32*3) { port_i = m_keyb_scancode / 32; i = m_keyb_scancode % 32; if((ioport(portnames[port_i])->read()>>i) & 1) { m_keyb_empty_scan = 2; trigger = true; } } if (trigger) { m_keyb_scancode |= 0x80; if (!m_keyb_interrupt_disabled) m_maincpu->set_input_line(M6809_IRQ_LINE, HOLD_LINE); } /* Don't need this apparently... else { m_maincpu->set_input_line(M6809_IRQ_LINE, CLEAR_LINE); } */ } } TIMER_DEVICE_CALLBACK_MEMBER( bml3_state::bml3_p ) { /* cassette - turn 1200/2400Hz to a bit */ m_cass_data[1]++; u8 cass_ws = (m_cass->input() > +0.03) ? 1 : 0; if (cass_ws != m_cass_data[0]) { m_cass_data[0] = cass_ws; m_acia->write_rxd((m_cass_data[1] < 12) ? 1 : 0); m_cass_data[1] = 0; } } #if 0 INTERRUPT_GEN_MEMBER(bml3_state::bml3_irq) { m_maincpu->set_input_line(M6809_IRQ_LINE, HOLD_LINE); } #endif INTERRUPT_GEN_MEMBER(bml3_state::bml3_timer_firq) { if(!m_firq_mask) { m_maincpu->set_input_line(M6809_FIRQ_LINE, ASSERT_LINE); m_firq_status = 1; } } void bml3_state::machine_start() { m_extram = std::make_unique(0x10000); m_psg_latch = 0; m_attr_latch = 0; m_vres_reg = 0; m_keyb_interrupt_disabled = 0; m_keyb_nmi_disabled = 0; m_keyb_counter_operation_disabled = 0; m_keyb_empty_scan = 0; m_keyb_scancode = 0; m_keyb_capslock_led_on = 0; m_keyb_hiragana_led_on = 0; m_keyb_katakana_led_on = 0; m_crtc_index = 0; m_firq_status = 0; m_cassbit = 0; m_cassold = 0; } void bml3_state::machine_reset() { address_space &mem = m_maincpu->space(AS_PROGRAM); /* defaults */ mem.install_rom(0xa000, 0xfeff,memregion(""maincpu"")->base() + 0xa000); mem.install_rom(0xfff0, 0xffff,memregion(""maincpu"")->base() + 0xfff0); mem.install_write_handler(0xa000, 0xbfff, write8_delegate(FUNC(bml3_state::bml3_a000_w), this),0); mem.install_write_handler(0xc000, 0xdfff, write8_delegate(FUNC(bml3_state::bml3_c000_w), this),0); mem.install_write_handler(0xe000, 0xefff, write8_delegate(FUNC(bml3_state::bml3_e000_w), this),0); mem.install_write_handler(0xf000, 0xfeff, write8_delegate(FUNC(bml3_state::bml3_f000_w), this),0); mem.install_write_handler(0xfff0, 0xffff, write8_delegate(FUNC(bml3_state::bml3_fff0_w), this),0); m_firq_mask = -1; // disable firq } WRITE8_MEMBER(bml3_state::bml3_piaA_w) { address_space &mem = m_maincpu->space(AS_PROGRAM); /* ROM banking: -0-- --0- 0xa000 - 0xbfff ROM R RAM W -1-- --0- 0xa000 - 0xbfff RAM R/W -x-- --1- 0xa000 - 0xbfff no change 0--- -0-- 0xc000 - 0xdfff ROM R RAM W 1--- -0-- 0xc000 - 0xdfff RAM R/W x--- -1-- 0xc000 - 0xdfff no change 0--- 0--- 0xe000 - 0xefff ROM R RAM W 1--- 0--- 0xe000 - 0xefff RAM R/W x--- 1--- 0xe000 - 0xefff no change ---- ---x 0xf000 - 0xfeff (0) ROM R RAM W (1) RAM R/W ---- --x- 0xfff0 - 0xffff (0) ROM R RAM W (1) RAM R/W */ logerror(""Check banking PIA A -> %02x\\n"",data); if(!(data & 0x2)) { if(data & 0x40) { mem.install_readwrite_handler(0xa000, 0xbfff, read8_delegate(FUNC(bml3_state::bml3_a000_r), this), write8_delegate(FUNC(bml3_state::bml3_a000_w), this), 0); } else { mem.install_rom(0xa000, 0xbfff, memregion(""maincpu"")->base() + 0xa000); mem.install_write_handler(0xa000, 0xbfff, write8_delegate(FUNC(bml3_state::bml3_a000_w), this), 0); } } if(!(data & 0x4)) { if(data & 0x40) { mem.install_readwrite_handler(0xc000, 0xdfff, read8_delegate(FUNC(bml3_state::bml3_c000_r), this), write8_delegate(FUNC(bml3_state::bml3_c000_w), this), 0); } else { mem.install_rom(0xc000, 0xdfff, memregion(""maincpu"")->base() + 0xc000); mem.install_write_handler(0xc000, 0xdfff, write8_delegate(FUNC(bml3_state::bml3_c000_w), this), 0); } } if(!(data & 0x8)) { if(data & 0x80) { mem.install_readwrite_handler(0xe000, 0xefff, read8_delegate(FUNC(bml3_state::bml3_e000_r), this), write8_delegate(FUNC(bml3_state::bml3_e000_w), this), 0); } else { mem.install_rom(0xe000, 0xefff, memregion(""maincpu"")->base() + 0xe000); mem.install_write_handler(0xe000, 0xefff, write8_delegate(FUNC(bml3_state::bml3_e000_w), this), 0); } } if(data & 1) { mem.install_readwrite_handler(0xf000, 0xfeff, read8_delegate(FUNC(bml3_state::bml3_f000_r), this), write8_delegate(FUNC(bml3_state::bml3_f000_w), this), 0); } else { mem.install_rom(0xf000, 0xfeff, memregion(""maincpu"")->base() + 0xf000); mem.install_write_handler(0xf000, 0xfeff, write8_delegate(FUNC(bml3_state::bml3_f000_w), this), 0); } if(data & 2) { mem.install_readwrite_handler(0xfff0, 0xffff, read8_delegate(FUNC(bml3_state::bml3_fff0_r), this), write8_delegate(FUNC(bml3_state::bml3_fff0_w), this), 0); } else { mem.install_rom(0xfff0, 0xffff, memregion(""maincpu"")->base() + 0xfff0); mem.install_write_handler(0xfff0, 0xffff, write8_delegate(FUNC(bml3_state::bml3_fff0_w), this), 0); } } WRITE_LINE_MEMBER( bml3_state::bml3_acia_tx_w ) { //logerror(""%02x TAPE\\n"",state); m_cassbit = state; } WRITE_LINE_MEMBER( bml3_state::bml3_acia_rts_w ) { logerror(""%02x TAPE RTS\\n"",state); } WRITE_LINE_MEMBER( bml3_state::bml3_acia_irq_w ) { logerror(""%02x TAPE IRQ\\n"",state); } TIMER_DEVICE_CALLBACK_MEMBER( bml3_state::bml3_c ) { m_cass_data[3]++; if (m_cassbit != m_cassold) { m_cass_data[3] = 0; m_cassold = m_cassbit; } if (m_cassbit) m_cass->output(BIT(m_cass_data[3], 0) ? -1.0 : +1.0); // 2400Hz else m_cass->output(BIT(m_cass_data[3], 1) ? -1.0 : +1.0); // 1200Hz } #if 0 static const ay8910_interface ay8910_config = { AY8910_LEGACY_OUTPUT, AY8910_DEFAULT_LOADS, DEVCB_NOOP, // read A DEVCB_NOOP, // read B DEVCB_NOOP, // write A DEVCB_NOOP // write B }; #endif static SLOT_INTERFACE_START(bml3_cards) SLOT_INTERFACE(""bml3mp1802"", BML3BUS_MP1802) /* MP-1802 Floppy Controller Card */ SLOT_INTERFACE(""bml3mp1805"", BML3BUS_MP1805) /* MP-1805 Floppy Controller Card */ SLOT_INTERFACE(""bml3kanji"", BML3BUS_KANJI) SLOT_INTERFACE_END MACHINE_CONFIG_START(bml3_state::bml3_common) /* basic machine hardware */ MCFG_CPU_ADD(""maincpu"",M6809, CPU_CLOCK) MCFG_CPU_VBLANK_INT_DRIVER(""screen"", bml3_state, bml3_timer_firq) // MCFG_CPU_PERIODIC_INT_DRIVER(bml3_state, bml3_firq, 45) // MCFG_MACHINE_RESET_OVERRIDE(bml3_state,bml3) /* video hardware */ MCFG_SCREEN_ADD(""screen"", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2400)) /* Service manual specifies ""Raster return period"" as 2.4 ms (p.64), although the total vertical non-displaying time seems to be 4 ms. */ MCFG_SCREEN_SIZE(640, 400) MCFG_SCREEN_VISIBLE_AREA(0, 320-1, 0, 200-1) MCFG_SCREEN_UPDATE_DEVICE(""crtc"", mc6845_device, screen_update) MCFG_PALETTE_ADD_3BIT_BRG(""palette"") /* Devices */ // CRTC clock should be synchronous with the CPU clock. MCFG_MC6845_ADD(""crtc"", H46505, ""screen"", CPU_CLOCK) MCFG_MC6845_SHOW_BORDER_AREA(false) MCFG_MC6845_CHAR_WIDTH(8) MCFG_MC6845_UPDATE_ROW_CB(bml3_state, crtc_update_row) // fire once per scan of an individual key // According to the service manual (p.65), the keyboard timer is driven by the horizontal video sync clock. MCFG_TIMER_DRIVER_ADD_PERIODIC(""keyboard_timer"", bml3_state, keyboard_callback, attotime::from_hz(H_CLOCK/2)) MCFG_TIMER_DRIVER_ADD_PERIODIC(""bml3_c"", bml3_state, bml3_c, attotime::from_hz(4800)) MCFG_TIMER_DRIVER_ADD_PERIODIC(""bml3_p"", bml3_state, bml3_p, attotime::from_hz(40000)) MCFG_DEVICE_ADD(""pia"", PIA6821, 0) MCFG_PIA_WRITEPA_HANDLER(WRITE8(bml3_state, bml3_piaA_w)) MCFG_DEVICE_ADD(""acia"", ACIA6850, 0) MCFG_ACIA6850_TXD_HANDLER(WRITELINE(bml3_state, bml3_acia_tx_w)) MCFG_ACIA6850_RTS_HANDLER(WRITELINE(bml3_state, bml3_acia_rts_w)) MCFG_ACIA6850_IRQ_HANDLER(WRITELINE(bml3_state, bml3_acia_irq_w)) MCFG_DEVICE_ADD(""acia_clock"", CLOCK, 9600) // 600 baud x 16(divider) = 9600 MCFG_CLOCK_SIGNAL_HANDLER(DEVWRITELINE(""acia"", acia6850_device, write_txc)) MCFG_DEVCB_CHAIN_OUTPUT(DEVWRITELINE(""acia"", acia6850_device, write_rxc)) MCFG_CASSETTE_ADD( ""cassette"" ) /* Audio */ MCFG_SPEAKER_STANDARD_MONO(""mono"") MCFG_SOUND_WAVE_ADD(WAVE_TAG, ""cassette"") MCFG_SOUND_ROUTE(ALL_OUTPUTS, ""mono"", 0.25) MCFG_SOUND_ADD(""speaker"", SPEAKER_SOUND, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, ""mono"", 0.50) /* slot devices */ MCFG_DEVICE_ADD(""bml3bus"", BML3BUS, 0) MCFG_BML3BUS_CPU(""maincpu"") MCFG_BML3BUS_OUT_NMI_CB(WRITELINE(bml3_state, bml3bus_nmi_w)) MCFG_BML3BUS_OUT_IRQ_CB(WRITELINE(bml3_state, bml3bus_irq_w)) MCFG_BML3BUS_OUT_FIRQ_CB(WRITELINE(bml3_state, bml3bus_firq_w)) /* Default to MP-1805 disk (3"" or 5.25"" SS/SD), as our MB-6892 ROM dump includes the MP-1805 ROM. User may want to switch this to MP-1802 (5.25"" DS/DD). Note it isn't feasible to use both, as they each place boot ROM at F800. */ MCFG_BML3BUS_SLOT_ADD(""bml3bus"", ""sl1"", bml3_cards, ""bml3mp1805"") MCFG_BML3BUS_SLOT_ADD(""bml3bus"", ""sl2"", bml3_cards, nullptr) MCFG_BML3BUS_SLOT_ADD(""bml3bus"", ""sl3"", bml3_cards, nullptr) MCFG_BML3BUS_SLOT_ADD(""bml3bus"", ""sl4"", bml3_cards, nullptr) MCFG_BML3BUS_SLOT_ADD(""bml3bus"", ""sl5"", bml3_cards, nullptr) MCFG_BML3BUS_SLOT_ADD(""bml3bus"", ""sl6"", bml3_cards, ""bml3kanji"") MACHINE_CONFIG_END MACHINE_CONFIG_START(bml3_state::bml3) bml3_common(config); MCFG_CPU_MODIFY( ""maincpu"" ) MCFG_CPU_PROGRAM_MAP(bml3_mem) #if 0 // TODO: slot device for sound card // audio MCFG_SOUND_ADD(""ym2203"", YM2203, 2000000) //unknown clock / divider MCFG_YM2203_AY8910_INTF(&ay8910_config) MCFG_SOUND_ROUTE(0, ""mono"", 0.25) MCFG_SOUND_ROUTE(1, ""mono"", 0.25) MCFG_SOUND_ROUTE(2, ""mono"", 0.50) MCFG_SOUND_ROUTE(3, ""mono"", 0.50) #endif MACHINE_CONFIG_END MACHINE_CONFIG_START(bml3_state::bml3mk2) bml3_common(config); MCFG_CPU_MODIFY( ""maincpu"" ) MCFG_CPU_PROGRAM_MAP(bml3mk2_mem) // TODO: anything to add here? MACHINE_CONFIG_END MACHINE_CONFIG_START(bml3_state::bml3mk5) bml3_common(config); MCFG_CPU_MODIFY( ""maincpu"" ) MCFG_CPU_PROGRAM_MAP(bml3mk5_mem) // TODO: anything to add here? MACHINE_CONFIG_END /* ROM definition */ ROM_START( bml3 ) ROM_REGION( 0x10000, ""maincpu"", ROMREGION_ERASEFF ) // ROM_LOAD( ""l3bas.rom"", 0xa000, 0x6000, BAD_DUMP CRC(d81baa07) SHA1(a8fd6b29d8c505b756dbf5354341c48f9ac1d24d)) //original, 24k isn't a proper rom size! // TODO: replace with MB-6890 ROMs (these are from an MB-6892) ROM_LOAD( ""598 p16611.ic3"", 0xa000, 0x2000, BAD_DUMP CRC(954b9bad) SHA1(047948fac6808717c60a1d0ac9205a5725362430)) ROM_LOAD( ""599 p16561.ic4"", 0xc000, 0x2000, BAD_DUMP CRC(b27a48f5) SHA1(94cb616df4caa6415c5076f9acdf675acb7453e2)) // TODO: Replace checksums with a ROM dump without a disk controller patch (checksums here are inclusive of the MP1805 patch) ROM_LOAD( ""600 p16681.ic5"", 0xe000, 0x2000, BAD_DUMP CRC(fe3988a5) SHA1(edc732f1cd421e0cf45ffcfc71c5589958ceaae7)) ROM_REGION( 0x1000, ""chargen"", 0 ) ROM_LOAD(""font.rom"", 0x00000, 0x1000, BAD_DUMP CRC(0b6f2f10) SHA1(dc411b447ca414e94843636d8b5f910c954581fb) ) // handcrafted ROM_REGION( 0x8000, ""vram"", ROMREGION_ERASEFF ) ROM_END ROM_START( bml3mk2 ) ROM_REGION( 0x10000, ""maincpu"", ROMREGION_ERASEFF ) // ROM_LOAD( ""l3bas.rom"", 0xa000, 0x6000, BAD_DUMP CRC(d81baa07) SHA1(a8fd6b29d8c505b756dbf5354341c48f9ac1d24d)) //original, 24k isn't a proper rom size! // TODO: replace with MB-6891 ROMs (these are from an MB-6892) ROM_LOAD( ""598 p16611.ic3"", 0xa000, 0x2000, BAD_DUMP CRC(954b9bad) SHA1(047948fac6808717c60a1d0ac9205a5725362430)) ROM_LOAD( ""599 p16561.ic4"", 0xc000, 0x2000, BAD_DUMP CRC(b27a48f5) SHA1(94cb616df4caa6415c5076f9acdf675acb7453e2)) ROM_LOAD( ""600 p16681.ic5"", 0xe000, 0x2000, BAD_DUMP CRC(fe3988a5) SHA1(edc732f1cd421e0cf45ffcfc71c5589958ceaae7)) ROM_REGION( 0x1000, ""chargen"", 0 ) ROM_LOAD(""font.rom"", 0x00000, 0x1000, BAD_DUMP CRC(0b6f2f10) SHA1(dc411b447ca414e94843636d8b5f910c954581fb) ) // handcrafted ROM_REGION( 0x8000, ""vram"", ROMREGION_ERASEFF ) ROM_END ROM_START( bml3mk5 ) ROM_REGION( 0x10000, ""maincpu"", ROMREGION_ERASEFF ) // ROM_LOAD( ""l3bas.rom"", 0xa000, 0x6000, BAD_DUMP CRC(d81baa07) SHA1(a8fd6b29d8c505b756dbf5354341c48f9ac1d24d)) //original, 24k isn't a proper rom size! /* Handcrafted ROMs, rom labels and contents might not match */ ROM_LOAD( ""598 p16611.ic3"", 0xa000, 0x2000, BAD_DUMP CRC(954b9bad) SHA1(047948fac6808717c60a1d0ac9205a5725362430)) ROM_LOAD( ""599 p16561.ic4"", 0xc000, 0x2000, BAD_DUMP CRC(b27a48f5) SHA1(94cb616df4caa6415c5076f9acdf675acb7453e2)) // TODO: Replace checksums with a ROM dump without a disk controller patch (checksums here are inclusive of the MP1805 patch) ROM_LOAD( ""600 p16681.ic5"", 0xe000, 0x2000, BAD_DUMP CRC(fe3988a5) SHA1(edc732f1cd421e0cf45ffcfc71c5589958ceaae7)) ROM_REGION( 0x1000, ""chargen"", 0 ) ROM_LOAD(""font.rom"", 0x00000, 0x1000, BAD_DUMP CRC(0b6f2f10) SHA1(dc411b447ca414e94843636d8b5f910c954581fb) ) // handcrafted ROM_REGION( 0x8000, ""vram"", ROMREGION_ERASEFF ) ROM_END /* Driver */ /* YEAR NAME PARENT COMPAT MACHINE INPUT STATE INIT COMPANY FULLNAME FLAGS */ COMP( 1980, bml3, 0, 0, bml3, bml3, bml3_state, 0, ""Hitachi"", ""MB-6890 Basic Master Level 3"", MACHINE_NOT_WORKING) COMP( 1982, bml3mk2,bml3, 0, bml3mk2, bml3, bml3_state, 0, ""Hitachi"", ""MB-6891 Basic Master Level 3 Mark 2"", MACHINE_NOT_WORKING) COMP( 1983, bml3mk5,bml3, 0, bml3mk5, bml3, bml3_state, 0, ""Hitachi"", ""MB-6892 Basic Master Level 3 Mark 5"", MACHINE_NOT_WORKING) ",16241,True,2732.492557592215,median " #include ""tsMuxer.h"" #include ""pesPacket.h"" #include ""tsPacket.h"" //#include ""tsEncoder.h"" #include #include ""ac3StreamReader.h"" #include ""avCodecs.h"" #include ""dtsStreamReader.h"" #include ""dvbSubStreamReader.h"" #include ""h264StreamReader.h"" #include ""iso_writer.h"" #include ""lpcmStreamReader.h"" #include ""mpegAudioStreamReader.h"" #include ""mpegStreamReader.h"" #include ""muxerManager.h"" #include ""vodCoreException.h"" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include #endif using namespace std; int V3_flags = 0; int HDR10_metadata[6] = {0, 0, 0, 0, 0, 0}; bool isV3() { return V3_flags & HDMV_V3; } bool is4K() { return V3_flags & FOUR_K; } const static uint64_t M_PCR_DELTA = 7000; const static uint64_t SIT_INTERVAL = 76900; // const static uint64_t M_CBR_PCR_DELTA = 2250; const static uint64_t M_CBR_PCR_DELTA = 7000; static const uint8_t PES_INT_AC3_ID = 0x80; static const uint8_t PES_INT_DTS_ID = 0x8a; // static const uint8_t PES_INT_LPCM_ID = 0xa0; static const uint8_t PES_INT_SUB_ID = 0x20; // static const int64_t FIXED_PTS_OFFSET = 27593l; // static const int64_t FIXED_PCR_OFFSET = 45000; static const int64_t DEFAULT_VBV_BUFFER_LEN = 500; // default 500 ms vbv buffer // static const int64_t FIXED_PCR_OFFSET = 8589934592ll - 90000ll*10ll; // static const uint64_t FIXED_PCR_OFFSET = 0; static const int PAT_PID = 0; static const int SIT_PID = 0x1f; static const int NULL_PID = 8191; uint8_t DefaultSitTableOne[] = { 0x47, 0x40, 0x1f, 0x10, 0x00, 0x7f, 0xf0, 0x19, 0xff, 0xff, 0xc1, 0x00, 0x00, 0xf0, 0x0a, 0x63, 0x08, 0xc1, 0x5a, 0xae, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x80, 0x00, 0x34, 0x1e, 0xe7, 0x4e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; TSMuxer::TSMuxer(MuxerManager* owner) : AbstractMuxer(owner) { m_m2tsMode = false; m_vbvLen = DEFAULT_VBV_BUFFER_LEN * 90; m_lastPESDTS = -1; m_cbrBitrate = -1; // mux CBR if bitrate specifed m_minBitrate = -1; m_pcrOnVideo = false; m_endStreamDTS = 0; m_prevM2TSPCROffset = 0; m_pesPID = 0; m_lastTSIndex = -1; m_lastPesLen = -1; m_lastMuxedDts = -1; m_lastPCR = -1; m_lastPMTPCR = -1; m_lastSITPCR = -1; m_nullCnt = 0; m_pmtCnt = 0; // 2; m_patCnt = 0; // 2; m_sitCnt = 1; m_needTruncate = false; m_videoTrackCnt = 0; m_DVvideoTrackCnt = 0; m_videoSecondTrackCnt = 0; m_audioTrackCnt = 0; m_secondaryAudioTrackCnt = 0; m_pgsTrackCnt = 0; m_beforePCRDataWrited = 0; m_useNewStyleAudioPES = false; m_minDts = -1; m_pcrBits = 0; m_pcr_delta = -1; m_patPmtDelta = -1; m_firstPts.push_back(-1); m_lastPts.push_back(-1); m_muxedPacketCnt.push_back(0); m_interliaveInfo.push_back(std::vector()); m_pesIFrame = false; m_pesSpsPps = false; m_computeMuxStats = false; m_pmtFrames = 0; m_curFileStartPts = 0; // FIXED_PTS_OFFSET; m_splitSize = m_splitDuration = 0; m_curFileNum = 0; m_bluRayMode = false; m_hdmvDescriptors = false; m_lastGopNullCnt = 0; m_outBufLen = 0; m_pesData.reserve(1024 * 128); // m_iFrameFound = false; m_mainStreamIndex = -1; m_muxFile = 0; m_isExternalFile = false; m_writeBlockSize = 0; m_frameSize = 188; m_processedBlockSize = 0; m_sublingMuxer = 0; m_outBuf = 0; m_masterMode = false; m_subMode = false; setPtsOffset(0); m_canSwithBlock = true; m_additionCLPISize = 0; #ifdef _DEBUG m_lastProcessedDts = -1000000000; m_lastStreamIndex = -1; #endif } void TSMuxer::setPtsOffset(int64_t value) { m_timeOffset = value; m_fixed_pcr_offset = m_timeOffset - DEFAULT_VBV_BUFFER_LEN * 90; m_prevM2TSPCR = m_fixed_pcr_offset * 300; } void TSMuxer::internalReset() { m_outBufLen = 0; } TSMuxer::~TSMuxer() { delete[] m_outBuf; if (!m_isExternalFile) delete m_muxFile; } void TSMuxer::setVBVBufferLen(int value) { m_vbvLen = (int64_t)value * 90; m_fixed_pcr_offset = m_timeOffset - m_vbvLen; if (m_fixed_pcr_offset < 0) m_fixed_pcr_offset = 0; m_prevM2TSPCR = m_fixed_pcr_offset * 300; } void TSMuxer::intAddStream(const std::string& streamName, const std::string& codecName, int streamIndex, const map& params, AbstractStreamReader* codecReader) { int descriptorLen = 0; uint8_t descrBuffer[1024]; if (codecReader != 0) descriptorLen = codecReader->getTSDescriptor(descrBuffer, m_bluRayMode, m_hdmvDescriptors); if (codecName[0] == 'V') m_mainStreamIndex = streamIndex; else if (codecName[0] == 'A' && m_mainStreamIndex == -1) m_mainStreamIndex = streamIndex; string lang; map::const_iterator itr = params.find(""lang""); if (itr != params.end()) lang = itr->second; int tsStreamIndex = streamIndex + 16; bool isSecondary = codecReader->isSecondary(); if (codecName[0] == 'V') { if (!isSecondary) { int doubleMux = (m_subMode || m_masterMode) ? 2 : 1; if (codecReader->getStreamHDR() == 4) { tsStreamIndex = 0x1015 + m_DVvideoTrackCnt * doubleMux; m_DVvideoTrackCnt++; } else { tsStreamIndex = 0x1011 + m_videoTrackCnt * doubleMux; m_videoTrackCnt++; V3_flags |= NON_DV_TRACK; } if (m_subMode) tsStreamIndex++; } else { tsStreamIndex = 0x1B00 + m_videoSecondTrackCnt; m_videoSecondTrackCnt++; } } else if (codecName[0] == 'A') { if (isSecondary) { tsStreamIndex = 0x1A00 + m_secondaryAudioTrackCnt; m_secondaryAudioTrackCnt++; } else { tsStreamIndex = 0x1100 + m_audioTrackCnt; m_audioTrackCnt++; } } else if (codecName == ""S_HDMV/PGS"") { tsStreamIndex = (V3_flags & 0x1e ? 0x12A0 : 0x1200) + m_pgsTrackCnt; m_pgsTrackCnt++; } else if (codecName == ""S_TEXT/UTF8"") { tsStreamIndex = (V3_flags & 0x1e ? 0x12A0 : 0x1200) + m_pgsTrackCnt; m_pgsTrackCnt++; } m_extIndexToTSIndex[streamIndex] = tsStreamIndex; m_pmt.program_number = 1; if (m_pcrOnVideo) { if (codecName[0] == 'V') m_pmt.pcr_pid = tsStreamIndex; } else m_pmt.pcr_pid = DEFAULT_PCR_PID; if (codecName == ""A_AC3"") m_pesType[tsStreamIndex] = PES_INT_AC3_ID; // m_ac3Cnt++; else if (codecName == ""S_SUP"") m_pesType[tsStreamIndex] = PES_PRIVATE_DATA1; else if (codecName == ""S_HDMV/PGS"") m_pesType[tsStreamIndex] = PES_PRIVATE_DATA1; else if (codecName == ""S_TEXT/UTF8"") m_pesType[tsStreamIndex] = PES_PRIVATE_DATA1; else if (codecName == ""A_MP3"") m_pesType[tsStreamIndex] = PES_AUDIO_ID; else if (codecName == ""A_DTS"") m_pesType[tsStreamIndex] = PES_INT_DTS_ID; // m_dtsCnt++; else if (codecName == ""A_LPCM"") m_pesType[tsStreamIndex] = PES_PRIVATE_DATA1; // PES_INT_LPCM_ID; //m_lpcmCnt++; else if (codecName[0] == 'V') { if (codecName == ""V_MS/VFW/WVC1"") { m_pesType[tsStreamIndex] = PES_VC1_ID; } else { m_pesType[tsStreamIndex] = (m_m2tsMode ? PES_VIDEO_ID : PES_VIDEO_ID - 1); // m_videoCnt++; } } else if (codecName[0] == 'A') { m_pesType[tsStreamIndex] = PES_AUDIO_ID; // m_audioCnt++; } else if (codecName[0] == 'S') { m_pesType[tsStreamIndex] = PES_INT_SUB_ID; // m_subCnt++; } if (codecName[0] == 'V') { map::const_iterator itr = params.find(""fps""); if (itr != params.end()) { double fps = strToDouble(itr->second.c_str()); LTRACE(LT_DEBUG, 0, ""Muxing fps: "" << fps); } } if (codecName == ""V_MPEG4/ISO/AVC"") { H264StreamReader* h264Reader = (H264StreamReader*)codecReader; // h264Reader->setH264SPSCont(m_h264SPSCont); m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_VIDEO_H264, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else if (codecName == ""V_MPEG4/ISO/MVC"") { H264StreamReader* h264Reader = (H264StreamReader*)codecReader; m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_VIDEO_MVC, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else if (codecName == ""V_MPEGH/ISO/HEVC"") { int stream_type = STREAM_TYPE_VIDEO_H265; // For non-bluray, second Dolby Vision track must be stream_type 06 = private data if (!m_bluRayMode && tsStreamIndex == 0x1015 && (V3_flags & NON_DV_TRACK)) stream_type = STREAM_TYPE_PRIVATE_DATA; m_pmt.pidList.insert(std::make_pair( tsStreamIndex, PMTStreamInfo(stream_type, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else if (codecName == ""V_MS/VFW/WVC1"") m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_VIDEO_VC1, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else if (codecName == ""V_MPEG-2"") m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_VIDEO_MPEG2, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else if (codecName == ""A_AAC"") m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_AUDIO_AAC, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else if (codecName == ""S_SUP"") m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_SUB_PGS, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else if (codecName == ""S_HDMV/PGS"") m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_SUB_PGS, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else if (codecName == ""S_TEXT/UTF8"") m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_SUB_PGS, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else if (codecName == ""A_AC3"") { AC3StreamReader* ac3Reader = (AC3StreamReader*)codecReader; ac3Reader->setNewStyleAudioPES(m_useNewStyleAudioPES); int streamType = 0; if (ac3Reader->isTrueHD() && !ac3Reader->getDownconvertToAC3()) streamType = STREAM_TYPE_AUDIO_EAC3_TRUE_HD; else if (ac3Reader->isEAC3() && !ac3Reader->getDownconvertToAC3()) { if (ac3Reader->isSecondary()) streamType = STREAM_TYPE_AUDIO_EAC3_SECONDARY; else if (ac3Reader->isAC3()) streamType = STREAM_TYPE_AUDIO_EAC3; else streamType = STREAM_TYPE_AUDIO_EAC3_ATSC; } else streamType = STREAM_TYPE_AUDIO_AC3; m_pmt.pidList.insert(std::make_pair( tsStreamIndex, PMTStreamInfo(streamType, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else if (codecName == ""A_MP3"") { MpegAudioStreamReader* mp3Reader = (MpegAudioStreamReader*)codecReader; if (mp3Reader->getLayer() >= 2) m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_AUDIO_MPEG2, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); else m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_AUDIO_MPEG1, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else if (codecName == ""A_LPCM"") { m_pmt.pidList.insert( std::make_pair(tsStreamIndex, PMTStreamInfo(STREAM_TYPE_AUDIO_LPCM, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else if (codecName == ""A_DTS"") { DTSStreamReader* dtsReader = (DTSStreamReader*)codecReader; dtsReader->setNewStyleAudioPES(m_useNewStyleAudioPES); int audioType = 0; if (dtsReader->getDTSHDMode() && !dtsReader->getDownconvertToDTS()) { // if (dtsReader->getDTSHDMode() == DTSStreamReader::DTS_SUBTYPE_EXPRESS) if (dtsReader->isSecondary()) audioType = STREAM_TYPE_AUDIO_DTS_HD_SECONDARY; else if (dtsReader->getDTSHDMode() == DTSStreamReader::DTS_SUBTYPE_MASTER_AUDIO) audioType = STREAM_TYPE_AUDIO_DTS_HD_MASTER_AUDIO; else audioType = STREAM_TYPE_AUDIO_DTS_HD; } else { audioType = STREAM_TYPE_AUDIO_DTS; } m_pmt.pidList.insert(std::make_pair( tsStreamIndex, PMTStreamInfo(audioType, tsStreamIndex, descrBuffer, descriptorLen, codecReader, lang, isSecondary))); } else THROW(ERR_UNKNOWN_CODEC, ""Unsupported codec "" << codecName << "" for TS/M2TS muxing.""); m_streamInfo[DEFAULT_PCR_PID].m_tsCnt = 0; buildNULL(); buildPAT(); buildPMT(); } bool TSMuxer::doFlush() { if (!m_lastPts.empty()) m_lastPts[m_lastPts.size() - 1] += m_additionCLPISize; uint64_t newPCR = 0; if (m_m2tsMode) { newPCR = (m_endStreamDTS - m_minDts) / INT_FREQ_TO_TS_FREQ + 0.5 + m_fixed_pcr_offset; if (m_cbrBitrate != -1 && m_lastPCR != -1) { uint64_t cbrPCR = m_lastPCR + m_pcrBits * 90000.0 / m_cbrBitrate + 0.5; newPCR = FFMAX(newPCR, cbrPCR); } } return doFlush(newPCR, 0); } bool TSMuxer::doFlush(uint64_t newPCR, int64_t pcrGAP) { flushTSFrame(); if (m_sectorSize > 0) { // round file to sector size. It's also can be applied to any file in a m2ts mode int nullCnt = 0; if (m_processedBlockSize % m_sectorSize) nullCnt = m_sectorSize - (m_processedBlockSize % m_sectorSize); writeNullPackets(nullCnt / m_frameSize); } if (m_m2tsMode) processM2TSPCR(newPCR, pcrGAP); unsigned lastBlockSize = m_outBufLen & (MuxerManager::PHYSICAL_SECTOR_SIZE - 1); // last 64K of data unsigned roundBufLen = m_outBufLen & ~(MuxerManager::PHYSICAL_SECTOR_SIZE - 1); if (m_owner->isAsyncMode()) { if (lastBlockSize > 0) { assert(m_sectorSize == 0); // we should not be here in interleaved mode! uint8_t* newBuff = new uint8_t[lastBlockSize]; memcpy(newBuff, m_outBuf + roundBufLen, lastBlockSize); m_owner->asyncWriteBuffer(this, m_outBuf, roundBufLen, m_muxFile); m_outBuf = newBuff; } else { m_owner->asyncWriteBuffer(this, m_outBuf, roundBufLen, m_muxFile); m_outBuf = 0; } } else { m_owner->syncWriteBuffer(this, m_outBuf, roundBufLen, m_muxFile); memmove(m_outBuf, m_outBuf + roundBufLen, lastBlockSize); } m_outBufLen = lastBlockSize; assert(!m_sectorSize || m_outBufLen == 0); return true; } int TSMuxer::writeOutFile(uint8_t* buffer, int len) { int rez = m_muxFile->write(buffer, len); return rez; } bool TSMuxer::close() { if (m_isExternalFile) return true; if (m_sectorSize) { assert(m_outBufLen == 0 && m_muxFile->size() % m_sectorSize == 0); } if (!m_muxFile->close()) return false; if (m_sectorSize) return true; if (m_outBufLen > 0) { if (!m_muxFile->open(m_outFileName.c_str(), AbstractOutputStream::ofWrite + AbstractOutputStream::ofAppend)) return false; if (!writeOutFile(m_outBuf, m_outBufLen)) return false; } bool bRes = m_muxFile->close(); return bRes; } int TSMuxer::calcM2tsFrameCnt() { uint32_t byteCnt = 0; for (auto& i : m_m2tsDelayBlocks) byteCnt += i.second; byteCnt -= m_prevM2TSPCROffset; byteCnt += m_outBufLen; assert(byteCnt % 192 == 0); return byteCnt / 192; } void TSMuxer::processM2TSPCR(int64_t pcrVal, int64_t pcrGAP) { int m2tsFrameCnt = calcM2tsFrameCnt(); int64_t hiResPCR = pcrVal * 300 - pcrGAP; uint64_t pcrValDif = hiResPCR - m_prevM2TSPCR; // m2ts pcr clock based on full 27Mhz counter double pcrIncPerFrame = double(pcrValDif + 0.1) / (double)m2tsFrameCnt; double curM2TSPCR = m_prevM2TSPCR; uint8_t* curPos; if (m_m2tsDelayBlocks.size() > 0) { int offset = m_prevM2TSPCROffset; for (auto& i : m_m2tsDelayBlocks) { curPos = i.first + offset; int j = offset; for (; j < i.second; j += 192) { curM2TSPCR += pcrIncPerFrame; writeM2TSHeader(curPos, (uint64_t)curM2TSPCR); curPos += 192; } if (m_owner->isAsyncMode()) m_owner->asyncWriteBuffer(this, i.first, i.second, m_muxFile); else { m_owner->syncWriteBuffer(this, i.first, i.second, m_muxFile); delete[] i.first; } offset = j - i.second; } m_prevM2TSPCROffset = offset; m_m2tsDelayBlocks.clear(); } curPos = m_outBuf + m_prevM2TSPCROffset; uint8_t* end = m_outBuf + m_outBufLen; for (; curPos < end; curPos += 192) { curM2TSPCR += pcrIncPerFrame; writeM2TSHeader(curPos, (uint64_t)curM2TSPCR); } assert(curPos == end); m_prevM2TSPCROffset = m_outBufLen; // assert((int64_t) curM2TSPCR == hiResPCR); m_prevM2TSPCR = hiResPCR; } void TSMuxer::writeEmptyPacketWithPCRTest(int64_t pcrVal) { if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } uint8_t* curBuf = m_outBuf + m_outBufLen; TSPacket* tsPacket = (TSPacket*)curBuf; uint32_t* initTS = (uint32_t*)curBuf; *initTS = TSPacket::TS_FRAME_SYNC_BYTE; initTS[1] = 0x07 + TSPacket::PCR_BIT_VAL; tsPacket->setPID(m_pmt.pcr_pid); tsPacket->afExists = 1; tsPacket->adaptiveField.setPCR33(pcrVal); // tsPacket->counter = m_streamInfo[m_pmt.pcr_pid].m_tsCnt++; tsPacket->counter = m_streamInfo[m_pmt.pcr_pid].m_tsCnt; // do not increment counter because data_exists == 0 memset(curBuf + tsPacket->getHeaderSize(), 0xff, TS_FRAME_SIZE - tsPacket->getHeaderSize()); tsPacket->adaptiveField.length += TS_FRAME_SIZE - tsPacket->getHeaderSize(); m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; } void TSMuxer::writeEmptyPacketWithPCR(int64_t pcrVal) { if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } uint8_t* curBuf = m_outBuf + m_outBufLen; TSPacket* tsPacket = (TSPacket*)curBuf; uint32_t* initTS = (uint32_t*)curBuf; *initTS = TSPacket::TS_FRAME_SYNC_BYTE; initTS[1] = 0x07 + TSPacket::PCR_BIT_VAL; tsPacket->setPID(m_pmt.pcr_pid); tsPacket->afExists = 1; tsPacket->adaptiveField.setPCR33(pcrVal); // tsPacket->counter = m_streamInfo[m_pmt.pcr_pid].m_tsCnt++; tsPacket->counter = m_streamInfo[m_pmt.pcr_pid].m_tsCnt; // do not increment counter becouse data_exists == 0 memset(curBuf + tsPacket->getHeaderSize(), 0xff, TS_FRAME_SIZE - tsPacket->getHeaderSize()); tsPacket->adaptiveField.length += TS_FRAME_SIZE - tsPacket->getHeaderSize(); m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; if (m_m2tsMode) processM2TSPCR(pcrVal, 0); writeOutBuffer(); } void TSMuxer::buildPesHeader(int pesStreamID, AVPacket& avPacket, int pid) { int64_t curDts = nanoClockToPts(avPacket.dts) + m_timeOffset; int64_t curPts = nanoClockToPts(avPacket.pts) + m_timeOffset; uint8_t tmpBuffer[2048]; PESPacket* pesPacket = (PESPacket*)tmpBuffer; if (curDts != curPts) pesPacket->serialize(curPts, curDts, pesStreamID); else pesPacket->serialize(curPts, pesStreamID); m_lastPESDTS = curDts; m_fullPesDTS = avPacket.dts; m_fullPesPTS = avPacket.pts; pesPacket->flagsHi |= PES_DATA_ALIGNMENT; // int additionDataSize = avPacket.codec->writePESExtension(pesPacket); AbstractStreamReader* ast = dynamic_cast(avPacket.codec); if (ast) ast->writePESExtension(pesPacket, avPacket); if (avPacket.flags & AVPacket::IS_COMPLETE_FRAME) pesPacket->setPacketLength(avPacket.size + pesPacket->getHeaderLength()); PriorityDataInfo tmpPriorityData; int additionDataSize = avPacket.codec->writeAdditionData(tmpBuffer + pesPacket->getHeaderLength(), tmpBuffer + sizeof(tmpBuffer), avPacket, &tmpPriorityData); int bufLen = pesPacket->getHeaderLength() + additionDataSize; m_pesData.resize(bufLen); memcpy(m_pesData.data(), tmpBuffer, bufLen); for (auto& i : tmpPriorityData) m_priorityData.push_back(std::pair(i.first + pesPacket->getHeaderLength(), i.second)); } void TSMuxer::addData(int pesStreamID, int pid, AVPacket& avPacket) { int beforePesLen = m_pesData.size(); if (m_pesData.size() == 0) { buildPesHeader(pesStreamID, avPacket, pid); m_pesPID = pid; m_pesIFrame = avPacket.flags & AVPacket::IS_IFRAME; m_pesSpsPps = avPacket.flags & AVPacket::IS_SPS_PPS_IN_GOP; } int oldLen = m_pesData.size(); int pesHeaderLen = oldLen - beforePesLen; if (oldLen > 100000000) THROW(ERR_COMMON, ""Pes packet len too large ( >100Mb). Bad stream or invalid codec speciffed.""); m_pesData.grow(avPacket.size /*+ additionDataSize*/); uint8_t* dst = m_pesData.data() + oldLen; // memcpy(dst, tmpBuffer, additionDataSize); memcpy(dst /*+ additionDataSize*/, avPacket.data, avPacket.size); if (avPacket.flags & AVPacket::PRIORITY_DATA) { if (!m_priorityData.empty() && m_priorityData.rbegin()->first + m_priorityData.rbegin()->second == beforePesLen) m_priorityData.rbegin()->second += avPacket.size + pesHeaderLen; else m_priorityData.push_back(pair(beforePesLen, avPacket.size + pesHeaderLen)); } } void TSMuxer::flushTSFrame() { writePESPacket(); } void TSMuxer::writePATPMT(int64_t pcr, bool force) { if (pcr == -1 || pcr - m_lastPMTPCR >= m_patPmtDelta || force) { m_lastPMTPCR = pcr != -1 ? pcr : m_fixed_pcr_offset; writePAT(); writePMT(); if (force || pcr - m_lastSITPCR > SIT_INTERVAL) { m_lastSITPCR = pcr; writeSIT(); } } } bool TSMuxer::isSplitPoint(const AVPacket& avPacket) { if (avPacket.stream_index != m_mainStreamIndex || !(avPacket.flags & AVPacket::IS_IFRAME)) return false; if (m_splitSize > 0) { return m_muxedPacketCnt[m_muxedPacketCnt.size() - 1] * m_frameSize > m_splitSize; } else if (m_splitDuration > 0) { return (avPacket.pts - m_curFileStartPts) > m_splitDuration; } else return false; } int TSMuxer::getFirstFileNum() const { string fileName = extractFileName(m_origFileName); return strToInt32(fileName.c_str()); } std::string TSMuxer::getNextName(const std::string curName) { std::string result = curName; if (m_bluRayMode) { string fileExt = extractFileExt(m_origFileName); string fileName = extractFileName(m_origFileName); string filePath = extractFilePath(m_origFileName); int origNum = strToInt32(fileName.c_str()); origNum += m_curFileNum; m_curFileNum++; result = closeDirPath(filePath) + strPadLeft(int32ToStr(origNum), 5, '0') + ""."" + fileExt; } else if (m_splitSize > 0 || m_splitDuration > 0) { m_curFileNum++; string fileExt = extractFileExt(m_origFileName); result = m_origFileName.substr(0, m_origFileName.size() - fileExt.size() - 1) + "".split."" + int32ToStr(m_curFileNum) + ""."" + fileExt; } return toNativeSeparators(result); } void TSMuxer::gotoNextFile(uint64_t newPts) { // 2. CloseCurrentFile if (m_owner->isAsyncMode()) m_owner->waitForWriting(); m_muxFile->close(); assert(m_outBufLen == 0); // 3. open new file m_outFileName = getNextName(m_outFileName); if (m_sublingMuxer) m_outFileName = getNextName(m_outFileName); // inc by 2 m_fileNames.push_back(m_outFileName); openDstFile(); for (PIDListMap::iterator itr = m_pmt.pidList.begin(); itr != m_pmt.pidList.end(); ++itr) { PMTStreamInfo& pmtInfo = itr->second; pmtInfo.m_codecReader->onSplitEvent(); if (pmtInfo.m_index.size() == 0) continue; pmtInfo.m_index.push_back(PMTIndex()); /* int spSize = pmtInfo.m_index.size(); if (pmtInfo.m_index[spSize-2].size() > 0) { uint64_t shortPts = (m_lastSplitPts / INT_FREQ_TO_TS_FREQ + 0.5) + m_timeOffset; uint32_t lastPesSize = pmtInfo.m_index[spSize-2].rbegin()->second.m_frameLen; pmtInfo.m_index[spSize-1].insert(make_pair(shortPts, PMTIndexData(firstDataFrame, lastPesSize))); pmtInfo.m_index[spSize-2].erase(pmtInfo.m_index[spSize-2].rbegin()->first); } */ } m_muxedPacketCnt.push_back(0); m_interliaveInfo.push_back(std::vector()); m_interliaveInfo.rbegin()->push_back(0); m_lastPts[m_lastPts.size() - 1] = newPts; //(curPts-FIXED_PTS_OFFSET)*INT_FREQ_TO_TS_FREQ; m_firstPts.push_back(newPts); //((curPts-FIXED_PTS_OFFSET)*INT_FREQ_TO_TS_FREQ); m_lastPts.push_back(newPts); //((curPts-FIXED_PTS_OFFSET)*INT_FREQ_TO_TS_FREQ); m_curFileStartPts = newPts; } void TSMuxer::writePESPacket() { if (m_pesData.size() > 0) { uint32_t tsPackets = 0; int size = m_pesData.size() - 6; if (size <= 0xffff) { m_pesData.data()[4] = size / 256; m_pesData.data()[5] = size % 256; } PMTStreamInfo& streamInfo = m_pmt.pidList[m_pesPID]; PESPacket* pesPacket = (PESPacket*)m_pesData.data(); bool updateIdx = false; if (m_computeMuxStats && (pesPacket->flagsLo & 0x80) == 0x80) { uint64_t curPts = pesPacket->getPts(); uint64_t curDts = curPts; if ((pesPacket->flagsLo & 0xc0) == 0xc0) curDts = pesPacket->getDts(); // LTRACE(LT_INFO, 2, ""pts="" << curPts << "" dts="" << curDts); int idxSize = streamInfo.m_index.size(); if (idxSize == 0) streamInfo.m_index.push_back(PMTIndex()); MPEGStreamReader* vCodec = dynamic_cast(streamInfo.m_codecReader); // bool isH264 = dynamic_cast (streamInfo.m_codecReader); bool SPSRequired = streamInfo.m_codecReader->needSPSForSplit(); SimplePacketizerReader* aCodec = dynamic_cast(streamInfo.m_codecReader); if (vCodec && m_pesIFrame) { // skip some I-frames for H.264 if no SPS/PPS in a gop if (m_pesSpsPps || !SPSRequired) { PMTIndex& curIndex = *streamInfo.m_index.rbegin(); if (curIndex.empty() || curPts > curIndex.rbegin()->first) { curIndex.insert( std::make_pair(curPts, PMTIndexData(m_muxedPacketCnt[m_muxedPacketCnt.size() - 1], 0))); updateIdx = true; } } m_lastGopNullCnt = m_nullCnt; } // else if (vCodec) { // PMTIndex& curIndex = *streamInfo.m_index.rbegin(); // curIndex.insert(std::make_pair(curPts, PMTIndexData(m_muxedPacketCnt[m_muxedPacketCnt.size()-1], // m_pesDataSize))); //} else if (aCodec) { if (m_videoTrackCnt + m_videoSecondTrackCnt == 0) { m_lastGopNullCnt = m_nullCnt; } PMTIndex& curIndex = *streamInfo.m_index.rbegin(); idxSize = curIndex.size(); if (idxSize == 0 || curPts - curIndex.rbegin()->first >= 90000) { curIndex.insert( std::make_pair(curPts, PMTIndexData(m_muxedPacketCnt[m_muxedPacketCnt.size() - 1], 0))); updateIdx = true; } } } uint8_t* curPtr = m_pesData.data(); uint8_t* dataEnd = curPtr + m_pesData.size(); bool payloadStart = true; for (auto& i : m_priorityData) { uint8_t* blockPtr = m_pesData.data() + i.first; if (blockPtr > curPtr) { tsPackets += writeTSFrames(m_pesPID, curPtr, blockPtr - curPtr, false, payloadStart); payloadStart = false; } tsPackets += writeTSFrames(m_pesPID, blockPtr, i.second, true, payloadStart); curPtr = blockPtr + i.second; } tsPackets += writeTSFrames(m_pesPID, curPtr, dataEnd - curPtr, false, payloadStart); m_pesData.resize(0); m_priorityData.clear(); if (updateIdx) { PMTIndex& curIndex = *streamInfo.m_index.rbegin(); assert(curIndex.rbegin()->second.m_frameLen == 0); curIndex.rbegin()->second.m_frameLen = (tsPackets + 1) * m_frameSize; } } } void TSMuxer::writePCR(uint64_t newPCR) { int bitsRest = 0; if (m_cbrBitrate != -1 && m_minBitrate != -1 && m_lastPCR != -1) { int expectedBits = (newPCR - m_lastPCR) / 90000.0 * m_minBitrate + 0.5; expectedBits -= m_pcrBits; if (expectedBits > 0) { int tsFrames = (expectedBits / 8 / m_frameSize); if (tsFrames * m_frameSize * 8 < expectedBits) tsFrames++; writeNullPackets(tsFrames); if (m_cbrBitrate == m_minBitrate) bitsRest = (tsFrames * m_frameSize * 8) - expectedBits; } } m_pcrBits = bitsRest; // assert(m_pcrBits % 8 == 0); writeEmptyPacketWithPCR(newPCR); m_lastPCR = newPCR; } void TSMuxer::flushTSBuffer() { if (m_owner->isAsyncMode()) m_owner->waitForWriting(); uint64_t fileSize = m_muxFile->size(); if (fileSize == -1) THROW(ERR_FILE_COMMON, ""Can't determine size for file "" << m_outFileName); m_muxFile->close(); if (!m_muxFile->open(m_outFileName.c_str(), File::ofWrite + File::ofAppend)) THROW(ERR_FILE_COMMON, ""Can't reopen file "" << m_outFileName); if (writeOutFile(m_outBuf, m_outBufLen) != m_outBufLen) THROW(ERR_FILE_COMMON, ""Can't write last data block to file "" << m_outFileName); delete[] m_outBuf; m_outBufLen = 0; } void TSMuxer::finishFileBlock(uint64_t newPts, uint64_t newPCR, bool doChangeFile, bool recursive) { if (m_processedBlockSize > 0) { int64_t gapForPATPMT = (192 * 4.0) / 35000000.0 * 27000000.0; doFlush(newPCR, gapForPATPMT); if (!doChangeFile) m_interliaveInfo.rbegin()->push_back(m_processedBlockSize / 192); m_processedBlockSize = 0; m_owner->muxBlockFinished(this); if (m_m2tsMode) assert(m_outBuf == 0 && m_outBufLen == 0); else flushTSBuffer(); m_outBuf = new uint8_t[m_writeBlockSize + 1024]; m_prevM2TSPCROffset = 0; } if (doChangeFile) gotoNextFile(newPts); writePATPMT(newPCR, true); writePCR(newPCR); if (m_sublingMuxer && recursive) m_sublingMuxer->finishFileBlock(newPts, newPCR, doChangeFile, false); } bool TSMuxer::blockFull() const { return m_processedBlockSize >= m_interliaveBlockSize; } bool TSMuxer::muxPacket(AVPacket& avPacket) { /* if (!m_iFrameFound && m_mainStreamIndex != -1) { if (avPacket.stream_index == m_mainStreamIndex) m_iFrameFound = ( avPacket.flags & AVPacket::IS_IFRAME ) != 0; if (!m_iFrameFound) return false; } */ if (avPacket.data == 0 || avPacket.size == 0) { return true; } // if (m_lastProcessedDts != avPacket.dts || m_lastStreamIndex != avPacket.stream_index) // LTRACE(LT_INFO, 2, ""dts="" << avPacket.dts/1000000000.0 << "" index="" << avPacket.stream_index); #ifdef _DEBUG // assert (avPacket.dts >= m_lastProcessedDts); m_lastProcessedDts = avPacket.dts; m_lastStreamIndex = avPacket.stream_index; #endif if (avPacket.stream_index == m_mainStreamIndex) { MPEGStreamReader* mpegReader = dynamic_cast(avPacket.codec); if (mpegReader) m_additionCLPISize = INTERNAL_PTS_FREQ / mpegReader->getFPS(); if (avPacket.duration > 0) *m_lastPts.rbegin() = FFMAX(*m_lastPts.rbegin(), avPacket.pts + avPacket.duration); else *m_lastPts.rbegin() = FFMAX(*m_lastPts.rbegin(), avPacket.pts); } if (m_firstPts[m_firstPts.size() - 1] == -1 /*|| avPacket.pts < m_firstPts[m_firstPts.size()-1]*/) { if (m_firstPts[m_firstPts.size() - 1] == -1) { m_curFileStartPts = avPacket.pts; uint64_t firstPtsShift = nanoClockToPts(avPacket.pts); m_fixed_pcr_offset = m_timeOffset - m_vbvLen + firstPtsShift; if (m_fixed_pcr_offset < 0) m_fixed_pcr_offset = 0; m_prevM2TSPCR = (m_fixed_pcr_offset - 100) * 300; // add a little extra delta (100) to prevent 0 bitrate for first several packets } m_firstPts[m_firstPts.size() - 1] = avPacket.pts; } if (m_pcr_delta == -1) { if (m_cbrBitrate != -1) m_pcr_delta = M_CBR_PCR_DELTA; else m_pcr_delta = M_PCR_DELTA; m_patPmtDelta = m_m2tsMode ? M_PCR_DELTA : PCR_FREQUENCY / 4; } if (m_minDts == -1) m_minDts = avPacket.dts; int tsIndex = m_extIndexToTSIndex[avPacket.stream_index]; if (tsIndex == 0) THROW(ERR_TS_COMMON, ""Unknown track number "" << avPacket.stream_index); bool newPES = false; if (avPacket.dts != m_streamInfo[tsIndex].m_dts || avPacket.pts != m_streamInfo[tsIndex].m_pts || tsIndex != m_lastTSIndex || avPacket.flags & AVPacket::FORCE_NEW_FRAME) { writePESPacket(); newPES = true; } m_lastTSIndex = tsIndex; int64_t newPCR = (avPacket.dts - m_minDts) / INT_FREQ_TO_TS_FREQ + 0.5 + m_fixed_pcr_offset; if (m_cbrBitrate != -1 && m_lastPCR != -1) { int64_t cbrPCR = m_lastPCR + m_pcrBits * 90000.0 / m_cbrBitrate + 0.5; newPCR = FFMAX(newPCR, cbrPCR); } if (newPES && m_canSwithBlock && (isSplitPoint(avPacket) || isSplitPoint(avPacket))) { finishFileBlock(avPacket.pts, newPCR, true); // goto next file } else if (newPES && m_interliaveBlockSize > 0 && m_canSwithBlock && (blockFull() || m_sublingMuxer && m_sublingMuxer->blockFull())) { finishFileBlock(avPacket.pts, newPCR, false); // interleave SSIF here } else if (newPCR - m_lastPCR >= m_pcr_delta) { if (m_interliaveBlockSize == 0 || avPacket.stream_index == m_mainStreamIndex) { writePATPMT(newPCR); writePCR(newPCR); } } m_streamInfo[tsIndex].m_pts = avPacket.pts; m_streamInfo[tsIndex].m_dts = avPacket.dts; int pesStreamID = m_pesType[tsIndex]; if (pesStreamID <= SYSTEM_START_CODE) { if (m_useNewStyleAudioPES) pesStreamID = PES_VC1_ID; else pesStreamID = PES_PRIVATE_DATA1; } addData(pesStreamID, tsIndex, avPacket); MPEGStreamReader* mpegReader = dynamic_cast(avPacket.codec); if (avPacket.duration > 0) m_endStreamDTS = avPacket.dts + avPacket.duration; else if (mpegReader) m_endStreamDTS = avPacket.dts + INTERNAL_PTS_FREQ / mpegReader->getFPS(); else m_endStreamDTS = avPacket.dts; return true; } int TSMuxer::writeTSFrames(int pid, uint8_t* buffer, int len, bool priorityData, bool payloadStart) { int result = 0; uint8_t* curPos = buffer; uint8_t* end = buffer + len; int streamType = m_pmt.pidList[pid].m_streamType; bool tsPriority = priorityData; StreamInfo& streamInfo = m_streamInfo[pid]; while (curPos < end) { if (m_cbrBitrate != -1 && m_lastPCR != -1) { int64_t newPCR = m_lastPCR + m_pcrBits * 90000.0 / m_cbrBitrate + 0.5; if (newPCR - m_lastPCR >= m_pcr_delta && m_lastPCR != -1) { m_pcrBits = 0; writePATPMT(newPCR); writePCR(newPCR); if (m_lastPESDTS != -1 && m_lastPCR > m_lastPESDTS) { LTRACE(LT_ERROR, 2, ""VBV buffer overflow at position "" << (m_lastPCR - m_fixed_pcr_offset) / 90000.0 << "" sec""); } } } if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } int tmpBufferLen = end - curPos; uint32_t* initTS = (uint32_t*)(m_outBuf + m_outBufLen); *initTS = TSPacket::TS_FRAME_SYNC_BYTE + TSPacket::DATA_EXIST_BIT_VAL; TSPacket* tsPacket = (TSPacket*)(m_outBuf + m_outBufLen); int payloadLen = TS_FRAME_SIZE - tsPacket->getHeaderSize(); tsPacket->setPID(pid); tsPacket->counter = streamInfo.m_tsCnt++; tsPacket->payloadStart = payloadStart; // curPos == buffer; payloadStart = false; tsPacket->priority = tsPriority; if (tmpBufferLen < payloadLen) { // insert padding bytes if (!tsPacket->afExists) { tsPacket->afExists = 1; if (payloadLen - tmpBufferLen == 1) { tsPacket->adaptiveField.length = 0; payloadLen--; } else { initTS[1] = 0x01; // zero all af flags, set af len to 1. payloadLen -= 2; } } memset((uint8_t*)tsPacket + tsPacket->getHeaderSize(), 0xff, payloadLen - tmpBufferLen); tsPacket->adaptiveField.length += payloadLen - tmpBufferLen; payloadLen = tmpBufferLen; } int tsHeaderSize = tsPacket->getHeaderSize(); memcpy(m_outBuf + m_outBufLen + tsHeaderSize, curPos, payloadLen); curPos += payloadLen; m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; writeOutBuffer(); result++; } return result; } void TSMuxer::buildNULL() { *((uint32_t*)m_nullBuffer) = TSPacket::TS_FRAME_SYNC_BYTE; TSPacket* tsPacket = (TSPacket*)m_nullBuffer; tsPacket->setPID(NULL_PID); tsPacket->dataExists = 1; memset(m_nullBuffer + TSPacket::TS_HEADER_SIZE, 0xff, TS_FRAME_SIZE - TSPacket::TS_HEADER_SIZE); } void TSMuxer::buildPAT() { *((uint32_t*)m_patBuffer) = TSPacket::TS_FRAME_SYNC_BYTE + TSPacket::DATA_EXIST_BIT_VAL; TSPacket* tsPacket = (TSPacket*)m_patBuffer; tsPacket->setPID(PAT_PID); tsPacket->dataExists = 1; tsPacket->payloadStart = 1; m_pat.pmtPids[SIT_PID] = 0; // add NIT. program number = 0 m_pat.pmtPids[DEFAULT_PMT_PID] = 1; // add PMT. program number = 1 m_pat.transport_stream_id = 1; // version of transport stream uint32_t size = m_pat.serialize(m_patBuffer + TSPacket::TS_HEADER_SIZE, TS_FRAME_SIZE - TSPacket::TS_HEADER_SIZE); memset(m_patBuffer + TSPacket::TS_HEADER_SIZE + size, 0xff, TS_FRAME_SIZE - TSPacket::TS_HEADER_SIZE - size); } void TSMuxer::buildPMT() { *((uint32_t*)m_pmtBuffer) = TSPacket::TS_FRAME_SYNC_BYTE + TSPacket::DATA_EXIST_BIT_VAL; TSPacket* tsPacket = (TSPacket*)m_pmtBuffer; tsPacket->setPID(DEFAULT_PMT_PID); tsPacket->dataExists = 1; tsPacket->payloadStart = 1; uint32_t size = m_pmt.serialize(m_pmtBuffer + TSPacket::TS_HEADER_SIZE, 3864, m_bluRayMode, m_hdmvDescriptors); uint8_t* pmtEnd = m_pmtBuffer + TSPacket::TS_HEADER_SIZE + size; uint8_t* curPos = m_pmtBuffer + TS_FRAME_SIZE; for (; curPos < pmtEnd; curPos += TS_FRAME_SIZE) { memmove(curPos + 4, curPos, pmtEnd - curPos); pmtEnd += 4; *((uint32_t*)curPos) = TSPacket::TS_FRAME_SYNC_BYTE + TSPacket::DATA_EXIST_BIT_VAL; TSPacket* tsPacket2 = (TSPacket*)curPos; tsPacket2->setPID(DEFAULT_PMT_PID); tsPacket2->dataExists = 1; tsPacket2->payloadStart = 0; } int oldPmtSize = pmtEnd - m_pmtBuffer; int roundSize = pmtEnd - m_pmtBuffer; if (roundSize % TS_FRAME_SIZE != 0) roundSize = (roundSize / TS_FRAME_SIZE + 1) * TS_FRAME_SIZE; memset(pmtEnd, 0xff, roundSize - oldPmtSize); m_pmtFrames = roundSize / TS_FRAME_SIZE; } void TSMuxer::buildSIT() {} void TSMuxer::writeNullPackets(int cnt) { for (int i = 0; i < cnt; i++) { if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } memcpy(m_outBuf + m_outBufLen, m_nullBuffer, TS_FRAME_SIZE); TSPacket* tsPacket = (TSPacket*)(m_outBuf + m_outBufLen); tsPacket->counter = m_nullCnt++; m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; writeOutBuffer(); } } bool TSMuxer::appendM2TSNullPacketToFile(uint64_t curFileSize, int counter, int* packetsWrited) { *packetsWrited = 0; while (counter < 0) counter += 16; uint8_t tmpBuff[192]; File* file = dynamic_cast(m_muxFile); file->seek(curFileSize - 192, File::smBegin); int readCnt = file->read(tmpBuff, 192); if (readCnt != 192) return false; memcpy(tmpBuff + 4, m_nullBuffer, TS_FRAME_SIZE); TSPacket* tsPacket = (TSPacket*)(tmpBuff); for (uint64_t newFileSize = curFileSize; newFileSize % (2048 * 3) != 0; newFileSize += 192) { tsPacket->counter = counter++; if (file->write(tmpBuff, 192) != 192) return false; // m_muxedPacketCnt[m_muxedPacketCnt.size()-1]++; (*packetsWrited)++; } return true; } void TSMuxer::writePAT() { if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } memcpy(m_outBuf + m_outBufLen, m_patBuffer, TS_FRAME_SIZE); TSPacket* tsPacket = (TSPacket*)(m_outBuf + m_outBufLen); tsPacket->counter = m_patCnt++; m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; writeOutBuffer(); } void TSMuxer::writePMT() { uint8_t* curPos = m_pmtBuffer; for (int i = 0; i < m_pmtFrames; i++) { if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } memcpy(m_outBuf + m_outBufLen, curPos, TS_FRAME_SIZE); TSPacket* tsPacket = (TSPacket*)(m_outBuf + m_outBufLen); tsPacket->counter = m_pmtCnt++; m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; writeOutBuffer(); curPos += TS_FRAME_SIZE; } } void TSMuxer::writeSIT() { if (m_m2tsMode) { m_outBufLen += 4; m_processedBlockSize += 4; m_pcrBits += 4 * 8; } memcpy(m_outBuf + m_outBufLen, DefaultSitTableOne, TS_FRAME_SIZE); TSPacket* tsPacket = (TSPacket*)(m_outBuf + m_outBufLen); tsPacket->counter = m_sitCnt++; m_outBufLen += TS_FRAME_SIZE; m_processedBlockSize += TS_FRAME_SIZE; m_pcrBits += TS_FRAME_SIZE * 8; m_muxedPacketCnt[m_muxedPacketCnt.size() - 1]++; writeOutBuffer(); } void TSMuxer::writeOutBuffer() { if (m_outBufLen >= m_writeBlockSize) { int toFileLen = m_writeBlockSize & ~(MuxerManager::PHYSICAL_SECTOR_SIZE - 1); if (m_owner->isAsyncMode()) { uint8_t* newBuf = new uint8_t[m_writeBlockSize + 1024]; memcpy(newBuf, m_outBuf + toFileLen, m_outBufLen - toFileLen); if (m_m2tsMode) { if (m_prevM2TSPCROffset >= toFileLen && m_m2tsDelayBlocks.empty()) { m_owner->asyncWriteBuffer(this, m_outBuf, toFileLen, m_muxFile); m_prevM2TSPCROffset -= toFileLen; } else m_m2tsDelayBlocks.push_back(std::make_pair(m_outBuf, toFileLen)); } else m_owner->asyncWriteBuffer(this, m_outBuf, toFileLen, m_muxFile); m_outBuf = newBuf; } else { if (!m_m2tsMode) m_owner->syncWriteBuffer(this, m_outBuf, toFileLen, m_muxFile); else { if (m_prevM2TSPCROffset >= toFileLen && m_m2tsDelayBlocks.empty()) { m_owner->syncWriteBuffer(this, m_outBuf, toFileLen, m_muxFile); m_prevM2TSPCROffset -= toFileLen; } else { uint8_t* newBuf = new uint8_t[toFileLen]; memcpy(newBuf, m_outBuf, toFileLen); m_m2tsDelayBlocks.push_back(std::make_pair(newBuf, toFileLen)); } } memmove(m_outBuf, m_outBuf + toFileLen, m_outBufLen - toFileLen); } m_outBufLen -= toFileLen; } } void TSMuxer::parseMuxOpt(const std::string& opts) { vector params = splitStr(opts.c_str(), ' '); for (auto& i : params) { vector paramPair = splitStr(trimStr(i).c_str(), '='); if (paramPair.size() == 0) continue; if (paramPair[0] == ""--pcr-on-video-pid"") setPCROnVideoPID(true); else if (paramPair[0] == ""--new-audio-pes"") setNewStyleAudioPES(true); else if (paramPair[0] == ""--hdmv-descriptors"") m_hdmvDescriptors = true; else if (paramPair[0] == ""--bitrate"" && paramPair.size() > 1) { setMaxBitrate(strToDouble(paramPair[1].c_str()) * 1000.0); setMinBitrate(strToDouble(paramPair[1].c_str()) * 1000.0); } else if (paramPair[0] == ""--maxbitrate"" && paramPair.size() > 1) setMaxBitrate(strToDouble(paramPair[1].c_str()) * 1000.0); else if (paramPair[0] == ""--minbitrate"" && paramPair.size() > 1) setMinBitrate(strToDouble(paramPair[1].c_str()) * 1000.0); else if (paramPair[0] == ""--vbv-len"" && paramPair.size() > 1) setVBVBufferLen(strToInt32(paramPair[1].c_str())); else if (paramPair[0] == ""--split-duration"") { setSplitDuration(strToInt64(paramPair[1].c_str()) * 1000000000ull); m_computeMuxStats = true; } else if (paramPair[0] == ""--split-size"") { uint64_t coeff = 1; string postfix; for (auto& j : paramPair[1]) if (!(j >= '0' && j <= '9' || j == '.')) postfix += j; postfix = strToUpperCase(postfix); if (postfix == ""GB"") coeff = 1000000000ull; else if (postfix == ""GIB"") coeff = 1024ull * 1024ull * 1024ull; else if (postfix == ""MB"") coeff = 1000000; else if (postfix == ""MIB"") coeff = 1024 * 1024; else if (postfix == ""KB"") coeff = 1000; else if (postfix == ""KIB"") coeff = 1024; string prefix = paramPair[1].substr(0, paramPair[1].size() - postfix.size()); setSplitSize(strToDouble(prefix.c_str()) * coeff); m_computeMuxStats = true; } else if (paramPair[0] == ""--blu-ray"" || paramPair[0] == ""--blu-ray-v3"" || paramPair[0] == ""--avchd"") { m_bluRayMode = true; m_computeMuxStats = true; } else if (paramPair[0] == ""--cut-start"" || paramPair[0] == ""--cut-end"") { m_computeMuxStats = true; } } } void TSMuxer::setSubMode(AbstractMuxer* mainMuxer, bool flushInterleavedBlock) { m_sublingMuxer = dynamic_cast(mainMuxer); m_subMode = true; m_canSwithBlock = flushInterleavedBlock; m_interliaveInfo.rbegin()->push_back(0); } void TSMuxer::joinToMasterFile() { m_isExternalFile = true; m_muxFile = dynamic_cast(m_sublingMuxer)->getDstFile(); } void TSMuxer::setMasterMode(AbstractMuxer* subMuxer, bool flushInterleavedBlock) { m_sublingMuxer = dynamic_cast(subMuxer); m_masterMode = true; m_canSwithBlock = flushInterleavedBlock; m_interliaveInfo.rbegin()->push_back(0); } void TSMuxer::openDstFile() { m_muxFile = m_fileFactory ? m_fileFactory->createFile() : new File(); int systemFlags = 0; #ifdef _WIN32 if (m_owner->isAsyncMode()) systemFlags += FILE_FLAG_NO_BUFFERING; #endif if (!m_muxFile->open(m_outFileName.c_str(), File::ofWrite, systemFlags)) THROW(ERR_CANT_CREATE_FILE, ""Can't create file "" << m_outFileName); } vector TSMuxer::getFirstPts() { std::vector rez; for (auto& i : m_firstPts) rez.push_back(nanoClockToPts(i) + m_timeOffset); return rez; } void TSMuxer::alignPTS(TSMuxer* otherMuxer) { if (!m_lastPts.empty() && !otherMuxer->m_lastPts.empty()) { int64_t minPTS = FFMIN(*m_lastPts.rbegin(), *otherMuxer->m_lastPts.rbegin()); *m_lastPts.rbegin() = minPTS; *otherMuxer->m_lastPts.rbegin() = minPTS; } } vector TSMuxer::getLastPts() { std::vector rez; for (auto& i : m_lastPts) rez.push_back(nanoClockToPts(i) + m_timeOffset); // if (!rez.empty()) // *rez.rbegin() += m_mainStreamFrameDuration; return rez; } void TSMuxer::setFileName(const std::string& fileName, FileFactory* fileFactory) { m_curFileNum = 0; AbstractMuxer::setFileName(fileName, fileFactory); m_outFileName = getNextName(fileName); string ext = strToUpperCase(extractFileExt(m_outFileName)); setMuxFormat(ext); m_fileNames.clear(); m_fileNames.push_back(m_outFileName); } std::string TSMuxer::getFileNameByIdx(size_t idx) { if (idx < m_fileNames.size()) return m_fileNames[idx]; assert(1); return std::string(); } void TSMuxer::setMuxFormat(const std::string& format) { m_m2tsMode = format == ""M2TS"" || format == ""M2T"" || format == ""MTS"" || format == ""SSIF""; m_writeBlockSize = (m_m2tsMode ? DEFAULT_FILE_BLOCK_SIZE : TS188_ROUND_BLOCK_SIZE); m_outBuf = new uint8_t[m_writeBlockSize + 1024]; m_frameSize = m_m2tsMode ? 192 : 188; if (m_m2tsMode) m_sectorSize = 1024 * 6; } bool TSMuxer::isInterleaveMode() const { return m_masterMode || m_subMode; } std::vector TSMuxer::getInterleaveInfo(int idx) const { return m_interliaveInfo[idx]; } ",16325,True,2819.3936241779625,median "********************************************************************** * UTILS ********************************************************************** CLASS lcl_utils DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS normalize_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_path) TYPE string. CLASS-METHODS split_path IMPORTING iv_path TYPE string RETURNING VALUE(rv_path_name) TYPE zif_abapgit_ajson=>ty_path_name. CLASS-METHODS validate_array_index IMPORTING iv_path TYPE string iv_index TYPE string RETURNING VALUE(rv_index) TYPE i RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_utils IMPLEMENTATION. METHOD validate_array_index. IF NOT iv_index CO '0123456789'. zcx_abapgit_ajson_error=>raise( |Cannot add non-numeric key [{ iv_index }] to array [{ iv_path }]| ). ENDIF. rv_index = iv_index. IF rv_index = 0. zcx_abapgit_ajson_error=>raise( |Cannot add zero key to array [{ iv_path }]| ). ENDIF. ENDMETHOD. METHOD normalize_path. rv_path = iv_path. IF strlen( rv_path ) = 0. rv_path = '/'. ENDIF. IF rv_path+0(1) <> '/'. rv_path = '/' && rv_path. ENDIF. IF substring( val = rv_path off = strlen( rv_path ) - 1 ) <> '/'. rv_path = rv_path && '/'. ENDIF. ENDMETHOD. METHOD split_path. DATA lv_offs TYPE i. DATA lv_len TYPE i. DATA lv_trim_slash TYPE i. lv_len = strlen( iv_path ). IF lv_len = 0 OR iv_path = '/'. RETURN. "" empty path is the alias for root item = '' + '' ENDIF. IF substring( val = iv_path off = lv_len - 1 ) = '/'. lv_trim_slash = 1. "" ignore last '/' ENDIF. lv_offs = find( val = reverse( iv_path ) sub = '/' off = lv_trim_slash ). IF lv_offs = -1. lv_offs = lv_len. "" treat whole string as the 'name' part ENDIF. lv_offs = lv_len - lv_offs. rv_path_name-path = normalize_path( substring( val = iv_path len = lv_offs ) ). rv_path_name-name = substring( val = iv_path off = lv_offs len = lv_len - lv_offs - lv_trim_slash ). ENDMETHOD. ENDCLASS. ********************************************************************** * PARSER ********************************************************************** CLASS lcl_json_parser DEFINITION FINAL. PUBLIC SECTION. METHODS parse IMPORTING iv_json TYPE string RETURNING VALUE(rt_json_tree) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. TYPES: ty_stack_tt TYPE STANDARD TABLE OF REF TO zif_abapgit_ajson=>ty_node. DATA mt_stack TYPE ty_stack_tt. CLASS-METHODS join_path IMPORTING it_stack TYPE ty_stack_tt RETURNING VALUE(rv_path) TYPE string. METHODS raise IMPORTING iv_error TYPE string RAISING zcx_abapgit_ajson_error. METHODS _parse IMPORTING iv_json TYPE string RETURNING VALUE(rt_json_tree) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error cx_sxml_error. METHODS _get_location IMPORTING iv_json TYPE string iv_offset TYPE i RETURNING VALUE(rv_location) TYPE string. ENDCLASS. CLASS lcl_json_parser IMPLEMENTATION. METHOD parse. DATA lx_sxml_parse TYPE REF TO cx_sxml_parse_error. DATA lx_sxml TYPE REF TO cx_sxml_error. DATA lv_location TYPE string. TRY. "" TODO sane JSON check: "" JSON can be true,false,null,(-)digits "" or start from "" or from { rt_json_tree = _parse( iv_json ). CATCH cx_sxml_parse_error INTO lx_sxml_parse. lv_location = _get_location( iv_json = iv_json iv_offset = lx_sxml_parse->xml_offset ). zcx_abapgit_ajson_error=>raise( iv_msg = |Json parsing error (SXML): { lx_sxml_parse->get_text( ) }| iv_location = lv_location ). CATCH cx_sxml_error INTO lx_sxml. zcx_abapgit_ajson_error=>raise( iv_msg = |Json parsing error (SXML): { lx_sxml->get_text( ) }| iv_location = '@PARSER' ). ENDTRY. ENDMETHOD. METHOD _get_location. DATA lv_json TYPE string. DATA lv_offset TYPE i. DATA lt_text TYPE TABLE OF string. DATA lv_text TYPE string. DATA lv_line TYPE i. DATA lv_pos TYPE i. lv_offset = iv_offset. IF lv_offset < 0. lv_offset = 0. ENDIF. IF lv_offset > strlen( iv_json ). lv_offset = strlen( iv_json ). ENDIF. lv_json = iv_json(lv_offset). REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>cr_lf IN lv_json WITH cl_abap_char_utilities=>newline. SPLIT lv_json AT cl_abap_char_utilities=>newline INTO TABLE lt_text. lv_line = lines( lt_text ). IF lv_line = 0. lv_line = 1. lv_pos = 1. ELSE. READ TABLE lt_text INDEX lv_line INTO lv_text. lv_pos = strlen( lv_text ) + 1. ENDIF. rv_location = |Line { lv_line }, Offset { lv_pos }|. ENDMETHOD. METHOD _parse. DATA lo_reader TYPE REF TO if_sxml_reader. DATA lr_stack_top LIKE LINE OF mt_stack. DATA lo_node TYPE REF TO if_sxml_node. FIELD-SYMBOLS LIKE LINE OF rt_json_tree. CLEAR mt_stack. IF iv_json IS INITIAL. RETURN. ENDIF. lo_reader = cl_sxml_string_reader=>create( cl_abap_codepage=>convert_to( iv_json ) ). "" TODO: self protection, check non-empty, check starting from object ... DO. lo_node = lo_reader->read_next_node( ). IF lo_node IS NOT BOUND. EXIT. ENDIF. CASE lo_node->type. WHEN if_sxml_node=>co_nt_element_open. DATA lt_attributes TYPE if_sxml_attribute=>attributes. DATA lo_attr LIKE LINE OF lt_attributes. DATA lo_open TYPE REF TO if_sxml_open_element. lo_open ?= lo_node. APPEND INITIAL LINE TO rt_json_tree ASSIGNING . -type = to_lower( lo_open->qname-name ). READ TABLE mt_stack INDEX 1 INTO lr_stack_top. IF sy-subrc = 0. -path = join_path( mt_stack ). lr_stack_top->children = lr_stack_top->children + 1. IF lr_stack_top->type = 'array'. -name = |{ lr_stack_top->children }|. -index = lr_stack_top->children. ELSE. lt_attributes = lo_open->get_attributes( ). LOOP AT lt_attributes INTO lo_attr. IF lo_attr->qname-name = 'name' AND lo_attr->value_type = if_sxml_value=>co_vt_text. -name = lo_attr->get_value( ). ENDIF. ENDLOOP. ENDIF. IF -name IS INITIAL. raise( 'Node without name (maybe not JSON)' ). ENDIF. ENDIF. GET REFERENCE OF INTO lr_stack_top. INSERT lr_stack_top INTO mt_stack INDEX 1. WHEN if_sxml_node=>co_nt_element_close. DATA lo_close TYPE REF TO if_sxml_close_element. lo_close ?= lo_node. READ TABLE mt_stack INDEX 1 INTO lr_stack_top. DELETE mt_stack INDEX 1. IF lo_close->qname-name <> lr_stack_top->type. raise( 'Unexpected closing node type' ). ENDIF. WHEN if_sxml_node=>co_nt_value. DATA lo_value TYPE REF TO if_sxml_value_node. lo_value ?= lo_node. -value = lo_value->get_value( ). WHEN OTHERS. raise( 'Unexpected node type' ). ENDCASE. ENDDO. IF lines( mt_stack ) > 0. raise( 'Unexpected end of data' ). ENDIF. ENDMETHOD. METHOD join_path. FIELD-SYMBOLS LIKE LINE OF it_stack. LOOP AT it_stack ASSIGNING . rv_path = ->name && '/' && rv_path. ENDLOOP. ENDMETHOD. METHOD raise. zcx_abapgit_ajson_error=>raise( iv_location = join_path( mt_stack ) iv_msg = |JSON PARSER: { iv_error } @ { join_path( mt_stack ) }| ). ENDMETHOD. ENDCLASS. ********************************************************************** * SERIALIZER ********************************************************************** CLASS lcl_json_serializer DEFINITION FINAL CREATE PRIVATE. PUBLIC SECTION. CLASS-METHODS stringify IMPORTING it_json_tree TYPE zif_abapgit_ajson=>ty_nodes_ts iv_indent TYPE i DEFAULT 0 iv_keep_item_order TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_json_string) TYPE string RAISING zcx_abapgit_ajson_error. CLASS-METHODS class_constructor. PRIVATE SECTION. CLASS-DATA gv_comma_with_lf TYPE string. DATA mt_json_tree TYPE zif_abapgit_ajson=>ty_nodes_ts. DATA mv_keep_item_order TYPE abap_bool. DATA mt_buffer TYPE string_table. DATA mv_indent_step TYPE i. DATA mv_level TYPE i. CLASS-METHODS escape IMPORTING iv_unescaped TYPE string RETURNING VALUE(rv_escaped) TYPE string. METHODS _stringify RETURNING VALUE(rv_json_string) TYPE string RAISING zcx_abapgit_ajson_error. METHODS stringify_node IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node RAISING zcx_abapgit_ajson_error. METHODS stringify_set IMPORTING iv_parent_path TYPE string iv_array TYPE abap_bool RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_json_serializer IMPLEMENTATION. METHOD class_constructor. gv_comma_with_lf = ',' && cl_abap_char_utilities=>newline. ENDMETHOD. METHOD stringify. DATA lo TYPE REF TO lcl_json_serializer. CREATE OBJECT lo. lo->mt_json_tree = it_json_tree. lo->mv_indent_step = iv_indent. lo->mv_keep_item_order = iv_keep_item_order. rv_json_string = lo->_stringify( ). ENDMETHOD. METHOD _stringify. FIELD-SYMBOLS LIKE LINE OF mt_json_tree. READ TABLE mt_json_tree ASSIGNING WITH KEY path = '' name = ''. "" Root IF sy-subrc <> 0. RETURN. ENDIF. stringify_node( ). rv_json_string = concat_lines_of( table = mt_buffer ). ENDMETHOD. METHOD stringify_node. DATA lv_item TYPE string. DATA lv_indent_prefix TYPE string. IF mv_indent_step > 0. lv_indent_prefix = repeat( val = ` ` occ = mv_indent_step * mv_level ). lv_item = lv_indent_prefix. ENDIF. IF is_node-name IS NOT INITIAL AND is_node-index IS INITIAL. "" Not root, not array item IF mv_indent_step > 0. lv_item = lv_item && |""{ is_node-name }"": |. ELSE. lv_item = |""{ is_node-name }"":|. ENDIF. ENDIF. CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-array. lv_item = lv_item && '['. WHEN zif_abapgit_ajson=>node_type-object. lv_item = lv_item && '{'. WHEN zif_abapgit_ajson=>node_type-string. lv_item = lv_item && |""{ escape( is_node-value ) }""|. WHEN zif_abapgit_ajson=>node_type-boolean OR zif_abapgit_ajson=>node_type-number. lv_item = lv_item && is_node-value. WHEN zif_abapgit_ajson=>node_type-null. lv_item = lv_item && 'null'. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( iv_msg = |Unexpected type [{ is_node-type }]| iv_location = is_node-path && is_node-name ). ENDCASE. IF mv_indent_step > 0 AND ( is_node-type = zif_abapgit_ajson=>node_type-array OR is_node-type = zif_abapgit_ajson=>node_type-object ) AND is_node-children > 0. mv_level = mv_level + 1. lv_item = lv_item && cl_abap_char_utilities=>newline. ENDIF. APPEND lv_item TO mt_buffer. "" finish complex item IF is_node-type = zif_abapgit_ajson=>node_type-array OR is_node-type = zif_abapgit_ajson=>node_type-object. DATA lv_children_path TYPE string. DATA lv_tail TYPE string. lv_children_path = is_node-path && is_node-name && '/'. "" for root: path = '' and name = '', so result is '/' CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-array. IF is_node-children > 0. stringify_set( iv_parent_path = lv_children_path iv_array = abap_true ). ENDIF. lv_tail = ']'. WHEN zif_abapgit_ajson=>node_type-object. IF is_node-children > 0. stringify_set( iv_parent_path = lv_children_path iv_array = abap_false ). ENDIF. lv_tail = '}'. ENDCASE. IF mv_indent_step > 0 AND is_node-children > 0. lv_tail = lv_indent_prefix && lv_tail. mv_level = mv_level - 1. ENDIF. APPEND lv_tail TO mt_buffer. ENDIF. ENDMETHOD. METHOD stringify_set. DATA lv_tab_key TYPE string. DATA lv_first_done TYPE abap_bool. FIELD-SYMBOLS LIKE LINE OF mt_json_tree. IF iv_array = abap_true. lv_tab_key = 'array_index'. "" path + index ELSEIF mv_keep_item_order = abap_true. lv_tab_key = 'item_order'. "" path + order ELSE. lv_tab_key = 'primary_key'. "" path + name ENDIF. LOOP AT mt_json_tree ASSIGNING USING KEY (lv_tab_key) WHERE path = iv_parent_path. IF lv_first_done = abap_false. lv_first_done = abap_true. ELSEIF mv_indent_step > 0. APPEND gv_comma_with_lf TO mt_buffer. ELSE. APPEND ',' TO mt_buffer. ENDIF. stringify_node( ). ENDLOOP. IF mv_indent_step > 0 AND lv_first_done = abap_true. "" only of items were in the list APPEND cl_abap_char_utilities=>newline TO mt_buffer. ENDIF. ENDMETHOD. METHOD escape. rv_escaped = iv_unescaped. IF rv_escaped CA |""\\\\\\t\\n\\r|. "" TODO consider performance ... "" see also https://www.json.org/json-en.html rv_escaped = replace( val = rv_escaped sub = '\\' with = '\\\\' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\n| with = '\\n' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\r| with = '\\r' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = |\\t| with = '\\t' occ = 0 ). rv_escaped = replace( val = rv_escaped sub = '""' with = '\\""' occ = 0 ). ENDIF. ENDMETHOD. ENDCLASS. ********************************************************************** * JSON_TO_ABAP ********************************************************************** CLASS lcl_json_to_abap DEFINITION FINAL. PUBLIC SECTION. METHODS constructor IMPORTING !ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL. METHODS to_abap IMPORTING it_nodes TYPE zif_abapgit_ajson=>ty_nodes_ts CHANGING c_container TYPE any RAISING zcx_abapgit_ajson_error. METHODS to_timestamp IMPORTING iv_value TYPE zif_abapgit_ajson=>ty_node-value RETURNING VALUE(rv_result) TYPE timestamp RAISING zcx_abapgit_ajson_error. METHODS to_date IMPORTING iv_value TYPE zif_abapgit_ajson=>ty_node-value RETURNING VALUE(rv_result) TYPE d RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. TYPES: BEGIN OF ty_type_cache, type_path TYPE string, target_field_name TYPE string, dd TYPE REF TO cl_abap_datadescr, type_kind LIKE cl_abap_typedescr=>typekind_any, tab_item_buf TYPE REF TO data, END OF ty_type_cache. DATA mt_node_type_cache TYPE HASHED TABLE OF ty_type_cache WITH UNIQUE KEY type_path. DATA mr_nodes TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. DATA mi_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping. METHODS any_to_abap IMPORTING iv_path TYPE string is_parent_type TYPE ty_type_cache OPTIONAL i_container_ref TYPE REF TO data RAISING zcx_abapgit_ajson_error. METHODS value_to_abap IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node is_node_type TYPE ty_type_cache i_container_ref TYPE REF TO data RAISING zcx_abapgit_ajson_error cx_sy_conversion_no_number. METHODS get_node_type IMPORTING is_node TYPE zif_abapgit_ajson=>ty_node OPTIONAL "" Empty for root is_parent_type TYPE ty_type_cache OPTIONAL i_container_ref TYPE REF TO data OPTIONAL RETURNING VALUE(rs_node_type) TYPE ty_type_cache RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_json_to_abap IMPLEMENTATION. METHOD constructor. mi_custom_mapping = ii_custom_mapping. ENDMETHOD. METHOD to_abap. DATA lr_ref TYPE REF TO data. CLEAR c_container. "" what about data/obj refs ? CLEAR mt_node_type_cache. GET REFERENCE OF c_container INTO lr_ref. GET REFERENCE OF it_nodes INTO mr_nodes. get_node_type( i_container_ref = lr_ref ). "" Pre-cache root node type any_to_abap( iv_path = '' i_container_ref = lr_ref ). ENDMETHOD. METHOD get_node_type. DATA lv_node_type_path TYPE string. DATA lo_sdescr TYPE REF TO cl_abap_structdescr. DATA lo_tdescr TYPE REF TO cl_abap_tabledescr. DATA lo_ddescr TYPE REF TO cl_abap_datadescr. "" Calculate type path IF is_parent_type-type_kind = cl_abap_typedescr=>typekind_table. lv_node_type_path = is_parent_type-type_path && '/-'. "" table item type ELSEIF is_parent_type-type_kind IS NOT INITIAL. lv_node_type_path = is_parent_type-type_path && '/' && is_node-name. ENDIF. "" For root node lv_node_type_path remains '' "" Get or create cached READ TABLE mt_node_type_cache INTO rs_node_type WITH KEY type_path = lv_node_type_path. IF sy-subrc <> 0. rs_node_type-type_path = lv_node_type_path. IF mi_custom_mapping IS BOUND. rs_node_type-target_field_name = to_upper( mi_custom_mapping->to_abap( iv_path = is_node-path iv_name = is_node-name ) ). IF rs_node_type-target_field_name IS INITIAL. rs_node_type-target_field_name = to_upper( is_node-name ). ENDIF. ELSE. rs_node_type-target_field_name = to_upper( is_node-name ). ENDIF. CASE is_parent_type-type_kind. WHEN 'h'. "" Table lo_tdescr ?= is_parent_type-dd. rs_node_type-dd = lo_tdescr->get_table_line_type( ). WHEN 'u' OR 'v'. "" Structure lo_sdescr ?= is_parent_type-dd. lo_sdescr->get_component_type( EXPORTING p_name = rs_node_type-target_field_name RECEIVING p_descr_ref = rs_node_type-dd EXCEPTIONS component_not_found = 4 ). IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( |Path not found| ). ENDIF. WHEN ''. "" Root node rs_node_type-dd ?= cl_abap_typedescr=>describe_by_data_ref( i_container_ref ). WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected parent type| ). ENDCASE. rs_node_type-type_kind = rs_node_type-dd->type_kind. "" for caching and cleaner unintialized access IF rs_node_type-type_kind = 'h'. "" Table lo_tdescr ?= rs_node_type-dd. IF lo_tdescr->table_kind <> 'S'. "" standard lo_ddescr = lo_tdescr->get_table_line_type( ). CREATE DATA rs_node_type-tab_item_buf TYPE HANDLE lo_ddescr. ENDIF. ENDIF. INSERT rs_node_type INTO TABLE mt_node_type_cache. ENDIF. ENDMETHOD. METHOD any_to_abap. DATA ls_node_type LIKE LINE OF mt_node_type_cache. DATA lx_ajson TYPE REF TO zcx_abapgit_ajson_error. DATA lx_root TYPE REF TO cx_root. DATA lr_target_field TYPE REF TO data. FIELD-SYMBOLS TYPE zif_abapgit_ajson=>ty_node. FIELD-SYMBOLS TYPE STANDARD TABLE. FIELD-SYMBOLS TYPE ANY TABLE. FIELD-SYMBOLS TYPE any. FIELD-SYMBOLS TYPE any. "" Assign container CASE is_parent_type-type_kind. WHEN 'h'. "" Table IF is_parent_type-tab_item_buf IS BOUND. "" Indirect hint that table was sorted/hashed, see get_node_type. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. lr_target_field = is_parent_type-tab_item_buf. "" For hashed/sorted table - same buffer for all children ASSIGN is_parent_type-tab_item_buf->* TO . ASSERT sy-subrc = 0. ELSE. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. ENDIF. WHEN 'u' OR 'v'. "" Structure ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. ENDCASE. TRY. "" array_index because stringified index goes in wrong order [1, 10, 2 ...] LOOP AT mr_nodes->* ASSIGNING USING KEY array_index WHERE path = iv_path. "" Get or create type cache record IF is_parent_type-type_kind <> 'h' OR ls_node_type-type_kind IS INITIAL. "" table records are the same, no need to refetch twice ls_node_type = get_node_type( is_node = is_parent_type = is_parent_type ). ENDIF. "" Validate node type IF ls_node_type-type_kind CA 'lr'. "" data/obj ref "" TODO maybe in future zcx_abapgit_ajson_error=>raise( 'Cannot assign to ref' ). ENDIF. "" Find target field reference CASE is_parent_type-type_kind. WHEN 'h'. "" Table IF NOT ls_node_type-target_field_name CO '0123456789'. "" Does not affect anything actually but for integrity zcx_abapgit_ajson_error=>raise( 'Need index to access tables' ). ENDIF. IF is_parent_type-tab_item_buf IS NOT BOUND. "" Indirect hint that table was srt/hsh, see get_node_type APPEND INITIAL LINE TO REFERENCE INTO lr_target_field. ASSERT sy-subrc = 0. ENDIF. WHEN 'u' OR 'v'. FIELD-SYMBOLS TYPE any. ASSIGN COMPONENT ls_node_type-target_field_name OF STRUCTURE TO . ASSERT sy-subrc = 0. GET REFERENCE OF INTO lr_target_field. WHEN ''. "" Root node lr_target_field = i_container_ref. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( 'Unexpected parent type' ). ENDCASE. "" Process value assignment CASE -type. WHEN zif_abapgit_ajson=>node_type-object. IF NOT ls_node_type-type_kind CO 'uv'. zcx_abapgit_ajson_error=>raise( 'Expected structure' ). ENDIF. any_to_abap( iv_path = -path && -name && '/' is_parent_type = ls_node_type i_container_ref = lr_target_field ). WHEN zif_abapgit_ajson=>node_type-array. IF NOT ls_node_type-type_kind = 'h'. zcx_abapgit_ajson_error=>raise( 'Expected table' ). ENDIF. any_to_abap( iv_path = -path && -name && '/' is_parent_type = ls_node_type i_container_ref = lr_target_field ). WHEN OTHERS. value_to_abap( is_node = is_node_type = ls_node_type i_container_ref = lr_target_field ). ENDCASE. IF is_parent_type-tab_item_buf IS BOUND. "" Indirect hint that table was sorted/hashed, see get_node_type. TRY. INSERT INTO TABLE . CATCH cx_sy_itab_duplicate_key. sy-subrc = 4. ENDTRY. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Duplicate insertion' ). ENDIF. ENDIF. ENDLOOP. CATCH zcx_abapgit_ajson_error INTO lx_ajson. IF lx_ajson->location IS INITIAL. lx_ajson->set_location( -path && -name ). ENDIF. RAISE EXCEPTION lx_ajson. CATCH cx_sy_conversion_no_number. zcx_abapgit_ajson_error=>raise( iv_msg = 'Source is not a number' iv_location = -path && -name ). CATCH cx_root INTO lx_root. zcx_abapgit_ajson_error=>raise( iv_msg = lx_root->get_text( ) iv_location = -path && -name ). ENDTRY. ENDMETHOD. METHOD value_to_abap. FIELD-SYMBOLS TYPE any. IF is_node_type-type_kind CA 'lruvh'. "" refs, table, strucs zcx_abapgit_ajson_error=>raise( |Unsupported target for value [{ is_node_type-type_kind }]| ). ENDIF. ASSIGN i_container_ref->* TO . ASSERT sy-subrc = 0. CASE is_node-type. WHEN zif_abapgit_ajson=>node_type-null. "" Do nothing WHEN zif_abapgit_ajson=>node_type-boolean. "" TODO: check type ? = boolc( is_node-value = 'true' ). WHEN zif_abapgit_ajson=>node_type-number. "" TODO: check type ? = is_node-value. WHEN zif_abapgit_ajson=>node_type-string. "" TODO: check type ? IF is_node_type-type_kind = 'D' AND is_node-value IS NOT INITIAL. = to_date( is_node-value ). ELSEIF is_node_type-type_kind = 'P' AND is_node-value IS NOT INITIAL. = to_timestamp( is_node-value ). ELSE. = is_node-value. ENDIF. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected JSON type [{ is_node-type }]| ). ENDCASE. ENDMETHOD. METHOD to_date. DATA lv_y TYPE c LENGTH 4. DATA lv_m TYPE c LENGTH 2. DATA lv_d TYPE c LENGTH 2. FIND FIRST OCCURRENCE OF REGEX '^(\\d{4})-(\\d{2})-(\\d{2})(T|$)' IN iv_value SUBMATCHES lv_y lv_m lv_d. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Unexpected date format' ). ENDIF. CONCATENATE lv_y lv_m lv_d INTO rv_result. ENDMETHOD. METHOD to_timestamp. CONSTANTS lc_utc TYPE c LENGTH 6 VALUE 'UTC'. CONSTANTS lc_regex_ts_with_hour TYPE string VALUE `^(\\d{4})-(\\d{2})-(\\d{2})(T)(\\d{2}):(\\d{2}):(\\d{2})(\\+)(\\d{2}):(\\d{2})`. CONSTANTS lc_regex_ts_utc TYPE string VALUE `^(\\d{4})-(\\d{2})-(\\d{2})(T)(\\d{2}):(\\d{2}):(\\d{2})(Z|$)`. DATA: BEGIN OF ls_timestamp, year TYPE c LENGTH 4, month TYPE c LENGTH 2, day TYPE c LENGTH 2, t TYPE c LENGTH 1, hour TYPE c LENGTH 2, minute TYPE c LENGTH 2, second TYPE c LENGTH 2, local_sign TYPE c LENGTH 1, local_hour TYPE c LENGTH 2, local_minute TYPE c LENGTH 2, END OF ls_timestamp. DATA lv_date TYPE d. DATA lv_time TYPE t. DATA lv_seconds_conv TYPE i. DATA lv_timestamp TYPE timestampl. FIND FIRST OCCURRENCE OF REGEX lc_regex_ts_with_hour IN iv_value SUBMATCHES ls_timestamp-year ls_timestamp-month ls_timestamp-day ls_timestamp-t ls_timestamp-hour ls_timestamp-minute ls_timestamp-second ls_timestamp-local_sign ls_timestamp-local_hour ls_timestamp-local_minute. IF sy-subrc = 0. lv_seconds_conv = ( ls_timestamp-local_hour * 3600 ) + ( ls_timestamp-local_minute * 60 ). ELSE. FIND FIRST OCCURRENCE OF REGEX lc_regex_ts_utc IN iv_value SUBMATCHES ls_timestamp-year ls_timestamp-month ls_timestamp-day ls_timestamp-t ls_timestamp-hour ls_timestamp-minute ls_timestamp-second. IF sy-subrc <> 0. zcx_abapgit_ajson_error=>raise( 'Unexpected timestamp format' ). ENDIF. ENDIF. CONCATENATE ls_timestamp-year ls_timestamp-month ls_timestamp-day INTO lv_date. CONCATENATE ls_timestamp-hour ls_timestamp-minute ls_timestamp-second INTO lv_time. CONVERT DATE lv_date TIME lv_time INTO TIME STAMP lv_timestamp TIME ZONE lc_utc. TRY. CASE ls_timestamp-local_sign. WHEN '-'. lv_timestamp = cl_abap_tstmp=>add( tstmp = lv_timestamp secs = lv_seconds_conv ). WHEN '+'. lv_timestamp = cl_abap_tstmp=>subtractsecs( tstmp = lv_timestamp secs = lv_seconds_conv ). ENDCASE. CATCH cx_parameter_invalid_range cx_parameter_invalid_type. zcx_abapgit_ajson_error=>raise( 'Unexpected error calculating timestamp' ). ENDTRY. cl_abap_tstmp=>move( EXPORTING tstmp_src = lv_timestamp IMPORTING tstmp_tgt = rv_result ). ENDMETHOD. ENDCLASS. ********************************************************************** * ABAP_TO_JSON ********************************************************************** CLASS lcl_abap_to_json DEFINITION FINAL. PUBLIC SECTION. CLASS-METHODS convert IMPORTING iv_data TYPE any is_prefix TYPE zif_abapgit_ajson=>ty_path_name OPTIONAL iv_array_index TYPE i DEFAULT 0 ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL iv_keep_item_order TYPE abap_bool DEFAULT abap_false iv_format_datetime TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rt_nodes) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. CLASS-METHODS insert_with_type IMPORTING iv_data TYPE any iv_type TYPE string is_prefix TYPE zif_abapgit_ajson=>ty_path_name OPTIONAL iv_array_index TYPE i DEFAULT 0 ii_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping OPTIONAL iv_keep_item_order TYPE abap_bool DEFAULT abap_false iv_format_datetime TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rt_nodes) TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. CLASS-METHODS format_date IMPORTING iv_date TYPE d RETURNING VALUE(rv_str) TYPE string. CLASS-METHODS format_time IMPORTING iv_time TYPE t RETURNING VALUE(rv_str) TYPE string. CLASS-METHODS format_timestamp IMPORTING iv_ts TYPE timestamp RETURNING VALUE(rv_str) TYPE string. CLASS-METHODS class_constructor. PRIVATE SECTION. CLASS-DATA gv_ajson_absolute_type_name TYPE string. DATA mi_custom_mapping TYPE REF TO zif_abapgit_ajson_mapping. DATA mv_keep_item_order TYPE abap_bool. DATA mv_format_datetime TYPE abap_bool. METHODS convert_any IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_ajson IMPORTING io_json TYPE REF TO zif_abapgit_ajson is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_value IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_ref IMPORTING iv_data TYPE any is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS convert_struc IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt cs_root TYPE zif_abapgit_ajson=>ty_node OPTIONAL RAISING zcx_abapgit_ajson_error. METHODS convert_table IMPORTING iv_data TYPE any io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. METHODS insert_value_with_type IMPORTING iv_data TYPE any iv_type TYPE string io_type TYPE REF TO cl_abap_typedescr is_prefix TYPE zif_abapgit_ajson=>ty_path_name iv_index TYPE i DEFAULT 0 iv_item_order TYPE i DEFAULT 0 CHANGING ct_nodes TYPE zif_abapgit_ajson=>ty_nodes_tt RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_abap_to_json IMPLEMENTATION. METHOD class_constructor. DATA lo_dummy TYPE REF TO zcl_abapgit_ajson. DATA lo_type TYPE REF TO cl_abap_refdescr. lo_type ?= cl_abap_typedescr=>describe_by_data( lo_dummy ). gv_ajson_absolute_type_name = lo_type->get_referenced_type( )->absolute_name. ENDMETHOD. METHOD convert. DATA lo_type TYPE REF TO cl_abap_typedescr. DATA lo_converter TYPE REF TO lcl_abap_to_json. lo_type = cl_abap_typedescr=>describe_by_data( iv_data ). CREATE OBJECT lo_converter. lo_converter->mi_custom_mapping = ii_custom_mapping. lo_converter->mv_keep_item_order = iv_keep_item_order. lo_converter->mv_format_datetime = iv_format_datetime. lo_converter->convert_any( EXPORTING iv_data = iv_data io_type = lo_type is_prefix = is_prefix iv_index = iv_array_index CHANGING ct_nodes = rt_nodes ). ENDMETHOD. METHOD convert_any. CASE io_type->kind. WHEN cl_abap_typedescr=>kind_elem. convert_value( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN cl_abap_typedescr=>kind_struct. convert_struc( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN cl_abap_typedescr=>kind_table. convert_table( EXPORTING iv_data = iv_data io_type = io_type is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). WHEN OTHERS. IF io_type->type_kind = cl_abap_typedescr=>typekind_dref OR iv_data IS INITIAL. "" Convert data references and initial references to other types (like ref to class or interface) "" Initial references will result in ""null"" convert_ref( EXPORTING iv_data = iv_data is_prefix = is_prefix iv_index = iv_index iv_item_order = iv_item_order CHANGING ct_nodes = ct_nodes ). ELSEIF io_type->type_kind = cl_abap_typedescr=>typekind_oref AND cl_abap_typedescr=>describe_by_object_ref( iv_data )->absolute_name = gv_ajson_absolute_type_name. convert_ajson( EXPORTING io_json = iv_data is_prefix = is_prefix iv_index = iv_index CHANGING ct_nodes = ct_nodes ). ELSE. zcx_abapgit_ajson_error=>raise( |Unsupported type [{ io_type->type_kind }] @{ is_prefix-path && is_prefix-name }| ). ENDIF. ENDCASE. ENDMETHOD. METHOD convert_ajson. FIELD-SYMBOLS LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE LINE OF ct_nodes. IF io_json IS NOT BOUND. RETURN. ENDIF. LOOP AT io_json->mt_json_tree ASSIGNING . APPEND TO ct_nodes ASSIGNING . IF -path IS INITIAL AND -name IS INITIAL. "" root node -path = is_prefix-path. -name = is_prefix-name. -index = iv_index. ELSE. -path = is_prefix-path && is_prefix-name && -path. ENDIF. ENDLOOP. ENDMETHOD. METHOD format_date. IF iv_date IS NOT INITIAL. rv_str = iv_date+0(4) && '-' && iv_date+4(2) && '-' && iv_date+6(2). ENDIF. ENDMETHOD. METHOD format_time. IF iv_time IS NOT INITIAL. rv_str = iv_time+0(2) && ':' && iv_time+2(2) && ':' && iv_time+4(2). ENDIF. ENDMETHOD. METHOD format_timestamp. CONSTANTS lc_utc TYPE c LENGTH 6 VALUE 'UTC'. DATA lv_date TYPE d. DATA lv_time TYPE t. IF iv_ts IS INITIAL. "" The zero value is January 1, year 1, 00:00:00.000000000 UTC. lv_date = '00010101'. ELSE. CONVERT TIME STAMP iv_ts TIME ZONE lc_utc INTO DATE lv_date TIME lv_time. ENDIF. rv_str = lv_date+0(4) && '-' && lv_date+4(2) && '-' && lv_date+6(2) && 'T' && lv_time+0(2) && '-' && lv_time+2(2) && '-' && lv_time+4(2) && 'Z'. ENDMETHOD. METHOD convert_value. DATA ls_node LIKE LINE OF ct_nodes. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. IF io_type->absolute_name = '\\TYPE-POOL=ABAP\\TYPE=ABAP_BOOL' OR io_type->absolute_name = '\\TYPE=ABAP_BOOLEAN' OR io_type->absolute_name = '\\TYPE=XSDBOOLEAN' OR io_type->absolute_name = '\\TYPE=FLAG' OR io_type->absolute_name = '\\TYPE=XFELD'. ls_node-type = zif_abapgit_ajson=>node_type-boolean. IF iv_data IS NOT INITIAL. ls_node-value = 'true'. ELSE. ls_node-value = 'false'. ENDIF. ELSEIF io_type->absolute_name = '\\TYPE=TIMESTAMP'. IF mv_format_datetime = abap_true. ls_node-type = zif_abapgit_ajson=>node_type-string. ls_node-value = format_timestamp( iv_data ). ELSE. ls_node-type = zif_abapgit_ajson=>node_type-number. ls_node-value = |{ iv_data }|. ENDIF. ELSEIF io_type->type_kind CO 'CNgXy'. "" Char like, xstring ls_node-type = zif_abapgit_ajson=>node_type-string. ls_node-value = |{ iv_data }|. ELSEIF io_type->type_kind = 'D'. "" Date ls_node-type = zif_abapgit_ajson=>node_type-string. IF mv_format_datetime = abap_true. ls_node-value = format_date( iv_data ). ELSE. ls_node-value = |{ iv_data }|. ENDIF. ELSEIF io_type->type_kind = 'T'. "" Time ls_node-type = zif_abapgit_ajson=>node_type-string. IF mv_format_datetime = abap_true. ls_node-value = format_time( iv_data ). ELSE. ls_node-value = |{ iv_data }|. ENDIF. ELSEIF io_type->type_kind CO 'bsI8aeFP'. "" Numeric ls_node-type = zif_abapgit_ajson=>node_type-number. ls_node-value = |{ iv_data }|. ELSE. zcx_abapgit_ajson_error=>raise( |Unexpected elementary type [{ io_type->type_kind }] @{ is_prefix-path && is_prefix-name }| ). ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. METHOD convert_ref. DATA ls_node LIKE LINE OF ct_nodes. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. IF iv_data IS INITIAL. ls_node-type = zif_abapgit_ajson=>node_type-null. ls_node-value = 'null'. ELSE. "" TODO support data references zcx_abapgit_ajson_error=>raise( |Unexpected reference @{ is_prefix-path && is_prefix-name }| ). ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. METHOD convert_struc. DATA lo_struc TYPE REF TO cl_abap_structdescr. DATA lt_comps TYPE cl_abap_structdescr=>component_table. DATA ls_next_prefix LIKE is_prefix. DATA lv_item_order TYPE i. DATA ls_root LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE ls_root. FIELD-SYMBOLS LIKE LINE OF lt_comps. FIELD-SYMBOLS TYPE any. "" Object root IF cs_root IS SUPPLIED. "" call for include structure ASSIGN cs_root TO . ELSE. "" First call ls_root-path = is_prefix-path. ls_root-name = is_prefix-name. ls_root-type = zif_abapgit_ajson=>node_type-object. ls_root-index = iv_index. IF mi_custom_mapping IS BOUND. ls_root-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_root-name IS INITIAL. ls_root-name = is_prefix-name. ENDIF. ls_root-order = iv_item_order. APPEND ls_root TO ct_nodes ASSIGNING . ENDIF. "" Object attributes lo_struc ?= io_type. lt_comps = lo_struc->get_components( ). "" get_components is potentially much slower than lo_struc->components "" but ! we still need it to identify booleans "" and rtti seems to cache type descriptions really well (https://github.com/sbcgua/benchmarks.git) "" the structures will be repeated in real life ls_next_prefix-path = is_prefix-path && -name && '/'. LOOP AT lt_comps ASSIGNING . IF -as_include = abap_true. convert_struc( EXPORTING iv_data = iv_data io_type = -type is_prefix = is_prefix CHANGING cs_root = ct_nodes = ct_nodes ). ELSE. -children = -children + 1. ls_next_prefix-name = to_lower( -name ). ASSIGN COMPONENT -name OF STRUCTURE iv_data TO . ASSERT sy-subrc = 0. IF mv_keep_item_order = abap_true. lv_item_order = -children. ENDIF. convert_any( EXPORTING iv_data = io_type = -type is_prefix = ls_next_prefix iv_item_order = lv_item_order CHANGING ct_nodes = ct_nodes ). ENDIF. ENDLOOP. ENDMETHOD. METHOD convert_table. DATA lo_table TYPE REF TO cl_abap_tabledescr. DATA lo_ltype TYPE REF TO cl_abap_typedescr. DATA ls_next_prefix LIKE is_prefix. DATA lv_tabix TYPE sy-tabix. DATA ls_root LIKE LINE OF ct_nodes. FIELD-SYMBOLS LIKE ls_root. FIELD-SYMBOLS TYPE ANY TABLE. FIELD-SYMBOLS TYPE any. "" Array root ls_root-path = is_prefix-path. ls_root-name = is_prefix-name. ls_root-type = zif_abapgit_ajson=>node_type-array. ls_root-index = iv_index. ls_root-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_root-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_root-name IS INITIAL. ls_root-name = is_prefix-name. ENDIF. APPEND ls_root TO ct_nodes ASSIGNING . "" Array items lo_table ?= io_type. lo_ltype = lo_table->get_table_line_type( ). ls_next_prefix-path = is_prefix-path && -name && '/'. ASSIGN iv_data TO . lv_tabix = 1. LOOP AT ASSIGNING . ls_next_prefix-name = to_lower( |{ lv_tabix }| ). convert_any( EXPORTING iv_data = io_type = lo_ltype is_prefix = ls_next_prefix iv_index = -children + 1 CHANGING ct_nodes = ct_nodes ). -children = -children + 1. lv_tabix = lv_tabix + 1. ENDLOOP. ENDMETHOD. METHOD insert_with_type. DATA lo_type TYPE REF TO cl_abap_typedescr. DATA lo_converter TYPE REF TO lcl_abap_to_json. lo_type = cl_abap_typedescr=>describe_by_data( iv_data ). CREATE OBJECT lo_converter. lo_converter->mi_custom_mapping = ii_custom_mapping. lo_converter->mv_keep_item_order = iv_keep_item_order. lo_converter->mv_format_datetime = iv_format_datetime. lo_converter->insert_value_with_type( EXPORTING iv_data = iv_data iv_type = iv_type io_type = lo_type is_prefix = is_prefix iv_index = iv_array_index CHANGING ct_nodes = rt_nodes ). ENDMETHOD. METHOD insert_value_with_type. DATA lv_prefix TYPE string. DATA ls_node LIKE LINE OF ct_nodes. lv_prefix = is_prefix-path && is_prefix-name. IF io_type->type_kind CO 'CNgXyDT'. "" Char like, date/time, xstring IF iv_type = zif_abapgit_ajson=>node_type-boolean AND iv_data <> 'true' AND iv_data <> 'false'. zcx_abapgit_ajson_error=>raise( |Unexpected boolean value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type = zif_abapgit_ajson=>node_type-null AND iv_data IS NOT INITIAL. zcx_abapgit_ajson_error=>raise( |Unexpected null value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type = zif_abapgit_ajson=>node_type-number AND iv_data CN '0123456789. E+-'. zcx_abapgit_ajson_error=>raise( |Unexpected numeric value [{ iv_data }] @{ lv_prefix }| ). ELSEIF iv_type <> zif_abapgit_ajson=>node_type-string AND iv_type <> zif_abapgit_ajson=>node_type-boolean AND iv_type <> zif_abapgit_ajson=>node_type-null AND iv_type <> zif_abapgit_ajson=>node_type-number. zcx_abapgit_ajson_error=>raise( |Unexpected type for value [{ iv_type },{ iv_data }] @{ lv_prefix }| ). ENDIF. ELSEIF io_type->type_kind CO 'bsI8PaeF'. "" Numeric IF iv_type <> zif_abapgit_ajson=>node_type-number. zcx_abapgit_ajson_error=>raise( |Unexpected value for numeric [{ iv_data }] @{ lv_prefix }| ). ENDIF. ELSE. zcx_abapgit_ajson_error=>raise( |Unexpected type [{ io_type->type_kind }] @{ lv_prefix }| ). ENDIF. ls_node-path = is_prefix-path. ls_node-name = is_prefix-name. ls_node-index = iv_index. ls_node-value = iv_data. ls_node-type = iv_type. ls_node-order = iv_item_order. IF mi_custom_mapping IS BOUND. ls_node-name = mi_custom_mapping->to_json( iv_path = is_prefix-path iv_name = is_prefix-name ). ENDIF. IF ls_node-name IS INITIAL. ls_node-name = is_prefix-name. ENDIF. APPEND ls_node TO ct_nodes. ENDMETHOD. ENDCLASS. ********************************************************************** * FILTER RUNNER ********************************************************************** CLASS lcl_filter_runner DEFINITION FINAL. PUBLIC SECTION. METHODS run IMPORTING ii_filter TYPE REF TO zif_abapgit_ajson_filter it_source_tree TYPE zif_abapgit_ajson=>ty_nodes_ts CHANGING ct_dest_tree TYPE zif_abapgit_ajson=>ty_nodes_ts RAISING zcx_abapgit_ajson_error. PRIVATE SECTION. DATA mi_filter TYPE REF TO zif_abapgit_ajson_filter. DATA mr_source_tree TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. DATA mr_dest_tree TYPE REF TO zif_abapgit_ajson=>ty_nodes_ts. METHODS walk IMPORTING iv_path TYPE string CHANGING cs_parent TYPE zif_abapgit_ajson=>ty_node OPTIONAL RAISING zcx_abapgit_ajson_error. ENDCLASS. CLASS lcl_filter_runner IMPLEMENTATION. METHOD run. ASSERT ii_filter IS BOUND. mi_filter = ii_filter. CLEAR ct_dest_tree. GET REFERENCE OF it_source_tree INTO mr_source_tree. GET REFERENCE OF ct_dest_tree INTO mr_dest_tree. walk( iv_path = '' ). ENDMETHOD. METHOD walk. DATA ls_node TYPE zif_abapgit_ajson=>ty_node. LOOP AT mr_source_tree->* INTO ls_node WHERE path = iv_path. CASE ls_node-type. WHEN zif_abapgit_ajson=>node_type-boolean OR zif_abapgit_ajson=>node_type-null OR zif_abapgit_ajson=>node_type-number OR zif_abapgit_ajson=>node_type-string. IF mi_filter->keep_node( ls_node ) = abap_false. CONTINUE. ENDIF. WHEN zif_abapgit_ajson=>node_type-array OR zif_abapgit_ajson=>node_type-object. IF mi_filter->keep_node( is_node = ls_node iv_visit = zif_abapgit_ajson_filter=>visit_type-open ) = abap_false. CONTINUE. ENDIF. "" Intentionally clear AFTER ""open"" CLEAR ls_node-children. walk( EXPORTING iv_path = iv_path && ls_node-name && `/` CHANGING cs_parent = ls_node ). IF mi_filter->keep_node( is_node = ls_node iv_visit = zif_abapgit_ajson_filter=>visit_type-close ) = abap_false. CONTINUE. ENDIF. WHEN OTHERS. zcx_abapgit_ajson_error=>raise( |Unexpected node type { ls_node-type }| ). ENDCASE. IF cs_parent IS SUPPLIED. cs_parent-children = cs_parent-children + 1. IF cs_parent-type = zif_abapgit_ajson=>node_type-array. ls_node-name = |{ cs_parent-children }|. ls_node-index = cs_parent-children. ENDIF. ENDIF. INSERT ls_node INTO TABLE mr_dest_tree->*. ENDLOOP. ENDMETHOD. ENDCLASS. ",13202,True,2825.2547611896953,median "// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include #include ""gtest/gtest.h"" #include ""orttraining/core/optimizer/gist_encode_decode.h"" #include ""test/providers/provider_test_utils.h"" #include ""core/providers/cpu/cpu_execution_provider.h"" #include ""core/session/environment.h"" #include ""orttraining/models/runner/training_runner.h"" #include ""orttraining/training_ops/cpu/controlflow/event_pool.h"" // TODO: move with PipelineBatchPlanner #ifdef USE_CUDA #include ""bert_toy_fetches.h"" #include ""core/providers/cuda/cuda_execution_provider.h"" #endif using namespace onnxruntime::logging; using namespace onnxruntime::training; using namespace google::protobuf::util; namespace onnxruntime { namespace test { namespace { constexpr auto ORIGINAL_MODEL_PATH = ORT_TSTR(""testdata/test_training_model.onnx""); constexpr auto BACKWARD_MODEL_PATH = ORT_TSTR(""testdata/temp_backward_model.onnx""); std::unordered_set GetModelOutputNames(const InferenceSession& session) { const auto outputs_result = session.GetModelOutputs(); ORT_ENFORCE(outputs_result.first.IsOK(), ""Failed to get model outputs: "", outputs_result.first.ErrorMessage()); std::unordered_set output_names{}; for (const auto* output : *outputs_result.second) { output_names.insert(output->Name()); } return output_names; } } // namespace static TrainingSession::TrainingConfiguration MakeBasicTrainingConfig() { TrainingSession::TrainingConfiguration config{}; config.model_with_training_graph_path = BACKWARD_MODEL_PATH; config.loss_function_config = TrainingSession::TrainingConfiguration::LossFunctionConfiguration{}; config.loss_function_config.value().loss_function_info = LossFunctionInfo(OpDef(""MeanSquaredError""), ""loss"", {""predictions"", ""labels""}); return config; } static Status BuildBackPropGraph( const PathString& forward_model_file, const TrainingSession::TrainingConfiguration& config, PathString& backward_model_file) { std::unique_ptr env; ORT_RETURN_IF_ERROR(Environment::Create(nullptr, env)); SessionOptions so{}; TrainingSession training_session{so, *env}; std::cout << ""Loading source model file = "" << ToMBString(forward_model_file) << ""\\n""; ORT_RETURN_IF_ERROR(training_session.Load(forward_model_file)); TrainingSession::TrainingConfigurationResult config_result{}; ORT_RETURN_IF_ERROR(training_session.ConfigureForTraining(config, config_result)); backward_model_file = config.model_with_training_graph_path.value(); return Status::OK(); } /** * Run a training session for this model for 1 epoch, using batch size of 1 and synthetic input data. * @param so - SessionOptions for this run. * @param backprop_model_file - Mocel file to be run. This should already contain loss function and backward prop nodes. * @return TrainingSession for this run. */ static std::unique_ptr RunTrainingSessionWithChecks( const SessionOptions& so, const PathString& backprop_model_file) { std::unique_ptr env; EXPECT_TRUE(Environment::Create(nullptr, env).IsOK()); std::unique_ptr training_session = onnxruntime::make_unique(so, *env); EXPECT_TRUE(training_session->Load(backprop_model_file).IsOK()); std::pair res = training_session->GetModelMetadata(); EXPECT_TRUE(res.first.IsOK()); EXPECT_TRUE(res.second != nullptr); auto model_metadata = res.second; std::cout << ""Loaded "" << model_metadata->graph_name << '\\n'; EXPECT_TRUE(training_session->Initialize().IsOK()); std::vector gradient_fetches; RunOptions run_options; run_options.run_log_verbosity_level = so.session_log_verbosity_level; run_options.run_tag = so.session_logid; // Create dummy feeds std::vector image_dims = {1, 784}; std::vector label_dims = {1, 10}; std::vector image_value(784, 1); std::vector label_value(10, 1); MLValue imageMLValue; TrainingUtil::CreateCpuMLValue(image_dims, image_value, &imageMLValue); MLValue labelMLValue; TrainingUtil::CreateCpuMLValue(label_dims, label_value, &labelMLValue); auto fw_feeds = std::make_pair, std::vector>({""X"", ""labels""}, {imageMLValue, labelMLValue}); auto output_names_include_gradients = GetModelOutputNames(*training_session); std::vector training_output_names(output_names_include_gradients.begin(), output_names_include_gradients.end()); auto start_time = std::chrono::high_resolution_clock::now(); EXPECT_TRUE(training_session->Run(run_options, fw_feeds.first, fw_feeds.second, training_output_names, &gradient_fetches).IsOK()); auto end_time = std::chrono::high_resolution_clock::now(); auto elapsed = TimeDiffMicroSeconds(start_time, end_time); std::cout << ""Training session run completed in "" << elapsed << "" microseconds.\\n""; return training_session; } TEST(GradientGraphBuilderTest, BuildGradientGraphTest) { const auto config = MakeBasicTrainingConfig(); PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(ORIGINAL_MODEL_PATH, config, backprop_model_file)); std::shared_ptr pModel; ASSERT_STATUS_OK(Model::Load(backprop_model_file, pModel, nullptr, DefaultLoggingManager().DefaultLogger())); Graph& graph = pModel->MainGraph(); EXPECT_FALSE(graph.GraphResolveNeeded()); EXPECT_TRUE(graph.NumberOfNodes() > 0); EXPECT_TRUE(graph.MaxNodeIndex() > 0); std::cout << ""Graph input names = [\\n""; for (const NodeArg* p_node_arg : graph.GetInputs()) { std::cout << '\\t' << p_node_arg->Name() << '\\n'; } std::cout << ""]\\n""; std::cout << ""Graph output names = [\\n""; for (const NodeArg* p_node_arg : graph.GetOutputs()) { std::cout << '\\t' << p_node_arg->Name() << '\\n'; } std::cout << ""]\\n""; for (Node& node : graph.Nodes()) { const NodeIndex node_index = node.Index(); const std::string& node_name = node.Name(); const std::string& op_type = node.OpType(); std::cout << ""Operation node:"" << "" Index="" << node_index << (node.NodeType() == Node::Type::Fused ? ""-(FUSED)"" : """") << "" OpType="" << op_type << "" Name="" << node_name << '\\n'; } } TEST(GradientGraphBuilderTest, TrainingSession_Basic) { const auto config = MakeBasicTrainingConfig(); PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(ORIGINAL_MODEL_PATH, config, backprop_model_file)); SessionOptions so{}; RunTrainingSessionWithChecks(so, backprop_model_file); } TEST(GradientGraphBuilderTest, TrainingSession_WithGist) { auto config = MakeBasicTrainingConfig(); config.gist_config = TrainingSession::TrainingConfiguration::GistConfiguration{}; PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(ORIGINAL_MODEL_PATH, config, backprop_model_file)); std::cout << ""Loading model file = "" << ToMBString(backprop_model_file) << ""\\n""; std::shared_ptr p_model; ASSERT_STATUS_OK(onnxruntime::Model::Load(backprop_model_file, p_model, nullptr, DefaultLoggingManager().DefaultLogger())); const Graph& graph = p_model->MainGraph(); bool found_encoder = false; bool found_decoder = false; for (auto& node : graph.Nodes()) { const std::string& node_name = node.Name(); std::cout << ""Node name='"" << node_name << ""' op_type="" << node.OpType() << ""\\n""; if (node_name.find(onnxruntime::GistEncodeDecode::GIST_ENCODER_NODE_NAME_BASE) != std::string::npos) { found_encoder = true; std::cout << ""Found encoder node "" << node_name << ""\\n""; } else if (node_name.find(onnxruntime::GistEncodeDecode::GIST_DECODER_NODE_NAME_BASE) != std::string::npos) { found_decoder = true; std::cout << ""Found decoder node "" << node_name << ""\\n""; } } ASSERT_TRUE(found_encoder); ASSERT_TRUE(found_decoder); SessionOptions so{}; RunTrainingSessionWithChecks(so, backprop_model_file); } TEST(GradientGraphBuilderTest, TrainingSession_WithLogging) { const auto& log_manager = DefaultLoggingManager(); const auto& default_logger = log_manager.DefaultLogger(); log_manager.SetDefaultLoggerSeverity(Severity::kINFO); EXPECT_TRUE(default_logger.OutputIsEnabled(Severity::kERROR, ::onnxruntime::logging::DataType::USER)) << ""ERROR level logging enabled.""; EXPECT_TRUE(default_logger.OutputIsEnabled(Severity::kWARNING, ::onnxruntime::logging::DataType::USER)) << ""WARNING level logging enabled.""; EXPECT_TRUE(default_logger.OutputIsEnabled(Severity::kINFO, ::onnxruntime::logging::DataType::USER)) << ""INFO level logging enabled.""; const auto config = MakeBasicTrainingConfig(); PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(ORIGINAL_MODEL_PATH, config, backprop_model_file)); SessionOptions so; so.session_logid = ""training_session_with_logging""; so.session_log_verbosity_level = 1; // 1 == detailed logging std::unique_ptr training_session = RunTrainingSessionWithChecks(so, backprop_model_file); EXPECT_TRUE(default_logger.OutputIsEnabled(Severity::kERROR, ::onnxruntime::logging::DataType::USER)) << ""ERROR level logging still enabled.""; EXPECT_TRUE(default_logger.OutputIsEnabled(Severity::kWARNING, ::onnxruntime::logging::DataType::USER)) << ""WARNING level logging still enabled.""; EXPECT_TRUE(default_logger.OutputIsEnabled(Severity::kINFO, ::onnxruntime::logging::DataType::USER)) << ""INFO level logging still enabled.""; std::string profile_file = training_session->EndProfiling(); log_manager.SetDefaultLoggerSeverity(Severity::kWARNING); EXPECT_EQ(profile_file, std::string()) << ""There should be no profile output file.""; } TEST(GradientGraphBuilderTest, TrainingSession_WithProfiler) { const auto config = MakeBasicTrainingConfig(); PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(ORIGINAL_MODEL_PATH, config, backprop_model_file)); SessionOptions so; so.enable_profiling = true; so.profile_file_prefix = ORT_TSTR(""onnx_training_profiler_test""); std::unique_ptr training_session = RunTrainingSessionWithChecks(so, backprop_model_file); std::string profile_file = training_session->EndProfiling(); std::cout << ""Profile output file = "" << profile_file << '\\n'; std::ifstream profile(profile_file); ASSERT_TRUE(profile); std::vector core_trace_fields = {""pid"", ""dur"", ""ts"", ""ph"", ""X"", ""name"", ""args""}; std::vector fiddle_profile_data_fields = {""dur"", ""activation_size"", ""parameter_size"", ""output_size""}; int count = 0; std::string line; while (std::getline(profile, line)) { if (count == 0) { ASSERT_TRUE(line.find('[') != std::string::npos) << ""Missing opening array marker in first trace record: "" << line; // Opening array marker found. } else if (line.find(']') != std::string::npos) { // Closing array marker found. break; } else if (count >= 1) { if (count == 1) { auto s = ""model_loading_uri""; ASSERT_TRUE(line.find(s) != std::string::npos) << ""Missing field '"" << s << ""' in trace record: "" << line; } // Check we have the core fields in each trace record. for (auto& s : core_trace_fields) { ASSERT_TRUE(line.find(s) != std::string::npos) << ""Missing core trace field '"" << s << ""' in trace record: "" << line; } // Check we have the data profile fields output for each kernel operation. if (line.find(""_kernel_time"") != std::string::npos) { for (auto& s : fiddle_profile_data_fields) { ASSERT_TRUE(line.find(s) != std::string::npos) << ""Missing data profile field '"" << s << ""' in trace record: "" << line; } } } count++; } ASSERT_TRUE(count > 1); } #ifdef USE_CUDA static void RunBertTrainingWithChecks( const SessionOptions& so, const PathString& backprop_model_file) { std::unique_ptr env; EXPECT_TRUE(Environment::Create(nullptr, env).IsOK()); std::unique_ptr training_session = onnxruntime::make_unique(so, *env); EXPECT_TRUE(training_session->Load(backprop_model_file).IsOK()); std::pair res = training_session->GetModelMetadata(); EXPECT_TRUE(res.first.IsOK()); ASSERT_TRUE(res.second != nullptr); auto model_metadata = res.second; std::cout << ""Loaded "" << model_metadata->graph_name << '\\n'; CUDAExecutionProviderInfo xp_info; ASSERT_STATUS_OK(training_session->RegisterExecutionProvider(onnxruntime::make_unique(xp_info))); ASSERT_STATUS_OK(training_session->Initialize()); RunOptions run_options; run_options.run_log_verbosity_level = so.session_log_verbosity_level; run_options.run_tag = so.session_logid; // Creating feeds int batch_size = 13; int max_seq_len_in_batch = 7; std::vector feed_names = { ""input_ids"", ""token_type_ids"", ""input_mask"", ""masked_lm_ids"", ""next_sentence_labels"", ""masked_lm_positions"", ""masked_lm_weights"", }; std::vector tensor_shapes = { {batch_size, max_seq_len_in_batch}, {batch_size, max_seq_len_in_batch}, {batch_size, max_seq_len_in_batch}, {batch_size, max_seq_len_in_batch}, {batch_size}, {batch_size, max_seq_len_in_batch}, {batch_size, max_seq_len_in_batch}}; std::vector> tensor_values = { /*input_ids*/ {49, 97, 53, 5, 33, 65, 62, 51, 38, 61, 45, 74, 27, 64, 17, 36, 17, 96, 12, 79, 32, 68, 90, 77, 18, 39, 12, 93, 9, 87, 42, 60, 71, 12, 45, 55, 40, 78, 81, 26, 70, 61, 56, 66, 33, 7, 70, 1, 11, 92, 51, 90, 85, 80, 0, 78, 63, 42, 31, 93, 41, 90, 8, 24, 72, 28, 30, 18, 69, 57, 11, 10, 40, 65, 62, 13, 38, 70, 37, 90, 15, 70, 42, 69, 26, 77, 70, 75, 36, 56, 11}, /*token_type_ids*/ {12, 13, 1, 8, 15, 12, 9, 15, 11, 6, 4, 9, 4, 3, 8, 4, 9, 3, 2, 10, 15, 3, 11, 13, 10, 6, 15, 14, 8, 1, 0, 2, 12, 0, 15, 10, 7, 10, 2, 6, 7, 7, 4, 14, 2, 2, 10, 15, 3, 9, 9, 3, 10, 6, 9, 14, 2, 12, 10, 7, 9, 5, 6, 5, 1, 8, 15, 2, 2, 4, 4, 1, 2, 12, 8, 7, 6, 13, 8, 14, 15, 11, 2, 10, 3, 15, 10, 6, 7, 0, 8}, /*input_mask*/ {1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1}, /*masked_lm_ids*/ {1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 2, 0, 2, 0, 1, 0, 0, 2, 1, 2, 2, 2, 0, 1, 0, 2, 0, 2, 1, 1, 2, 0, 1, 1, 1, 2, 2, 0, 2, 1, 1, 2, 1, 0, 2, 0, 0, 2, 1, 2, 2, 2, 0, 2, 1, 1, 0, 2, 1, 2, 0, 0, 2, 0, 0, 0, 2, 1, 0, 0, 1, 2, 1, 0, 1, 2, 1, 2, 0, 2, 1, 2, 0, 2, 2, 2, 1, 1, 0, 2, 1}, /*next_sentence_labels*/ {1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0}, /*masked_lm_positions*/ {0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6}}; std::vector masked_lm_weights(13 * 7, 1.0f); std::vector feeds(feed_names.size()); for (size_t i = 0; i < 6; ++i) { TrainingUtil::CreateCpuMLValue(tensor_shapes[i].GetDims(), tensor_values[i], &feeds[i]); } TrainingUtil::CreateCpuMLValue(tensor_shapes[6].GetDims(), masked_lm_weights, &feeds[6]); auto output_names_include_gradients = GetModelOutputNames(*training_session); std::vector fetch_names(output_names_include_gradients.begin(), output_names_include_gradients.end()); std::vector fetches; EXPECT_TRUE(training_session->Run(run_options, feed_names, feeds, fetch_names, &fetches).IsOK()); for (size_t i = 0; i < fetch_names.size(); ++i) { if (!fetches[i].IsAllocated() || !!fetches[i].IsTensor()) continue; const Tensor& tensor = fetches[i].Get(); if (DataTypeImpl::GetType() != tensor.DataType()) { continue; } const std::string& name = fetch_names[i]; if (BERT_TOY_FETCHES.find(name) == BERT_TOY_FETCHES.end()) { continue; } auto gradient_ref = BERT_TOY_FETCHES.at(name); EXPECT_TRUE(static_cast(tensor.Shape().Size()) == gradient_ref.size()); float max_diff = 0; float max_percent_diff = 0; const float* data = tensor.template Data(); for (size_t idx = 0; idx < gradient_ref.size(); ++idx) { float diff = std::fabs(static_cast(gradient_ref[idx]) - data[idx]); max_diff = std::fmax(max_diff, diff); max_percent_diff = std::fmax(max_percent_diff, diff / data[idx]); } EXPECT_TRUE(max_diff < 1e-5) << name << "" is incorrect: max_diff is "" << max_diff; if (max_diff > 1e-10) { EXPECT_TRUE(max_percent_diff < 0.01f) << name << "" is incorrect: max_percent_diff is "" << max_percent_diff; } } } #endif TEST(GradientGraphBuilderTest, TrainingSession_BertToy) { const auto model_path = ORT_TSTR(""testdata/bert_toy_optimized.onnx""); TrainingSession::TrainingConfiguration config{}; config.model_with_training_graph_path = ORT_TSTR(""testdata/bert_toy_optimized_bw.onnx""); config.loss_function_config = TrainingSession::TrainingConfiguration::LossFunctionConfiguration{}; config.loss_function_config.value().loss_function_info = LossFunctionInfo(OpDef(""BertLoss"", kOnnxDomain), ""total_loss"", {/*prediction_masked_lm*/ ""prediction_scores"", /*prediction_next_sentence*/ ""seq_relationship_score"", /*masked_lm_positions*/ ""masked_lm_positions"", /*masked_lm_ids*/ ""masked_lm_ids"", /*masked_lm_weights*/ ""masked_lm_weights"", /*next_sentence_labels*/ ""next_sentence_labels"", /*mlm_loss*/ ""mlm_loss"", /*nsp_loss*/ ""nsp_loss""}); config.weight_names_to_not_train = { ""position_01"", // Slice's dat input ""op_min_ends_expand_10"", //op_min_ends_expand_10 }; config.immutable_weights = { {""Div"", {{1, 8.0f}, {1, 1.4142135381698608f}}}, {""Add"", {{1, 1.0f}, {1, 9.999999960041972e-13f}}}, {""Mul"", {{1, 0.5f}, {1, -10000.0f}}}, {""Sub"", {{0, 1.0f}}}}; PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(model_path, config, backprop_model_file)); #ifdef USE_CUDA SessionOptions so; RunBertTrainingWithChecks(so, backprop_model_file); #endif } class PipelineSplitter { public: struct UnidirectionCutInfo { // nodes are identified by its output[0] std::vector nodes; // inputs for sync between sub models std::vector sync_inputs; // outputs for sync between sub models // note there might be some graph ouputs do not need to sync std::vector sync_outputs; // dependencies for maintaining topological order std::vector wait_depends; std::vector record_depends; }; struct CutInfo { UnidirectionCutInfo fw; UnidirectionCutInfo bw; }; PipelineSplitter() = default; void Split( PathString backprop_model_file, const std::vector& sub_model_files, const std::vector& cuts) { const auto num_subs = cuts.size(); std::shared_ptr model; ASSERT_STATUS_OK(Model::Load( backprop_model_file, model, nullptr, DefaultLoggingManager().DefaultLogger())); const auto& main_graph = model->MainGraph(); const auto mp = model->ToProto(); const auto& main_gp = mp.graph(); auto lookup_main_graph_node_arg_proto = [&main_graph](const std::string& node_arg_name) -> const ONNX_NAMESPACE::ValueInfoProto* { const auto* node_arg = main_graph.GetNodeArg(node_arg_name); if (!node_arg) return nullptr; return &node_arg->ToProto(); }; std::vector sub_mps(num_subs, mp); for (size_t i = 0; i < num_subs; ++i) { auto& sub = sub_mps[i]; sub.clear_graph(); FillInputWait(sub.mutable_graph(), main_gp, lookup_main_graph_node_arg_proto, cuts[i].fw.sync_inputs, cuts[i].fw.wait_depends, i, /*bw*/ false); } for (const auto& n : main_gp.node()) { // check which sub_model the node should be in const size_t sub_id = [&]() { for (size_t i = 0; i < num_subs; ++i) { const auto& cut = cuts[i]; if (std::count(cut.fw.nodes.cbegin(), cut.fw.nodes.cend(), n.output()[0])) { return i; } if (std::count(cut.bw.nodes.cbegin(), cut.bw.nodes.cend(), n.output()[0])) { return i; } } ORT_THROW(""Failed to find sub-model containing node: "", n.name()); }(); auto* sub_gp = sub_mps[sub_id].mutable_graph(); const auto& cut = cuts[sub_id]; // add WaitEvent node at the beginning of bw if (!cut.bw.nodes.empty() && n.output()[0] == cut.bw.nodes.front()) { FillInputWait(sub_gp, main_gp, lookup_main_graph_node_arg_proto, cut.bw.sync_inputs, cut.bw.wait_depends, sub_id, /*bw*/ true); } // copy node to sub model sub_gp->mutable_node()->Add()->CopyFrom(n); for (auto i = n.input().cbegin(); i != n.input().cend(); ++i) { AddItemByName(sub_gp->mutable_initializer(), main_gp.initializer(), *i, *i); if (0 == std::count(cut.fw.sync_inputs.cbegin(), cut.fw.sync_inputs.cend(), *i) && 0 == std::count(cut.bw.sync_inputs.cbegin(), cut.bw.sync_inputs.cend(), *i)) { // carry over original graph's input, if not in sync_inputs AddItemByName(sub_gp->mutable_input(), main_gp.input(), *i, *i); } } for (auto i = n.output().cbegin(); i != n.output().cend(); ++i) { if (std::count(cut.fw.sync_outputs.cbegin(), cut.fw.sync_outputs.cend(), *i) || std::count(cut.bw.sync_outputs.cbegin(), cut.bw.sync_outputs.cend(), *i)) continue; // sync_ouputs already handled, skip // add graph output if (!AddItemByName(sub_gp->mutable_output(), main_gp.output(), *i, *i)) { // for non-output, add shape info AddValueInfoByNameFromLookup(*sub_gp->mutable_value_info(), lookup_main_graph_node_arg_proto, *i, *i); } } // add RecordEvent node at the end of fw and bw if ((!cut.fw.nodes.empty() && n.output()[0] == cut.fw.nodes.back()) || (!cut.bw.nodes.empty() && n.output()[0] == cut.bw.nodes.back())) { bool bw = (n.output()[0] == cut.bw.nodes.back()); const auto& sync_outputs = (bw ? cut.bw.sync_outputs : cut.fw.sync_outputs); const auto& dependencies = (bw ? cut.bw.record_depends : cut.fw.record_depends); FillOutputRecord(sub_gp, main_gp, lookup_main_graph_node_arg_proto, sync_outputs, dependencies, sub_id, bw); } } // save sub models for (size_t sub_id = 0; sub_id < num_subs; ++sub_id) { std::ofstream ofs(sub_model_files[sub_id], std::ofstream::binary); sub_mps[sub_id].SerializeToOstream(&ofs); ofs.close(); } } private: // add RepeatedField item by name from another RepeatedFields // return true if the name exists in dst template bool AddItemByName(TD* dst, const TS& src, const std::string& name, const std::string& new_name) { for (auto iter = dst->cbegin(); iter != dst->cend(); ++iter) { if (iter->name() == new_name) { return true; } } for (auto iter = src.cbegin(); iter != src.cend(); ++iter) { if (iter->name() == name) { auto* p = dst->Add(); p->CopyFrom(*iter); *p->mutable_name() = new_name; return true; } } return false; } // expected signature of TValueInfoLookupFn: // const ValueInfoProto* TValueInfoLookupFn(const std::string& name) template bool AddValueInfoByNameFromLookup( google::protobuf::RepeatedPtrField& dst, TValueInfoLookupFn lookup, const std::string& name, const std::string& new_name) { for (auto iter = dst.cbegin(); iter != dst.cend(); ++iter) { if (iter->name() == new_name) { return true; } } const ONNX_NAMESPACE::ValueInfoProto* value_info = lookup(name); if (value_info) { auto* p = dst.Add(); p->CopyFrom(*value_info); *p->mutable_name() = new_name; return true; } return false; } template void FillInputWait( ONNX_NAMESPACE::GraphProto* sub_gp, const ONNX_NAMESPACE::GraphProto& main_gp, TValueInfoLookupFn main_graph_lookup, const std::vector& sync_inputs, const std::vector& dependencies, size_t sub_id, bool bw) { // input/output with Wait/RecordEvent // Note data is gated by Wait/RecordEvent, so name with postfix ""_sync"" // In distributed training, the pattern is: // wait_data -> recv -> wait_pipeline -> fw/bw -> record_pipeline -> send -> record_data // Here wait_data/record_data is to ensure execution order due to data dependency (same batch across pipelines), // while wait_pipeline/recorde_pipeline is to ensure pipeline execution order. // This test simplifies the graph to omit send/recv, // but we still need to have double wait and record to sync data and pipeline separately ONNX_NAMESPACE::NodeProto* wait_data_np = nullptr; ONNX_NAMESPACE::NodeProto* wait_pipeline_np = nullptr; std::string wait_data_id = ""wait_data_"" + std::to_string(sub_id) + (bw ? ""_bw"" : ""_fw""); std::string wait_pipeline_id = ""wait_pipeline_"" + std::to_string(sub_id) + (bw ? ""_bw"" : ""_fw""); bool is_first = (sub_id == 0 && !bw); if (sync_inputs.size() + dependencies.size() > 0) { if (!is_first) { wait_data_np = sub_gp->add_node(); *wait_data_np->mutable_op_type() = ""WaitEvent""; *wait_data_np->mutable_domain() = kMSDomain; *wait_data_np->mutable_input()->Add() = wait_data_id; } wait_pipeline_np = sub_gp->add_node(); *wait_pipeline_np->mutable_op_type() = ""WaitEvent""; *wait_pipeline_np->mutable_domain() = kMSDomain; *wait_pipeline_np->mutable_input()->Add() = wait_pipeline_id; } for (const auto& name : sync_inputs) { std::string input_name = name + ""_sync""; std::string recv_name = name + ""_recv""; if (wait_data_np) { *wait_data_np->mutable_input()->Add() = input_name; *wait_data_np->mutable_output()->Add() = recv_name; *wait_pipeline_np->mutable_input()->Add() = recv_name; } else { *wait_pipeline_np->mutable_input()->Add() = input_name; } *wait_pipeline_np->mutable_output()->Add() = name; // some input comes graph input if (AddItemByName(sub_gp->mutable_input(), main_gp.input(), name, input_name)) { ASSERT_TRUE(is_first); // add shape info EXPECT_TRUE(AddValueInfoByNameFromLookup(*sub_gp->mutable_value_info(), main_graph_lookup, name, name)); } else { // some input comes from the middle of the graph AddValueInfoByNameFromLookup(*sub_gp->mutable_input(), main_graph_lookup, name, input_name); // add shape info AddValueInfoByNameFromLookup(*sub_gp->mutable_value_info(), main_graph_lookup, name, recv_name); AddValueInfoByNameFromLookup(*sub_gp->mutable_value_info(), main_graph_lookup, name, name); } } if (wait_pipeline_np) { //add dependencies on the first wait auto* wait_np = wait_data_np ? wait_data_np : wait_pipeline_np; for (const auto& dep : dependencies) { *wait_np->mutable_input()->Add() = dep; } // add input for event ids if (wait_data_np) { auto* p = sub_gp->mutable_input()->Add(); *p->mutable_name() = wait_data_id; p->mutable_type()->mutable_tensor_type()->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); } auto* p = sub_gp->mutable_input()->Add(); *p->mutable_name() = wait_pipeline_id; p->mutable_type()->mutable_tensor_type()->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); } } template void FillOutputRecord( ONNX_NAMESPACE::GraphProto* sub_gp, const ONNX_NAMESPACE::GraphProto& /*main_gp*/, TValueInfoLookupFn main_graph_lookup, const std::vector& sync_outputs, const std::vector& dependencies, size_t sub_id, bool bw) { ONNX_NAMESPACE::NodeProto* record_pipeline_np = nullptr; ONNX_NAMESPACE::NodeProto* record_data_np = nullptr; std::string record_pipeline_id = ""record_pipeline_"" + std::to_string(sub_id) + (bw ? ""_bw"" : ""_fw""); std::string record_data_id = ""record_data_"" + std::to_string(sub_id) + (bw ? ""_bw"" : ""_fw""); bool is_last = (sub_id == 0 && bw); if (sync_outputs.size() + dependencies.size() > 0) { record_pipeline_np = sub_gp->add_node(); *record_pipeline_np->mutable_op_type() = ""RecordEvent""; *record_pipeline_np->mutable_domain() = kMSDomain; *record_pipeline_np->mutable_input()->Add() = record_pipeline_id; if (!is_last) { record_data_np = sub_gp->add_node(); *record_data_np->mutable_op_type() = ""RecordEvent""; *record_data_np->mutable_domain() = kMSDomain; *record_data_np->mutable_input()->Add() = record_data_id; } } if (sync_outputs.size() > 0) { for (const auto& name : sync_outputs) { *record_pipeline_np->mutable_input()->Add() = name; if (record_data_np) { *record_pipeline_np->mutable_output()->Add() = name + ""_send""; *record_data_np->mutable_input()->Add() = name + ""_send""; *record_data_np->mutable_output()->Add() = name + ""_sync""; } else { *record_pipeline_np->mutable_output()->Add() = name + ""_sync""; } } } if (record_pipeline_np) { for (const auto& name : dependencies) *record_pipeline_np->mutable_input()->Add() = name; // add input for event_id auto* p = sub_gp->mutable_input()->Add(); *p->mutable_name() = record_pipeline_id; p->mutable_type()->mutable_tensor_type()->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); if (record_data_np) { p = sub_gp->mutable_input()->Add(); *p->mutable_name() = record_data_id; p->mutable_type()->mutable_tensor_type()->set_elem_type(ONNX_NAMESPACE::TensorProto_DataType_INT64); } } // add graph output and shape info for (const auto& name : sync_outputs) { AddValueInfoByNameFromLookup(*sub_gp->mutable_output(), main_graph_lookup, name, name + ""_sync""); if (!is_last) { AddValueInfoByNameFromLookup(*sub_gp->mutable_value_info(), main_graph_lookup, name, name + ""_send""); } AddValueInfoByNameFromLookup(*sub_gp->mutable_value_info(), main_graph_lookup, name, name); } } }; // TODO: move to a proper location for pipeline training // pipeline plan for each batch struct PipelineBatchInfo { // Event pairs for each pipeline slot to WaitEvent when start, and RecordEvent when end std::vector> events; // indices of retired batches, so their data could be reused // a batch can only be retired after finished backward in stage 0 // this can be used to join worker threads or reuse buffers // for example, in a node with N GPUs and B batches to run in pipeline (with one stage for each GPU) // there will be (N * B) threads created, and by being able to retire, // only at most (N * (2 * N - 1)) concurrent threads are needed // for small number of B, there's no retired threads so total count would be the same. // for big number of B, this would be helpful std::vector retired_batches; }; class PipelineTimeline { public: struct Slot { enum class Type { Unused, Forward, Backward }; Type type; size_t batch_id; Slot() : type(Type::Unused) {} }; PipelineTimeline() = default; void Initialize(size_t num_stages, size_t num_slots) { slots_.resize(num_stages); for (size_t s = 0; s < num_stages; ++s) { slots_[s].resize(num_slots); } } bool IsOccupied(size_t s, size_t t) const { return slots_[s][t].type != Slot::Type::Unused; } const Slot& Get(size_t s, size_t t) const { return slots_[s][t]; } size_t GetNumSlots() const { return slots_[0].size(); } void Occupy(size_t s, size_t t, size_t batch_id, Slot::Type st) { Slot& slot = slots_[s][t]; ORT_ENFORCE(slot.type == Slot::Type::Unused); slot.type = st; slot.batch_id = batch_id; } private: std::vector> slots_; }; // pipeline planner for batches class PipelineBatchPlanner { private: int64_t max_id_; PipelineTimeline timeline_; public: PipelineBatchPlanner() : max_id_(::onnxruntime::contrib::OrtEventPool::GetPoolSize() - 1) { } // Generate timeline for one-forward-one-backward scheduling, // which schedules execution in batch order to minimize latency for onging batches // each stage requires 2 pair of wait/record events for FW/BW void GenerateOneFWOneBWTimeline(size_t num_stages, size_t num_batches) { // The first batch has 2 * (num_stages - 1) gaps between FW and BW // then 2 slots for FW/BW in each batch size_t num_slots = 2 * (num_stages - 1) + num_batches * 2; timeline_.Initialize(num_stages, num_slots); // fw time slot to start the search for empty ones in each stage std::vector t_fw(num_stages, 0); // bw time slot to start the search for empty ones in each stage std::vector t_bw(num_stages, 0); // generate timeline in batch order to minimize latency for ongoing batches for (size_t batch_id = 0; batch_id < num_batches; ++batch_id) { // plan for FW for (size_t s = 0; s < num_stages; ++s) { while (timeline_.IsOccupied(s, t_fw[s])) { ++t_fw[s]; } // after find a slot, update t[s+1..] if needed for (size_t ss = s + 1; ss < num_stages; ++ss) { t_fw[ss] = std::max(t_fw[ss], t_fw[s] + (ss - s)); } // occupy slot in timeline timeline_.Occupy(s, t_fw[s]++, batch_id, PipelineTimeline::Slot::Type::Forward); } // plan for BW for (int s = gsl::narrow(num_stages - 1); s >= 0; --s) { t_bw[s] = std::max(t_fw[s], t_bw[s]); while (timeline_.IsOccupied(s, t_bw[s])) { t_bw[s]++; } // after find a slot, update t_bw[s-1..] for (int ss = s - 1; ss >= 0; --ss) { t_bw[ss] = std::max(t_bw[ss], t_bw[s] + (s - ss)); } // occupy slot in timeline timeline_.Occupy(s, t_bw[s], batch_id, PipelineTimeline::Slot::Type::Backward); } } } // create pipeline plans according to generated timeline // with start_event_id = s, the output of each stage is [-1, s], [s, s+1], [s+1, s+2]... for each occupied slot // and will be assigned to each batch's PipelineBatchInfo // returns the first unused event_id after creating int64_t CreatePlan(int64_t start_event_id, const size_t stage, std::vector& plan) { // fill in plan int64_t prev_event_id = -1; int64_t event_id = start_event_id; std::vector retired_batches; for (size_t t = 0; t < timeline_.GetNumSlots(); ++t) { if (!timeline_.IsOccupied(stage, t)) continue; const auto& slot = timeline_.Get(stage, t); ORT_ENFORCE(event_id < max_id_); if (stage == 0) { if (slot.type == PipelineTimeline::Slot::Type::Forward) { // set retired batches when starting a new batch (s == 0 && !bw) plan[slot.batch_id].retired_batches = retired_batches; retired_batches.clear(); } else if (slot.type == PipelineTimeline::Slot::Type::Backward) { // add to retired batches after backward of stage 0 retired_batches.push_back(gsl::narrow(slot.batch_id)); } } // add a pair of wait/record event ids to given batch_id plan[slot.batch_id].events.emplace_back(prev_event_id, event_id); prev_event_id = event_id; ++event_id; } return event_id; } }; void RetrieveEventOperators( Graph& graph, Node** forward_wait_before_recv, Node** forward_wait_after_recv, Node** forward_record_before_send, Node** forward_record_after_send, Node** backward_wait_before_recv, Node** backward_wait_after_recv, Node** backward_record_before_send, Node** backward_record_after_send) { // Initialize retrieved nodes. // Non-existing nodes may hold NULL forever. // Existing nodes may get valid pointers below. *forward_wait_before_recv = nullptr; *forward_wait_after_recv = nullptr; *forward_record_before_send = nullptr; *forward_record_after_send = nullptr; *backward_wait_before_recv = nullptr; *backward_wait_after_recv = nullptr; *backward_record_before_send = nullptr; *backward_record_after_send = nullptr; // Declare container for WaitEvent's in topological order. std::vector waits; // Declare container for RecordEvent's in topological order. std::vector records; // Find out WaitEvent's and RecordEvent's. GraphViewer graph_viewer(graph); for (auto& node_idx : graph_viewer.GetNodesInTopologicalOrder()) { Node* node = graph.GetNode(node_idx); if (node->OpType() == ""WaitEvent"") { waits.push_back(node); } else if (node->OpType() == ""RecordEvent"") { records.push_back(node); } } if (waits.size() == size_t(4)) { // Each of first stage and middle stages has 4 WaitEvent's. *forward_wait_before_recv = waits[0]; *forward_wait_after_recv = waits[1]; *backward_wait_before_recv = waits[2]; *backward_wait_after_recv = waits[3]; } else if (waits.size() == size_t(2)) { // Last stage has 2 WaitEvent's. *forward_wait_before_recv = waits[0]; *forward_wait_after_recv = waits[1]; } else { ORT_THROW(""Wrong number of WaitEvent operators: "", waits.size(), ""Expected value is either 2 or 4.""); } if (records.size() == size_t(4)) { // Each of first stage and middle stages has 4 RecordEvent's. *forward_record_before_send = records[0]; *forward_record_after_send = records[1]; *backward_record_before_send = records[2]; *backward_record_after_send = records[3]; } else if (waits.size() == size_t(2)) { // Last stage has 2 RecordEvent's. *backward_record_before_send = records[0]; *backward_record_after_send = records[1]; } else { ORT_THROW(""Wrong number of RecordEvent operators: "", waits.size(), "". Expected value is either 2 or 4.""); } } void RetrieveSendRecvOperators( Graph& graph, Node** forward_recv, Node** forward_send, Node** backward_recv, Node** backward_send) { // Initialize retrieved nodes. // Non-existing nodes may hold NULL forever. // Existing nodes may get valid pointers below. *forward_recv = nullptr; *forward_send = nullptr; *backward_recv = nullptr; *backward_send = nullptr; auto is_backward = [](Node& node) { return (node.Description() == ""Backward pass""); }; // Search for Send's and Recv's by assuming that // there are only one Send and one Recv in forward/backward. for (auto& node : graph.Nodes()) { if (node.OpType() == ""Send"") { if (is_backward(node)) { // backward_send can only be assigned one valid pointer. // If it is assigned more than once, it means we have multiple // Send in backward pass and therefore our assumption doesn't hold. // This check ensure that only we only update *backward_send when // its value is NULL and guards our one-Recv assumption. ASSERT_TRUE(!(*backward_send)); *backward_send = &node; } else { // Guard the uniqueness of Send in the forward pass by throwing // when *forward_send already carries a valid pointer. ASSERT_TRUE(!(*forward_send)); *forward_send = &node; } } else if (node.OpType() == ""Recv"") { if (is_backward(node)) { // Guard the uniqueness of Recv in the backward pass by throwing // when *backward_recv already carries a valid pointer. ASSERT_TRUE(!(*backward_recv)); *backward_recv = &node; } else { // Guard the uniqueness of Recv in the forwaard pass by throwing // when *forward_recv already carries a valid pointer. *forward_recv = &node; } } } } // verify pipeline config can load and gradient graph can construct. TEST(GradientGraphBuilderTest, TrainingSession_PipelineTransform_base) { PathString filename_base = ORT_TSTR(""testdata/test_training_model_""); auto load_and_check_gradient_graph = [](int stageIdx, PathString& input_file, PathString& output_file) { auto config = MakeBasicTrainingConfig(); TrainingSession::TrainingConfiguration::PipelineConfiguration pipe_config{}; config.pipeline_config = pipe_config; PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(input_file, config, backprop_model_file)); std::shared_ptr model; ASSERT_STATUS_OK(Model::Load(backprop_model_file, model, nullptr, DefaultLoggingManager().DefaultLogger())); Graph& graph = model->MainGraph(); // Declare forward event nodes. // The nodes are declared according to their topological order. Node* forward_wait_before_recv{nullptr}; Node* forward_wait_after_recv{nullptr}; Node* forward_record_before_send{nullptr}; Node* forward_record_after_send{nullptr}; // Declare backward event nodes. // The nodes are declared according to their topological order. Node* backward_wait_before_recv{nullptr}; Node* backward_wait_after_recv{nullptr}; Node* backward_record_before_send{nullptr}; Node* backward_record_after_send{nullptr}; // Find event nodes. RetrieveEventOperators( graph, &forward_wait_before_recv, &forward_wait_after_recv, &forward_record_before_send, &forward_record_after_send, &backward_wait_before_recv, &backward_wait_after_recv, &backward_record_before_send, &backward_record_after_send); // Check event nodes. if (stageIdx == 2) { ASSERT_TRUE(forward_wait_before_recv); ASSERT_TRUE(forward_wait_after_recv); // Last pipeline stage can perform backward right after its forward. // It won't have event operators to divide forward from backward. ASSERT_TRUE(!forward_record_before_send); ASSERT_TRUE(!forward_record_after_send); ASSERT_TRUE(!backward_wait_before_recv); ASSERT_TRUE(!backward_wait_after_recv); ASSERT_TRUE(backward_record_before_send); ASSERT_TRUE(backward_record_after_send); } else { // Beginning of forward. ASSERT_TRUE(forward_wait_before_recv); ASSERT_TRUE(forward_wait_after_recv); // End of forward. ASSERT_TRUE(forward_record_before_send); ASSERT_TRUE(forward_record_after_send); // Beginning of backward. ASSERT_TRUE(backward_wait_before_recv); ASSERT_TRUE(backward_wait_after_recv); // End of backward. ASSERT_TRUE(backward_record_before_send); ASSERT_TRUE(backward_record_after_send); } Node* forward_send{nullptr}; Node* forward_recv{nullptr}; Node* backward_recv{nullptr}; Node* backward_send{nullptr}; RetrieveSendRecvOperators( graph, &forward_recv, &forward_send, &backward_recv, &backward_send); // Except the last partion, each partition should have send forward and recv backward. if (stageIdx == 0 || stageIdx == 1) { ASSERT_TRUE(forward_send && backward_recv); } else { ASSERT_TRUE(!forward_send && !backward_recv); } // Except the first partion, each partition should have recv forward and send backward. if (stageIdx == 1 || stageIdx == 2) { ASSERT_TRUE(forward_recv && backward_send); } else { ASSERT_TRUE(!forward_recv && !backward_send); } auto mp = model->ToProto(); std::ofstream ofs(output_file, std::ofstream::binary); mp.SerializeToOstream(&ofs); ofs.close(); }; for (int i = 0; i < 3; ++i) { #ifdef _WIN32 auto surfix = std::to_wstring(i); #else auto surfix = std::to_string(i); #endif PathString input_file = filename_base + surfix + ORT_TSTR("".onnx""); PathString output_file = filename_base + surfix + ORT_TSTR(""_back.onnx""); load_and_check_gradient_graph(i, input_file, output_file); } } TEST(GradientGraphBuilderTest, TrainingSession_WithPipeline) { auto config = MakeBasicTrainingConfig(); //config.set_gradients_as_graph_outputs = true; PathString backprop_model_file; ASSERT_STATUS_OK(BuildBackPropGraph(ORIGINAL_MODEL_PATH, config, backprop_model_file)); // cut the model using outputs const std::vector cuts = { //sub model 0 {{{""T1"", ""T2"", ""T3""}, {""X""}, {""T3""}, {}, {}}, {{""T2_grad"", ""T1_grad"", ""B1_grad"", ""W1_grad""}, {""T3_grad""}, {}, {""T3_sync""}, {""B1_grad"", ""W1_grad""}}}, // sub model 1 {{{""T4"", ""T5"", ""T6""}, {""T3""}, {""T6""}, {}, {}}, {{""T5_grad"", ""T4_grad"", ""T3_grad"", ""B2_grad"", ""W2_grad""}, {""T6_grad""}, {""T3_grad""}, {""T6_sync""}, {""B2_grad"", ""W2_grad""}}}, // sub model 2 {{{""T7"", ""MeanSquaredError_diff"", ""MeanSquaredError_diff_square"", ""loss"", ""predictions""}, {""T6""}, {}, {}, {}}, {{""MeanSquaredError_reduce_mean_Grad/Unqueezed_Grad"", ""MeanSquaredError_reduce_mean_Grad/Tiled_Grad"", ""MeanSquaredError_diff_square_grad"", ""MeanSquaredError_diff_grad"", ""predictions_grad"", ""B3_grad"", ""T7_grad"", ""W3_grad"", ""T6_grad""}, {}, {""T6_grad""}, {}, {""loss"", ""predictions"", ""B3_grad"", ""W3_grad""}}}}; const auto num_subs = cuts.size(); std::vector sub_model_files(num_subs); for (size_t sub_id = 0; sub_id < num_subs; ++sub_id) { #ifdef _WIN32 auto sub_id_str = std::to_wstring(sub_id); #else auto sub_id_str = std::to_string(sub_id); #endif sub_model_files[sub_id] = ORT_TSTR(""sub_"") + sub_id_str + ORT_TSTR("".onnx""); } PipelineSplitter splitter; splitter.Split(backprop_model_file, sub_model_files, cuts); // create training sessions std::unique_ptr env; ASSERT_STATUS_OK(Environment::Create(nullptr, env)); struct SubSession { std::unique_ptr sess; SessionOptions so; RunOptions run_options; }; std::vector subs(num_subs); for (size_t sub_id = 0; sub_id < num_subs; ++sub_id) { auto& sub_sess = subs[sub_id]; sub_sess.so.enable_profiling = true; #ifdef _WIN32 auto sub_id_str = std::to_wstring(sub_id); #else auto sub_id_str = std::to_string(sub_id); #endif sub_sess.so.profile_file_prefix = ORT_TSTR(""pipeline"") + sub_id_str; sub_sess.run_options.run_log_verbosity_level = sub_sess.so.session_log_verbosity_level; sub_sess.run_options.run_tag = sub_sess.so.session_logid; sub_sess.sess = onnxruntime::make_unique(sub_sess.so, *env); ASSERT_STATUS_OK(sub_sess.sess->Load(sub_model_files[sub_id])); ASSERT_STATUS_OK(sub_sess.sess->Initialize()); } // pipeline inputs for each batch struct PipelineFeed { MLValue x_value; MLValue label_value; std::vector record_data_values; std::vector> wait_record_pipeline_values; void SetInputs(const std::vector& x, const std::vector& label) { // dummy data for model inputs std::vector x_dims = {1, 784}; std::vector label_dims = {1, 10}; TrainingUtil::CreateCpuMLValue(x_dims, x, &x_value); TrainingUtil::CreateCpuMLValue(label_dims, label, &label_value); } void SetEvents(const std::vector& record_data, const std::vector>& wait_record_pipeline) { record_data_values.resize(record_data.size()); for (size_t i = 0; i < record_data.size(); ++i) { TrainingUtil::CreateCpuMLValue({}, {record_data[i]}, &record_data_values[i]); } wait_record_pipeline_values.resize(wait_record_pipeline.size()); for (size_t i = 0; i < wait_record_pipeline.size(); ++i) { TrainingUtil::CreateCpuMLValue( {}, {wait_record_pipeline[i].first}, &wait_record_pipeline_values[i].first); TrainingUtil::CreateCpuMLValue( {}, {wait_record_pipeline[i].second}, &wait_record_pipeline_values[i].second); } } }; // pipeline data for each batch struct PipelineData : public PipelineFeed { MLValue t3_value; MLValue t3_grad_value; MLValue t6_value; MLValue t6_grad_value; PipelineData() { std::vector t3_dims = {1, 128}; std::vector t6_dims = {1, 32}; std::vector t3_data(128); std::vector t6_data(32); TrainingUtil::CreateCpuMLValue(t3_dims, t3_data, &t3_value); TrainingUtil::CreateCpuMLValue(t3_dims, t3_data, &t3_grad_value); TrainingUtil::CreateCpuMLValue(t6_dims, t6_data, &t6_value); TrainingUtil::CreateCpuMLValue(t6_dims, t6_data, &t6_grad_value); }; }; auto worker = [&subs](size_t sub_id, PipelineData& data) { std::vector input_names; std::vector input_values; std::vector output_names; std::vector output_values; switch (sub_id) { case 0: input_names = { ""X_sync"", ""T3_grad_sync"", ""wait_pipeline_0_fw"", ""record_pipeline_0_fw"", ""record_data_0_fw"", ""wait_data_0_bw"", ""wait_pipeline_0_bw"", ""record_pipeline_0_bw""}; input_values = { data.x_value, data.t3_grad_value, data.wait_record_pipeline_values[0].first, data.wait_record_pipeline_values[0].second, data.record_data_values[0], data.record_data_values[3], data.wait_record_pipeline_values[1].first, data.wait_record_pipeline_values[1].second}; output_names = {""T3_sync""}; output_values = {data.t3_value}; break; case 1: input_names = { ""T3_sync"", ""T6_grad_sync"", ""wait_data_1_fw"", ""wait_pipeline_1_fw"", ""record_pipeline_1_fw"", ""record_data_1_fw"", ""wait_data_1_bw"", ""wait_pipeline_1_bw"", ""record_pipeline_1_bw"", ""record_data_1_bw""}; input_values = { data.t3_value, data.t6_grad_value, data.record_data_values[0], data.wait_record_pipeline_values[2].first, data.wait_record_pipeline_values[2].second, data.record_data_values[1], data.record_data_values[2], data.wait_record_pipeline_values[3].first, data.wait_record_pipeline_values[3].second, data.record_data_values[3]}; output_names = {""T6_sync"", ""T3_grad_sync""}; output_values = {data.t6_value, data.t3_grad_value}; break; case 2: // note that last stage only need to wait on FW and record and BW // there's no wait/record in between input_names = { ""T6_sync"", ""labels"", ""wait_data_2_fw"", ""wait_pipeline_2_fw"", ""record_pipeline_2_bw"", ""record_data_2_bw""}; input_values = { data.t6_value, data.label_value, data.record_data_values[1], data.wait_record_pipeline_values[4].first, // wait on FW data.wait_record_pipeline_values[5].second, // record on BW data.record_data_values[2]}; output_names = {""T6_grad_sync""}; output_values = {data.t6_grad_value}; break; default: ASSERT_TRUE(false); } EXPECT_STATUS_OK(subs[sub_id].sess->Run(subs[sub_id].run_options, input_names, input_values, output_names, &output_values)); }; const std::vector start_ids = {100, 200, 300}; const std::vector expected_end_ids = {112, 212, 312}; const size_t num_stages = start_ids.size(); const int num_batches = 6; std::vector plan(num_batches); PipelineBatchPlanner planner; planner.GenerateOneFWOneBWTimeline(num_stages, num_batches); // create plan for all stages for testing purpose // in actual execution, only one stage would be needed for each rank for (size_t stage = 0; stage < num_stages; ++stage) { int64_t end_id = planner.CreatePlan(start_ids[stage], stage, plan); EXPECT_TRUE(end_id == expected_end_ids[stage]); } // Timeline view of ground truth for plan // sub 0: F0 F1 F2 F3 F4 B0 F5 B1 B2 B3 B4 B5 // sub 1: F0 F1 F2 B0 F3 B1 F4 B2 F5 B3 B4 B5 // sub 2: F0 B0 F1 B1 F2 B2 F3 B3 F4 B4 F5 B5 // Note that in distributed training, event id would be local to each pipeline // We use different ranges for event ids for pipelines here: // 0 -> 99: data dependencies for record_data // 100 -> 199: sub 0 // 200 -> 299: sub 1 // 300 -> 399: sub 2 // so for sub 0, the schedule is: // F0(-1, 100), F1(100,101), F2(101,102)... // for sub 1, the schedule is: // F0(-1, 200), F1(200,201), F2(201,202)... // for sub 2, the schedule is: // F0 (-1, 300), B0 (300, 301), F1 (301, 302), B1(302, 303)... // Note the chart above is timeline view, execution plan needs to change it to batch view const std::vector expected_plan = { // each batch event pairs are in order of: // batch 0 events on {sub0_fw, sub0_bw, sub1_fw, sub1_bw, sub2_fwbw} {{{-1, 100}, {104, 105}, {-1, 200}, {202, 203}, {-1, 300}, {300, 301}}, {}}, // batch 1 {{{100, 101}, {106, 107}, {200, 201}, {204, 205}, {301, 302}, {302, 303}}, {}}, // batch 2 {{{101, 102}, {107, 108}, {201, 202}, {206, 207}, {303, 304}, {304, 305}}, {}}, // batch 3 {{{102, 103}, {108, 109}, {203, 204}, {208, 209}, {305, 306}, {306, 307}}, {}}, // batch 4 {{{103, 104}, {109, 110}, {205, 206}, {209, 210}, {307, 308}, {308, 309}}, {}}, // batch 5 {{{105, 106}, {110, 111}, {207, 208}, {210, 211}, {309, 310}, {310, 311}}, {0}}, }; for (int batch = 0; batch < num_batches; ++batch) { EXPECT_TRUE(expected_plan[batch].retired_batches == plan[batch].retired_batches); EXPECT_TRUE(expected_plan[batch].events.size() == plan[batch].events.size()); for (size_t evt_id = 0; evt_id < expected_plan[batch].events.size(); ++evt_id) { EXPECT_TRUE(expected_plan[batch].events[evt_id] == plan[batch].events[evt_id]); } } struct BatchContext { PipelineData data; std::vector workers; }; std::unordered_map> batch_ctx_pool; for (int batch_id = 0; batch_id < num_batches; ++batch_id) { std::vector x(784); std::vector label(10); std::shared_ptr batch_ctx; bool reuse_batch_ctx = false; if (!plan[batch_id].retired_batches.empty()) { auto iter = batch_ctx_pool.find(plan[batch_id].retired_batches[0]); if (iter != batch_ctx_pool.end()) { batch_ctx = iter->second; // clean up retired batch, and reclaim data for reuse for (auto& w : batch_ctx->workers) { w.join(); } batch_ctx->workers.resize(0); batch_ctx_pool.erase(plan[batch_id].retired_batches[0]); reuse_batch_ctx = true; } } if (!reuse_batch_ctx) { batch_ctx = std::make_shared(); } // set inputs batch_ctx->data.SetInputs(x, label); batch_ctx->data.SetEvents({batch_id * 4, batch_id * 4 + 1, batch_id * 4 + 2, batch_id * 4 + 3}, plan[batch_id].events); // create one worker thread for each batch and each pipeline stage for (size_t sub_id = 0; sub_id < num_subs; ++sub_id) { auto* pd = &(batch_ctx->data); batch_ctx->workers.emplace_back([&worker, pd, sub_id]() { worker(sub_id, *pd); }); } batch_ctx_pool.emplace(batch_id, batch_ctx); } // wait until all workers done for (auto& pair : batch_ctx_pool) { for (auto& w : pair.second->workers) { w.join(); } } // finish profiler for (size_t sub_id = 0; sub_id < num_subs; ++sub_id) { subs[sub_id].sess->EndProfiling(); } } } // namespace test } // namespace onnxruntime ",16235,False,2412.3411463778825,median "/* * Copyright (C) 2008, 2009 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include ""config.h"" #if ENABLE(JIT) #if USE(JSVALUE32_64) #include ""JIT.h"" #include ""CodeBlock.h"" #include ""GCAwareJITStubRoutine.h"" #include ""Interpreter.h"" #include ""JITInlines.h"" #include ""JITStubCall.h"" #include ""JSArray.h"" #include ""JSFunction.h"" #include ""JSPropertyNameIterator.h"" #include ""JSVariableObject.h"" #include ""LinkBuffer.h"" #include ""RepatchBuffer.h"" #include ""ResultType.h"" #include ""SamplingTool.h"" #include #ifndef NDEBUG #include #endif using namespace std; namespace JSC { void JIT::emit_op_put_by_index(Instruction* currentInstruction) { unsigned base = currentInstruction[1].u.operand; unsigned property = currentInstruction[2].u.operand; unsigned value = currentInstruction[3].u.operand; JITStubCall stubCall(this, cti_op_put_by_index); stubCall.addArgument(base); stubCall.addArgument(TrustedImm32(property)); stubCall.addArgument(value); stubCall.call(); } void JIT::emit_op_put_getter_setter(Instruction* currentInstruction) { unsigned base = currentInstruction[1].u.operand; unsigned property = currentInstruction[2].u.operand; unsigned getter = currentInstruction[3].u.operand; unsigned setter = currentInstruction[4].u.operand; JITStubCall stubCall(this, cti_op_put_getter_setter); stubCall.addArgument(base); stubCall.addArgument(TrustedImmPtr(&m_codeBlock->identifier(property))); stubCall.addArgument(getter); stubCall.addArgument(setter); stubCall.call(); } void JIT::emit_op_del_by_id(Instruction* currentInstruction) { unsigned dst = currentInstruction[1].u.operand; unsigned base = currentInstruction[2].u.operand; unsigned property = currentInstruction[3].u.operand; JITStubCall stubCall(this, cti_op_del_by_id); stubCall.addArgument(base); stubCall.addArgument(TrustedImmPtr(&m_codeBlock->identifier(property))); stubCall.call(dst); } JIT::CodeRef JIT::stringGetByValStubGenerator(VM* vm) { JSInterfaceJIT jit; JumpList failures; failures.append(jit.branchPtr(NotEqual, Address(regT0, JSCell::structureOffset()), TrustedImmPtr(vm->stringStructure.get()))); // Load string length to regT1, and start the process of loading the data pointer into regT0 jit.load32(Address(regT0, ThunkHelpers::jsStringLengthOffset()), regT1); jit.loadPtr(Address(regT0, ThunkHelpers::jsStringValueOffset()), regT0); failures.append(jit.branchTest32(Zero, regT0)); // Do an unsigned compare to simultaneously filter negative indices as well as indices that are too large failures.append(jit.branch32(AboveOrEqual, regT2, regT1)); // Load the character JumpList is16Bit; JumpList cont8Bit; // Load the string flags jit.loadPtr(Address(regT0, StringImpl::flagsOffset()), regT1); jit.loadPtr(Address(regT0, StringImpl::dataOffset()), regT0); is16Bit.append(jit.branchTest32(Zero, regT1, TrustedImm32(StringImpl::flagIs8Bit()))); jit.load8(BaseIndex(regT0, regT2, TimesOne, 0), regT0); cont8Bit.append(jit.jump()); is16Bit.link(&jit); jit.load16(BaseIndex(regT0, regT2, TimesTwo, 0), regT0); cont8Bit.link(&jit); failures.append(jit.branch32(AboveOrEqual, regT0, TrustedImm32(0x100))); jit.move(TrustedImmPtr(vm->smallStrings.singleCharacterStrings()), regT1); jit.loadPtr(BaseIndex(regT1, regT0, ScalePtr, 0), regT0); jit.move(TrustedImm32(JSValue::CellTag), regT1); // We null check regT0 on return so this is safe jit.ret(); failures.link(&jit); jit.move(TrustedImm32(0), regT0); jit.ret(); LinkBuffer patchBuffer(*vm, &jit, GLOBAL_THUNK_ID); return FINALIZE_CODE(patchBuffer, (""String get_by_val stub"")); } void JIT::emit_op_get_by_val(Instruction* currentInstruction) { unsigned dst = currentInstruction[1].u.operand; unsigned base = currentInstruction[2].u.operand; unsigned property = currentInstruction[3].u.operand; ArrayProfile* profile = currentInstruction[4].u.arrayProfile; emitLoad2(base, regT1, regT0, property, regT3, regT2); addSlowCase(branch32(NotEqual, regT3, TrustedImm32(JSValue::Int32Tag))); emitJumpSlowCaseIfNotJSCell(base, regT1); loadPtr(Address(regT0, JSCell::structureOffset()), regT1); emitArrayProfilingSite(regT1, regT3, profile); and32(TrustedImm32(IndexingShapeMask), regT1); PatchableJump badType; JumpList slowCases; JITArrayMode mode = chooseArrayMode(profile); switch (mode) { case JITInt32: slowCases = emitInt32GetByVal(currentInstruction, badType); break; case JITDouble: slowCases = emitDoubleGetByVal(currentInstruction, badType); break; case JITContiguous: slowCases = emitContiguousGetByVal(currentInstruction, badType); break; case JITArrayStorage: slowCases = emitArrayStorageGetByVal(currentInstruction, badType); break; default: CRASH(); } addSlowCase(badType); addSlowCase(slowCases); Label done = label(); #if !ASSERT_DISABLED Jump resultOK = branch32(NotEqual, regT1, TrustedImm32(JSValue::EmptyValueTag)); breakpoint(); resultOK.link(this); #endif emitValueProfilingSite(); emitStore(dst, regT1, regT0); map(m_bytecodeOffset + OPCODE_LENGTH(op_get_by_val), dst, regT1, regT0); m_byValCompilationInfo.append(ByValCompilationInfo(m_bytecodeOffset, badType, mode, done)); } JIT::JumpList JIT::emitContiguousGetByVal(Instruction*, PatchableJump& badType, IndexingType expectedShape) { JumpList slowCases; badType = patchableBranch32(NotEqual, regT1, TrustedImm32(expectedShape)); loadPtr(Address(regT0, JSObject::butterflyOffset()), regT3); slowCases.append(branch32(AboveOrEqual, regT2, Address(regT3, Butterfly::offsetOfPublicLength()))); load32(BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1); // tag load32(BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0); // payload slowCases.append(branch32(Equal, regT1, TrustedImm32(JSValue::EmptyValueTag))); return slowCases; } JIT::JumpList JIT::emitDoubleGetByVal(Instruction*, PatchableJump& badType) { JumpList slowCases; badType = patchableBranch32(NotEqual, regT1, TrustedImm32(DoubleShape)); loadPtr(Address(regT0, JSObject::butterflyOffset()), regT3); slowCases.append(branch32(AboveOrEqual, regT2, Address(regT3, Butterfly::offsetOfPublicLength()))); loadDouble(BaseIndex(regT3, regT2, TimesEight), fpRegT0); slowCases.append(branchDouble(DoubleNotEqualOrUnordered, fpRegT0, fpRegT0)); moveDoubleToInts(fpRegT0, regT0, regT1); return slowCases; } JIT::JumpList JIT::emitArrayStorageGetByVal(Instruction*, PatchableJump& badType) { JumpList slowCases; add32(TrustedImm32(-ArrayStorageShape), regT1, regT3); badType = patchableBranch32(Above, regT3, TrustedImm32(SlowPutArrayStorageShape - ArrayStorageShape)); loadPtr(Address(regT0, JSObject::butterflyOffset()), regT3); slowCases.append(branch32(AboveOrEqual, regT2, Address(regT3, ArrayStorage::vectorLengthOffset()))); load32(BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(ArrayStorage, m_vector[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1); // tag load32(BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(ArrayStorage, m_vector[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0); // payload slowCases.append(branch32(Equal, regT1, TrustedImm32(JSValue::EmptyValueTag))); return slowCases; } void JIT::emitSlow_op_get_by_val(Instruction* currentInstruction, Vector::iterator& iter) { unsigned dst = currentInstruction[1].u.operand; unsigned base = currentInstruction[2].u.operand; unsigned property = currentInstruction[3].u.operand; ArrayProfile* profile = currentInstruction[4].u.arrayProfile; linkSlowCase(iter); // property int32 check linkSlowCaseIfNotJSCell(iter, base); // base cell check Jump nonCell = jump(); linkSlowCase(iter); // base array check Jump notString = branchPtr(NotEqual, Address(regT0, JSCell::structureOffset()), TrustedImmPtr(m_vm->stringStructure.get())); emitNakedCall(m_vm->getCTIStub(stringGetByValStubGenerator).code()); Jump failed = branchTestPtr(Zero, regT0); emitStore(dst, regT1, regT0); emitJumpSlowToHot(jump(), OPCODE_LENGTH(op_get_by_val)); failed.link(this); notString.link(this); nonCell.link(this); Jump skipProfiling = jump(); linkSlowCase(iter); // vector length check linkSlowCase(iter); // empty value emitArrayProfileOutOfBoundsSpecialCase(profile); skipProfiling.link(this); Label slowPath = label(); JITStubCall stubCall(this, cti_op_get_by_val); stubCall.addArgument(base); stubCall.addArgument(property); Call call = stubCall.call(dst); m_byValCompilationInfo[m_byValInstructionIndex].slowPathTarget = slowPath; m_byValCompilationInfo[m_byValInstructionIndex].returnAddress = call; m_byValInstructionIndex++; emitValueProfilingSite(); } void JIT::emit_op_put_by_val(Instruction* currentInstruction) { unsigned base = currentInstruction[1].u.operand; unsigned property = currentInstruction[2].u.operand; ArrayProfile* profile = currentInstruction[4].u.arrayProfile; emitLoad2(base, regT1, regT0, property, regT3, regT2); addSlowCase(branch32(NotEqual, regT3, TrustedImm32(JSValue::Int32Tag))); emitJumpSlowCaseIfNotJSCell(base, regT1); loadPtr(Address(regT0, JSCell::structureOffset()), regT1); emitArrayProfilingSite(regT1, regT3, profile); and32(TrustedImm32(IndexingShapeMask), regT1); PatchableJump badType; JumpList slowCases; JITArrayMode mode = chooseArrayMode(profile); switch (mode) { case JITInt32: slowCases = emitInt32PutByVal(currentInstruction, badType); break; case JITDouble: slowCases = emitDoublePutByVal(currentInstruction, badType); break; case JITContiguous: slowCases = emitContiguousPutByVal(currentInstruction, badType); break; case JITArrayStorage: slowCases = emitArrayStoragePutByVal(currentInstruction, badType); break; default: CRASH(); break; } addSlowCase(badType); addSlowCase(slowCases); Label done = label(); m_byValCompilationInfo.append(ByValCompilationInfo(m_bytecodeOffset, badType, mode, done)); } JIT::JumpList JIT::emitGenericContiguousPutByVal(Instruction* currentInstruction, PatchableJump& badType, IndexingType indexingShape) { unsigned value = currentInstruction[3].u.operand; ArrayProfile* profile = currentInstruction[4].u.arrayProfile; JumpList slowCases; badType = patchableBranch32(NotEqual, regT1, TrustedImm32(ContiguousShape)); loadPtr(Address(regT0, JSObject::butterflyOffset()), regT3); Jump outOfBounds = branch32(AboveOrEqual, regT2, Address(regT3, Butterfly::offsetOfPublicLength())); Label storeResult = label(); emitLoad(value, regT1, regT0); switch (indexingShape) { case Int32Shape: slowCases.append(branch32(NotEqual, regT1, TrustedImm32(JSValue::Int32Tag))); // Fall through. case ContiguousShape: store32(regT0, BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(JSValue, u.asBits.payload))); store32(regT1, BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(JSValue, u.asBits.tag))); break; case DoubleShape: { Jump notInt = branch32(NotEqual, regT1, TrustedImm32(JSValue::Int32Tag)); convertInt32ToDouble(regT0, fpRegT0); Jump ready = jump(); notInt.link(this); moveIntsToDouble(regT0, regT1, fpRegT0, fpRegT1); slowCases.append(branchDouble(DoubleNotEqualOrUnordered, fpRegT0, fpRegT0)); ready.link(this); storeDouble(fpRegT0, BaseIndex(regT3, regT2, TimesEight)); break; } default: CRASH(); break; } Jump done = jump(); outOfBounds.link(this); slowCases.append(branch32(AboveOrEqual, regT2, Address(regT3, Butterfly::offsetOfVectorLength()))); emitArrayProfileStoreToHoleSpecialCase(profile); add32(TrustedImm32(1), regT2, regT1); store32(regT1, Address(regT3, Butterfly::offsetOfPublicLength())); jump().linkTo(storeResult, this); done.link(this); emitWriteBarrier(regT0, regT1, regT1, regT3, UnconditionalWriteBarrier, WriteBarrierForPropertyAccess); return slowCases; } JIT::JumpList JIT::emitArrayStoragePutByVal(Instruction* currentInstruction, PatchableJump& badType) { unsigned value = currentInstruction[3].u.operand; ArrayProfile* profile = currentInstruction[4].u.arrayProfile; JumpList slowCases; badType = patchableBranch32(NotEqual, regT1, TrustedImm32(ArrayStorageShape)); loadPtr(Address(regT0, JSObject::butterflyOffset()), regT3); slowCases.append(branch32(AboveOrEqual, regT2, Address(regT3, ArrayStorage::vectorLengthOffset()))); Jump empty = branch32(Equal, BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(ArrayStorage, m_vector[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), TrustedImm32(JSValue::EmptyValueTag)); Label storeResult(this); emitLoad(value, regT1, regT0); store32(regT0, BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(ArrayStorage, m_vector[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.payload))); // payload store32(regT1, BaseIndex(regT3, regT2, TimesEight, OBJECT_OFFSETOF(ArrayStorage, m_vector[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.tag))); // tag Jump end = jump(); empty.link(this); emitArrayProfileStoreToHoleSpecialCase(profile); add32(TrustedImm32(1), Address(regT3, OBJECT_OFFSETOF(ArrayStorage, m_numValuesInVector))); branch32(Below, regT2, Address(regT3, ArrayStorage::lengthOffset())).linkTo(storeResult, this); add32(TrustedImm32(1), regT2, regT0); store32(regT0, Address(regT3, ArrayStorage::lengthOffset())); jump().linkTo(storeResult, this); end.link(this); emitWriteBarrier(regT0, regT1, regT1, regT3, UnconditionalWriteBarrier, WriteBarrierForPropertyAccess); return slowCases; } void JIT::emitSlow_op_put_by_val(Instruction* currentInstruction, Vector::iterator& iter) { unsigned base = currentInstruction[1].u.operand; unsigned property = currentInstruction[2].u.operand; unsigned value = currentInstruction[3].u.operand; ArrayProfile* profile = currentInstruction[4].u.arrayProfile; linkSlowCase(iter); // property int32 check linkSlowCaseIfNotJSCell(iter, base); // base cell check linkSlowCase(iter); // base not array check JITArrayMode mode = chooseArrayMode(profile); switch (mode) { case JITInt32: case JITDouble: linkSlowCase(iter); // value type check break; default: break; } Jump skipProfiling = jump(); linkSlowCase(iter); // out of bounds emitArrayProfileOutOfBoundsSpecialCase(profile); skipProfiling.link(this); Label slowPath = label(); JITStubCall stubPutByValCall(this, cti_op_put_by_val); stubPutByValCall.addArgument(base); stubPutByValCall.addArgument(property); stubPutByValCall.addArgument(value); Call call = stubPutByValCall.call(); m_byValCompilationInfo[m_byValInstructionIndex].slowPathTarget = slowPath; m_byValCompilationInfo[m_byValInstructionIndex].returnAddress = call; m_byValInstructionIndex++; } void JIT::emit_op_get_by_id(Instruction* currentInstruction) { int dst = currentInstruction[1].u.operand; int base = currentInstruction[2].u.operand; Identifier* ident = &(m_codeBlock->identifier(currentInstruction[3].u.operand)); emitLoad(base, regT1, regT0); emitJumpSlowCaseIfNotJSCell(base, regT1); compileGetByIdHotPath(ident); emitValueProfilingSite(); emitStore(dst, regT1, regT0); map(m_bytecodeOffset + OPCODE_LENGTH(op_get_by_id), dst, regT1, regT0); } void JIT::compileGetByIdHotPath(Identifier* ident) { // As for put_by_id, get_by_id requires the offset of the Structure and the offset of the access to be patched. // Additionally, for get_by_id we need patch the offset of the branch to the slow case (we patch this to jump // to array-length / prototype access tranpolines, and finally we also the the property-map access offset as a label // to jump back to if one of these trampolies finds a match. if (*ident == m_vm->propertyNames->length && shouldEmitProfiling()) { loadPtr(Address(regT0, JSCell::structureOffset()), regT2); emitArrayProfilingSiteForBytecodeIndex(regT2, regT3, m_bytecodeOffset); } BEGIN_UNINTERRUPTED_SEQUENCE(sequenceGetByIdHotPath); Label hotPathBegin(this); DataLabelPtr structureToCompare; PatchableJump structureCheck = patchableBranchPtrWithPatch(NotEqual, Address(regT0, JSCell::structureOffset()), structureToCompare, TrustedImmPtr(reinterpret_cast(patchGetByIdDefaultStructure))); addSlowCase(structureCheck); ConvertibleLoadLabel propertyStorageLoad = convertibleLoadPtr(Address(regT0, JSObject::butterflyOffset()), regT2); DataLabelCompact displacementLabel1 = loadPtrWithCompactAddressOffsetPatch(Address(regT2, patchGetByIdDefaultOffset), regT0); // payload DataLabelCompact displacementLabel2 = loadPtrWithCompactAddressOffsetPatch(Address(regT2, patchGetByIdDefaultOffset), regT1); // tag Label putResult(this); END_UNINTERRUPTED_SEQUENCE(sequenceGetByIdHotPath); m_propertyAccessCompilationInfo.append(PropertyStubCompilationInfo(PropertyStubGetById, m_bytecodeOffset, hotPathBegin, structureToCompare, structureCheck, propertyStorageLoad, displacementLabel1, displacementLabel2, putResult)); } void JIT::emitSlow_op_get_by_id(Instruction* currentInstruction, Vector::iterator& iter) { int dst = currentInstruction[1].u.operand; int base = currentInstruction[2].u.operand; int ident = currentInstruction[3].u.operand; compileGetByIdSlowCase(dst, base, &(m_codeBlock->identifier(ident)), iter); emitValueProfilingSite(); } void JIT::compileGetByIdSlowCase(int dst, int base, Identifier* ident, Vector::iterator& iter) { // As for the hot path of get_by_id, above, we ensure that we can use an architecture specific offset // so that we only need track one pointer into the slow case code - we track a pointer to the location // of the call (which we can use to look up the patch information), but should a array-length or // prototype access trampoline fail we want to bail out back to here. To do so we can subtract back // the distance from the call to the head of the slow case. linkSlowCaseIfNotJSCell(iter, base); linkSlowCase(iter); BEGIN_UNINTERRUPTED_SEQUENCE(sequenceGetByIdSlowCase); Label coldPathBegin(this); JITStubCall stubCall(this, cti_op_get_by_id); stubCall.addArgument(regT1, regT0); stubCall.addArgument(TrustedImmPtr(ident)); Call call = stubCall.call(dst); END_UNINTERRUPTED_SEQUENCE_FOR_PUT(sequenceGetByIdSlowCase, dst); // Track the location of the call; this will be used to recover patch information. m_propertyAccessCompilationInfo[m_propertyAccessInstructionIndex++].slowCaseInfo(PropertyStubGetById, coldPathBegin, call); } void JIT::emit_op_put_by_id(Instruction* currentInstruction) { // In order to be able to patch both the Structure, and the object offset, we store one pointer, // to just after the arguments have been loaded into registers 'hotPathBegin', and we generate code // such that the Structure & offset are always at the same distance from this. int base = currentInstruction[1].u.operand; int value = currentInstruction[3].u.operand; emitLoad2(base, regT1, regT0, value, regT3, regT2); emitJumpSlowCaseIfNotJSCell(base, regT1); BEGIN_UNINTERRUPTED_SEQUENCE(sequencePutById); Label hotPathBegin(this); // It is important that the following instruction plants a 32bit immediate, in order that it can be patched over. DataLabelPtr structureToCompare; addSlowCase(branchPtrWithPatch(NotEqual, Address(regT0, JSCell::structureOffset()), structureToCompare, TrustedImmPtr(reinterpret_cast(patchGetByIdDefaultStructure)))); ConvertibleLoadLabel propertyStorageLoad = convertibleLoadPtr(Address(regT0, JSObject::butterflyOffset()), regT1); DataLabel32 displacementLabel1 = storePtrWithAddressOffsetPatch(regT2, Address(regT1, patchPutByIdDefaultOffset)); // payload DataLabel32 displacementLabel2 = storePtrWithAddressOffsetPatch(regT3, Address(regT1, patchPutByIdDefaultOffset)); // tag END_UNINTERRUPTED_SEQUENCE(sequencePutById); emitWriteBarrier(regT0, regT2, regT1, regT2, ShouldFilterImmediates, WriteBarrierForPropertyAccess); m_propertyAccessCompilationInfo.append(PropertyStubCompilationInfo(PropertyStubPutById, m_bytecodeOffset, hotPathBegin, structureToCompare, propertyStorageLoad, displacementLabel1, displacementLabel2)); } void JIT::emitSlow_op_put_by_id(Instruction* currentInstruction, Vector::iterator& iter) { int base = currentInstruction[1].u.operand; int ident = currentInstruction[2].u.operand; int direct = currentInstruction[8].u.operand; linkSlowCaseIfNotJSCell(iter, base); linkSlowCase(iter); JITStubCall stubCall(this, direct ? cti_op_put_by_id_direct : cti_op_put_by_id); stubCall.addArgument(base); stubCall.addArgument(TrustedImmPtr(&(m_codeBlock->identifier(ident)))); stubCall.addArgument(regT3, regT2); Call call = stubCall.call(); // Track the location of the call; this will be used to recover patch information. m_propertyAccessCompilationInfo[m_propertyAccessInstructionIndex++].slowCaseInfo(PropertyStubPutById, call); } // Compile a store into an object's property storage. May overwrite base. void JIT::compilePutDirectOffset(RegisterID base, RegisterID valueTag, RegisterID valuePayload, PropertyOffset cachedOffset) { if (isOutOfLineOffset(cachedOffset)) loadPtr(Address(base, JSObject::butterflyOffset()), base); emitStore(indexRelativeToBase(cachedOffset), valueTag, valuePayload, base); } // Compile a load from an object's property storage. May overwrite base. void JIT::compileGetDirectOffset(RegisterID base, RegisterID resultTag, RegisterID resultPayload, PropertyOffset cachedOffset) { if (isInlineOffset(cachedOffset)) { emitLoad(indexRelativeToBase(cachedOffset), resultTag, resultPayload, base); return; } RegisterID temp = resultPayload; loadPtr(Address(base, JSObject::butterflyOffset()), temp); emitLoad(indexRelativeToBase(cachedOffset), resultTag, resultPayload, temp); } void JIT::compileGetDirectOffset(JSObject* base, RegisterID resultTag, RegisterID resultPayload, PropertyOffset cachedOffset) { if (isInlineOffset(cachedOffset)) { move(TrustedImmPtr(base->locationForOffset(cachedOffset)), resultTag); load32(Address(resultTag, OBJECT_OFFSETOF(JSValue, u.asBits.payload)), resultPayload); load32(Address(resultTag, OBJECT_OFFSETOF(JSValue, u.asBits.tag)), resultTag); return; } loadPtr(base->butterflyAddress(), resultTag); load32(Address(resultTag, offsetInButterfly(cachedOffset) * sizeof(WriteBarrier) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), resultPayload); load32(Address(resultTag, offsetInButterfly(cachedOffset) * sizeof(WriteBarrier) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), resultTag); } void JIT::privateCompilePutByIdTransition(StructureStubInfo* stubInfo, Structure* oldStructure, Structure* newStructure, PropertyOffset cachedOffset, StructureChain* chain, ReturnAddressPtr returnAddress, bool direct) { // The code below assumes that regT0 contains the basePayload and regT1 contains the baseTag. Restore them from the stack. #if CPU(MIPS) || CPU(SH4) || CPU(ARM) // For MIPS, we don't add sizeof(void*) to the stack offset. load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0); // For MIPS, we don't add sizeof(void*) to the stack offset. load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1); #else load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + sizeof(void*) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0); load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + sizeof(void*) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1); #endif JumpList failureCases; failureCases.append(branch32(NotEqual, regT1, TrustedImm32(JSValue::CellTag))); failureCases.append(branchPtr(NotEqual, Address(regT0, JSCell::structureOffset()), TrustedImmPtr(oldStructure))); testPrototype(oldStructure->storedPrototype(), failureCases, stubInfo); if (!direct) { // Verify that nothing in the prototype chain has a setter for this property. for (WriteBarrier* it = chain->head(); *it; ++it) testPrototype((*it)->storedPrototype(), failureCases, stubInfo); } // If we succeed in all of our checks, and the code was optimizable, then make sure we // decrement the rare case counter. #if ENABLE(VALUE_PROFILER) if (m_codeBlock->canCompileWithDFG() >= DFG::MayInline) { sub32( TrustedImm32(1), AbsoluteAddress(&m_codeBlock->rareCaseProfileForBytecodeOffset(stubInfo->bytecodeIndex)->m_counter)); } #endif // Reallocate property storage if needed. Call callTarget; bool willNeedStorageRealloc = oldStructure->outOfLineCapacity() != newStructure->outOfLineCapacity(); if (willNeedStorageRealloc) { // This trampoline was called to like a JIT stub; before we can can call again we need to // remove the return address from the stack, to prevent the stack from becoming misaligned. preserveReturnAddressAfterCall(regT3); JITStubCall stubCall(this, cti_op_put_by_id_transition_realloc); stubCall.skipArgument(); // base stubCall.skipArgument(); // ident stubCall.skipArgument(); // value stubCall.addArgument(TrustedImm32(oldStructure->outOfLineCapacity())); stubCall.addArgument(TrustedImmPtr(newStructure)); stubCall.call(regT0); restoreReturnAddressBeforeReturn(regT3); #if CPU(MIPS) || CPU(SH4) || CPU(ARM) // For MIPS, we don't add sizeof(void*) to the stack offset. load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0); // For MIPS, we don't add sizeof(void*) to the stack offset. load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1); #else load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + sizeof(void*) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0); load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[0]) + sizeof(void*) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1); #endif } emitWriteBarrier(regT0, regT1, regT1, regT3, UnconditionalWriteBarrier, WriteBarrierForPropertyAccess); storePtr(TrustedImmPtr(newStructure), Address(regT0, JSCell::structureOffset())); #if CPU(MIPS) || CPU(SH4) || CPU(ARM) // For MIPS, we don't add sizeof(void*) to the stack offset. load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[2]) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT3); load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[2]) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT2); #else load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[2]) + sizeof(void*) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT3); load32(Address(stackPointerRegister, OBJECT_OFFSETOF(JITStackFrame, args[2]) + sizeof(void*) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT2); #endif compilePutDirectOffset(regT0, regT2, regT3, cachedOffset); ret(); ASSERT(!failureCases.empty()); failureCases.link(this); restoreArgumentReferenceForTrampoline(); Call failureCall = tailRecursiveCall(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); patchBuffer.link(failureCall, FunctionPtr(direct ? cti_op_put_by_id_direct_fail : cti_op_put_by_id_fail)); if (willNeedStorageRealloc) { ASSERT(m_calls.size() == 1); patchBuffer.link(m_calls[0].from, FunctionPtr(cti_op_put_by_id_transition_realloc)); } stubInfo->stubRoutine = createJITStubRoutine( FINALIZE_CODE( patchBuffer, (""Baseline put_by_id transition stub for %s, return point %p"", toCString(*m_codeBlock).data(), returnAddress.value())), *m_vm, m_codeBlock->ownerExecutable(), willNeedStorageRealloc, newStructure); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relinkCallerToTrampoline(returnAddress, CodeLocationLabel(stubInfo->stubRoutine->code().code())); } void JIT::patchGetByIdSelf(CodeBlock* codeBlock, StructureStubInfo* stubInfo, Structure* structure, PropertyOffset cachedOffset, ReturnAddressPtr returnAddress) { RepatchBuffer repatchBuffer(codeBlock); // We don't want to patch more than once - in future go to cti_op_get_by_id_generic. // Should probably go to JITStubs::cti_op_get_by_id_fail, but that doesn't do anything interesting right now. repatchBuffer.relinkCallerToFunction(returnAddress, FunctionPtr(cti_op_get_by_id_self_fail)); // Patch the offset into the propoerty map to load from, then patch the Structure to look for. repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelPtrAtOffset(stubInfo->patch.baseline.u.get.structureToCompare), structure); repatchBuffer.setLoadInstructionIsActive(stubInfo->hotPathBegin.convertibleLoadAtOffset(stubInfo->patch.baseline.u.get.propertyStorageLoad), isOutOfLineOffset(cachedOffset)); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelCompactAtOffset(stubInfo->patch.baseline.u.get.displacementLabel1), offsetRelativeToPatchedStorage(cachedOffset) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)); // payload repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelCompactAtOffset(stubInfo->patch.baseline.u.get.displacementLabel2), offsetRelativeToPatchedStorage(cachedOffset) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)); // tag } void JIT::patchPutByIdReplace(CodeBlock* codeBlock, StructureStubInfo* stubInfo, Structure* structure, PropertyOffset cachedOffset, ReturnAddressPtr returnAddress, bool direct) { RepatchBuffer repatchBuffer(codeBlock); // We don't want to patch more than once - in future go to cti_op_put_by_id_generic. // Should probably go to cti_op_put_by_id_fail, but that doesn't do anything interesting right now. repatchBuffer.relinkCallerToFunction(returnAddress, FunctionPtr(direct ? cti_op_put_by_id_direct_generic : cti_op_put_by_id_generic)); // Patch the offset into the propoerty map to load from, then patch the Structure to look for. repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelPtrAtOffset(stubInfo->patch.baseline.u.put.structureToCompare), structure); repatchBuffer.setLoadInstructionIsActive(stubInfo->hotPathBegin.convertibleLoadAtOffset(stubInfo->patch.baseline.u.put.propertyStorageLoad), isOutOfLineOffset(cachedOffset)); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabel32AtOffset(stubInfo->patch.baseline.u.put.displacementLabel1), offsetRelativeToPatchedStorage(cachedOffset) + OBJECT_OFFSETOF(JSValue, u.asBits.payload)); // payload repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabel32AtOffset(stubInfo->patch.baseline.u.put.displacementLabel2), offsetRelativeToPatchedStorage(cachedOffset) + OBJECT_OFFSETOF(JSValue, u.asBits.tag)); // tag } void JIT::privateCompilePatchGetArrayLength(ReturnAddressPtr returnAddress) { StructureStubInfo* stubInfo = &m_codeBlock->getStubInfo(returnAddress); // regT0 holds a JSCell* // Check for array loadPtr(Address(regT0, JSCell::structureOffset()), regT2); Jump failureCases1 = branchTest32(Zero, regT2, TrustedImm32(IsArray)); Jump failureCases2 = branchTest32(Zero, regT2, TrustedImm32(IndexingShapeMask)); // Checks out okay! - get the length from the storage loadPtr(Address(regT0, JSArray::butterflyOffset()), regT2); load32(Address(regT2, ArrayStorage::lengthOffset()), regT2); Jump failureCases3 = branch32(Above, regT2, TrustedImm32(INT_MAX)); move(regT2, regT0); move(TrustedImm32(JSValue::Int32Tag), regT1); Jump success = jump(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); // Use the patch information to link the failure cases back to the original slow case routine. CodeLocationLabel slowCaseBegin = stubInfo->callReturnLocation.labelAtOffset(-stubInfo->patch.baseline.u.get.coldPathBegin); patchBuffer.link(failureCases1, slowCaseBegin); patchBuffer.link(failureCases2, slowCaseBegin); patchBuffer.link(failureCases3, slowCaseBegin); // On success return back to the hot patch code, at a point it will perform the store to dest for us. patchBuffer.link(success, stubInfo->hotPathBegin.labelAtOffset(stubInfo->patch.baseline.u.get.putResult)); // Track the stub we have created so that it will be deleted later. stubInfo->stubRoutine = FINALIZE_CODE_FOR_STUB( patchBuffer, (""Baseline get_by_id array length stub for %s, return point %p"", toCString(*m_codeBlock).data(), stubInfo->hotPathBegin.labelAtOffset( stubInfo->patch.baseline.u.get.putResult).executableAddress())); // Finally patch the jump to slow case back in the hot path to jump here instead. CodeLocationJump jumpLocation = stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relink(jumpLocation, CodeLocationLabel(stubInfo->stubRoutine->code().code())); // We don't want to patch more than once - in future go to cti_op_put_by_id_generic. repatchBuffer.relinkCallerToFunction(returnAddress, FunctionPtr(cti_op_get_by_id_array_fail)); } void JIT::privateCompileGetByIdProto(StructureStubInfo* stubInfo, Structure* structure, Structure* prototypeStructure, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset, ReturnAddressPtr returnAddress, CallFrame* callFrame) { // regT0 holds a JSCell* // The prototype object definitely exists (if this stub exists the CodeBlock is referencing a Structure that is // referencing the prototype object - let's speculatively load it's table nice and early!) JSObject* protoObject = asObject(structure->prototypeForLookup(callFrame)); Jump failureCases1 = checkStructure(regT0, structure); // Check the prototype object's Structure had not changed. Jump failureCases2 = addStructureTransitionCheck(protoObject, prototypeStructure, stubInfo, regT3); bool needsStubLink = false; // Checks out okay! if (slot.cachedPropertyType() == PropertySlot::Getter) { needsStubLink = true; compileGetDirectOffset(protoObject, regT2, regT1, cachedOffset); JITStubCall stubCall(this, cti_op_get_by_id_getter_stub); stubCall.addArgument(regT1); stubCall.addArgument(regT0); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else if (slot.cachedPropertyType() == PropertySlot::Custom) { needsStubLink = true; JITStubCall stubCall(this, cti_op_get_by_id_custom_stub); stubCall.addArgument(TrustedImmPtr(protoObject)); stubCall.addArgument(TrustedImmPtr(FunctionPtr(slot.customGetter()).executableAddress())); stubCall.addArgument(TrustedImmPtr(const_cast(&ident))); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else compileGetDirectOffset(protoObject, regT1, regT0, cachedOffset); Jump success = jump(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); // Use the patch information to link the failure cases back to the original slow case routine. CodeLocationLabel slowCaseBegin = stubInfo->callReturnLocation.labelAtOffset(-stubInfo->patch.baseline.u.get.coldPathBegin); patchBuffer.link(failureCases1, slowCaseBegin); if (failureCases2.isSet()) patchBuffer.link(failureCases2, slowCaseBegin); // On success return back to the hot patch code, at a point it will perform the store to dest for us. patchBuffer.link(success, stubInfo->hotPathBegin.labelAtOffset(stubInfo->patch.baseline.u.get.putResult)); if (needsStubLink) { for (Vector::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) { if (iter->to) patchBuffer.link(iter->from, FunctionPtr(iter->to)); } } // Track the stub we have created so that it will be deleted later. stubInfo->stubRoutine = createJITStubRoutine( FINALIZE_CODE( patchBuffer, (""Baseline get_by_id proto stub for %s, return point %p"", toCString(*m_codeBlock).data(), stubInfo->hotPathBegin.labelAtOffset( stubInfo->patch.baseline.u.get.putResult).executableAddress())), *m_vm, m_codeBlock->ownerExecutable(), needsStubLink); // Finally patch the jump to slow case back in the hot path to jump here instead. CodeLocationJump jumpLocation = stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relink(jumpLocation, CodeLocationLabel(stubInfo->stubRoutine->code().code())); // We don't want to patch more than once - in future go to cti_op_put_by_id_generic. repatchBuffer.relinkCallerToFunction(returnAddress, FunctionPtr(cti_op_get_by_id_proto_list)); } void JIT::privateCompileGetByIdSelfList(StructureStubInfo* stubInfo, PolymorphicAccessStructureList* polymorphicStructures, int currentIndex, Structure* structure, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset) { // regT0 holds a JSCell* Jump failureCase = checkStructure(regT0, structure); bool needsStubLink = false; bool isDirect = false; if (slot.cachedPropertyType() == PropertySlot::Getter) { needsStubLink = true; compileGetDirectOffset(regT0, regT2, regT1, cachedOffset); JITStubCall stubCall(this, cti_op_get_by_id_getter_stub); stubCall.addArgument(regT1); stubCall.addArgument(regT0); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else if (slot.cachedPropertyType() == PropertySlot::Custom) { needsStubLink = true; JITStubCall stubCall(this, cti_op_get_by_id_custom_stub); stubCall.addArgument(regT0); stubCall.addArgument(TrustedImmPtr(FunctionPtr(slot.customGetter()).executableAddress())); stubCall.addArgument(TrustedImmPtr(const_cast(&ident))); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else { isDirect = true; compileGetDirectOffset(regT0, regT1, regT0, cachedOffset); } Jump success = jump(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); if (needsStubLink) { for (Vector::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) { if (iter->to) patchBuffer.link(iter->from, FunctionPtr(iter->to)); } } // Use the patch information to link the failure cases back to the original slow case routine. CodeLocationLabel lastProtoBegin = CodeLocationLabel(JITStubRoutine::asCodePtr(polymorphicStructures->list[currentIndex - 1].stubRoutine)); if (!lastProtoBegin) lastProtoBegin = stubInfo->callReturnLocation.labelAtOffset(-stubInfo->patch.baseline.u.get.coldPathBegin); patchBuffer.link(failureCase, lastProtoBegin); // On success return back to the hot patch code, at a point it will perform the store to dest for us. patchBuffer.link(success, stubInfo->hotPathBegin.labelAtOffset(stubInfo->patch.baseline.u.get.putResult)); RefPtr stubRoutine = createJITStubRoutine( FINALIZE_CODE( patchBuffer, (""Baseline get_by_id self list stub for %s, return point %p"", toCString(*m_codeBlock).data(), stubInfo->hotPathBegin.labelAtOffset( stubInfo->patch.baseline.u.get.putResult).executableAddress())), *m_vm, m_codeBlock->ownerExecutable(), needsStubLink); polymorphicStructures->list[currentIndex].set(*m_vm, m_codeBlock->ownerExecutable(), stubRoutine, structure, isDirect); // Finally patch the jump to slow case back in the hot path to jump here instead. CodeLocationJump jumpLocation = stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relink(jumpLocation, CodeLocationLabel(stubRoutine->code().code())); } void JIT::privateCompileGetByIdProtoList(StructureStubInfo* stubInfo, PolymorphicAccessStructureList* prototypeStructures, int currentIndex, Structure* structure, Structure* prototypeStructure, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset, CallFrame* callFrame) { // regT0 holds a JSCell* // The prototype object definitely exists (if this stub exists the CodeBlock is referencing a Structure that is // referencing the prototype object - let's speculatively load it's table nice and early!) JSObject* protoObject = asObject(structure->prototypeForLookup(callFrame)); // Check eax is an object of the right Structure. Jump failureCases1 = checkStructure(regT0, structure); // Check the prototype object's Structure had not changed. Jump failureCases2 = addStructureTransitionCheck(protoObject, prototypeStructure, stubInfo, regT3); bool needsStubLink = false; bool isDirect = false; if (slot.cachedPropertyType() == PropertySlot::Getter) { needsStubLink = true; compileGetDirectOffset(protoObject, regT2, regT1, cachedOffset); JITStubCall stubCall(this, cti_op_get_by_id_getter_stub); stubCall.addArgument(regT1); stubCall.addArgument(regT0); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else if (slot.cachedPropertyType() == PropertySlot::Custom) { needsStubLink = true; JITStubCall stubCall(this, cti_op_get_by_id_custom_stub); stubCall.addArgument(TrustedImmPtr(protoObject)); stubCall.addArgument(TrustedImmPtr(FunctionPtr(slot.customGetter()).executableAddress())); stubCall.addArgument(TrustedImmPtr(const_cast(&ident))); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else { isDirect = true; compileGetDirectOffset(protoObject, regT1, regT0, cachedOffset); } Jump success = jump(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); if (needsStubLink) { for (Vector::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) { if (iter->to) patchBuffer.link(iter->from, FunctionPtr(iter->to)); } } // Use the patch information to link the failure cases back to the original slow case routine. CodeLocationLabel lastProtoBegin = CodeLocationLabel(JITStubRoutine::asCodePtr(prototypeStructures->list[currentIndex - 1].stubRoutine)); patchBuffer.link(failureCases1, lastProtoBegin); if (failureCases2.isSet()) patchBuffer.link(failureCases2, lastProtoBegin); // On success return back to the hot patch code, at a point it will perform the store to dest for us. patchBuffer.link(success, stubInfo->hotPathBegin.labelAtOffset(stubInfo->patch.baseline.u.get.putResult)); RefPtr stubRoutine = createJITStubRoutine( FINALIZE_CODE( patchBuffer, (""Baseline get_by_id proto list stub for %s, return point %p"", toCString(*m_codeBlock).data(), stubInfo->hotPathBegin.labelAtOffset( stubInfo->patch.baseline.u.get.putResult).executableAddress())), *m_vm, m_codeBlock->ownerExecutable(), needsStubLink); prototypeStructures->list[currentIndex].set(callFrame->vm(), m_codeBlock->ownerExecutable(), stubRoutine, structure, prototypeStructure, isDirect); // Finally patch the jump to slow case back in the hot path to jump here instead. CodeLocationJump jumpLocation = stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relink(jumpLocation, CodeLocationLabel(stubRoutine->code().code())); } void JIT::privateCompileGetByIdChainList(StructureStubInfo* stubInfo, PolymorphicAccessStructureList* prototypeStructures, int currentIndex, Structure* structure, StructureChain* chain, size_t count, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset, CallFrame* callFrame) { // regT0 holds a JSCell* ASSERT(count); JumpList bucketsOfFail; // Check eax is an object of the right Structure. bucketsOfFail.append(checkStructure(regT0, structure)); Structure* currStructure = structure; WriteBarrier* it = chain->head(); JSObject* protoObject = 0; for (unsigned i = 0; i < count; ++i, ++it) { protoObject = asObject(currStructure->prototypeForLookup(callFrame)); currStructure = it->get(); testPrototype(protoObject, bucketsOfFail, stubInfo); } ASSERT(protoObject); bool needsStubLink = false; bool isDirect = false; if (slot.cachedPropertyType() == PropertySlot::Getter) { needsStubLink = true; compileGetDirectOffset(protoObject, regT2, regT1, cachedOffset); JITStubCall stubCall(this, cti_op_get_by_id_getter_stub); stubCall.addArgument(regT1); stubCall.addArgument(regT0); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else if (slot.cachedPropertyType() == PropertySlot::Custom) { needsStubLink = true; JITStubCall stubCall(this, cti_op_get_by_id_custom_stub); stubCall.addArgument(TrustedImmPtr(protoObject)); stubCall.addArgument(TrustedImmPtr(FunctionPtr(slot.customGetter()).executableAddress())); stubCall.addArgument(TrustedImmPtr(const_cast(&ident))); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else { isDirect = true; compileGetDirectOffset(protoObject, regT1, regT0, cachedOffset); } Jump success = jump(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); if (needsStubLink) { for (Vector::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) { if (iter->to) patchBuffer.link(iter->from, FunctionPtr(iter->to)); } } // Use the patch information to link the failure cases back to the original slow case routine. CodeLocationLabel lastProtoBegin = CodeLocationLabel(JITStubRoutine::asCodePtr(prototypeStructures->list[currentIndex - 1].stubRoutine)); patchBuffer.link(bucketsOfFail, lastProtoBegin); // On success return back to the hot patch code, at a point it will perform the store to dest for us. patchBuffer.link(success, stubInfo->hotPathBegin.labelAtOffset(stubInfo->patch.baseline.u.get.putResult)); RefPtr stubRoutine = createJITStubRoutine( FINALIZE_CODE( patchBuffer, (""Baseline get_by_id chain list stub for %s, return point %p"", toCString(*m_codeBlock).data(), stubInfo->hotPathBegin.labelAtOffset( stubInfo->patch.baseline.u.get.putResult).executableAddress())), *m_vm, m_codeBlock->ownerExecutable(), needsStubLink); // Track the stub we have created so that it will be deleted later. prototypeStructures->list[currentIndex].set(callFrame->vm(), m_codeBlock->ownerExecutable(), stubRoutine, structure, chain, isDirect); // Finally patch the jump to slow case back in the hot path to jump here instead. CodeLocationJump jumpLocation = stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relink(jumpLocation, CodeLocationLabel(stubRoutine->code().code())); } void JIT::privateCompileGetByIdChain(StructureStubInfo* stubInfo, Structure* structure, StructureChain* chain, size_t count, const Identifier& ident, const PropertySlot& slot, PropertyOffset cachedOffset, ReturnAddressPtr returnAddress, CallFrame* callFrame) { // regT0 holds a JSCell* ASSERT(count); JumpList bucketsOfFail; // Check eax is an object of the right Structure. bucketsOfFail.append(checkStructure(regT0, structure)); Structure* currStructure = structure; WriteBarrier* it = chain->head(); JSObject* protoObject = 0; for (unsigned i = 0; i < count; ++i, ++it) { protoObject = asObject(currStructure->prototypeForLookup(callFrame)); currStructure = it->get(); testPrototype(protoObject, bucketsOfFail, stubInfo); } ASSERT(protoObject); bool needsStubLink = false; if (slot.cachedPropertyType() == PropertySlot::Getter) { needsStubLink = true; compileGetDirectOffset(protoObject, regT2, regT1, cachedOffset); JITStubCall stubCall(this, cti_op_get_by_id_getter_stub); stubCall.addArgument(regT1); stubCall.addArgument(regT0); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else if (slot.cachedPropertyType() == PropertySlot::Custom) { needsStubLink = true; JITStubCall stubCall(this, cti_op_get_by_id_custom_stub); stubCall.addArgument(TrustedImmPtr(protoObject)); stubCall.addArgument(TrustedImmPtr(FunctionPtr(slot.customGetter()).executableAddress())); stubCall.addArgument(TrustedImmPtr(const_cast(&ident))); stubCall.addArgument(TrustedImmPtr(stubInfo->callReturnLocation.executableAddress())); stubCall.call(); } else compileGetDirectOffset(protoObject, regT1, regT0, cachedOffset); Jump success = jump(); LinkBuffer patchBuffer(*m_vm, this, m_codeBlock); if (needsStubLink) { for (Vector::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) { if (iter->to) patchBuffer.link(iter->from, FunctionPtr(iter->to)); } } // Use the patch information to link the failure cases back to the original slow case routine. patchBuffer.link(bucketsOfFail, stubInfo->callReturnLocation.labelAtOffset(-stubInfo->patch.baseline.u.get.coldPathBegin)); // On success return back to the hot patch code, at a point it will perform the store to dest for us. patchBuffer.link(success, stubInfo->hotPathBegin.labelAtOffset(stubInfo->patch.baseline.u.get.putResult)); // Track the stub we have created so that it will be deleted later. RefPtr stubRoutine = createJITStubRoutine( FINALIZE_CODE( patchBuffer, (""Baseline get_by_id chain stub for %s, return point %p"", toCString(*m_codeBlock).data(), stubInfo->hotPathBegin.labelAtOffset( stubInfo->patch.baseline.u.get.putResult).executableAddress())), *m_vm, m_codeBlock->ownerExecutable(), needsStubLink); stubInfo->stubRoutine = stubRoutine; // Finally patch the jump to slow case back in the hot path to jump here instead. CodeLocationJump jumpLocation = stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck); RepatchBuffer repatchBuffer(m_codeBlock); repatchBuffer.relink(jumpLocation, CodeLocationLabel(stubRoutine->code().code())); // We don't want to patch more than once - in future go to cti_op_put_by_id_generic. repatchBuffer.relinkCallerToFunction(returnAddress, FunctionPtr(cti_op_get_by_id_proto_list)); } void JIT::compileGetDirectOffset(RegisterID base, RegisterID resultTag, RegisterID resultPayload, RegisterID offset, FinalObjectMode finalObjectMode) { ASSERT(sizeof(JSValue) == 8); if (finalObjectMode == MayBeFinal) { Jump isInline = branch32(LessThan, offset, TrustedImm32(firstOutOfLineOffset)); loadPtr(Address(base, JSObject::butterflyOffset()), base); neg32(offset); Jump done = jump(); isInline.link(this); addPtr(TrustedImmPtr(JSObject::offsetOfInlineStorage() - (firstOutOfLineOffset - 2) * sizeof(EncodedJSValue)), base); done.link(this); } else { #if !ASSERT_DISABLED Jump isOutOfLine = branch32(GreaterThanOrEqual, offset, TrustedImm32(firstOutOfLineOffset)); breakpoint(); isOutOfLine.link(this); #endif loadPtr(Address(base, JSObject::butterflyOffset()), base); neg32(offset); } load32(BaseIndex(base, offset, TimesEight, OBJECT_OFFSETOF(JSValue, u.asBits.payload) + (firstOutOfLineOffset - 2) * sizeof(EncodedJSValue)), resultPayload); load32(BaseIndex(base, offset, TimesEight, OBJECT_OFFSETOF(JSValue, u.asBits.tag) + (firstOutOfLineOffset - 2) * sizeof(EncodedJSValue)), resultTag); } void JIT::emit_op_get_by_pname(Instruction* currentInstruction) { unsigned dst = currentInstruction[1].u.operand; unsigned base = currentInstruction[2].u.operand; unsigned property = currentInstruction[3].u.operand; unsigned expected = currentInstruction[4].u.operand; unsigned iter = currentInstruction[5].u.operand; unsigned i = currentInstruction[6].u.operand; emitLoad2(property, regT1, regT0, base, regT3, regT2); emitJumpSlowCaseIfNotJSCell(property, regT1); addSlowCase(branchPtr(NotEqual, regT0, payloadFor(expected))); // Property registers are now available as the property is known emitJumpSlowCaseIfNotJSCell(base, regT3); emitLoadPayload(iter, regT1); // Test base's structure loadPtr(Address(regT2, JSCell::structureOffset()), regT0); addSlowCase(branchPtr(NotEqual, regT0, Address(regT1, OBJECT_OFFSETOF(JSPropertyNameIterator, m_cachedStructure)))); load32(addressFor(i), regT3); sub32(TrustedImm32(1), regT3); addSlowCase(branch32(AboveOrEqual, regT3, Address(regT1, OBJECT_OFFSETOF(JSPropertyNameIterator, m_numCacheableSlots)))); Jump inlineProperty = branch32(Below, regT3, Address(regT1, OBJECT_OFFSETOF(JSPropertyNameIterator, m_cachedStructureInlineCapacity))); add32(TrustedImm32(firstOutOfLineOffset), regT3); sub32(Address(regT1, OBJECT_OFFSETOF(JSPropertyNameIterator, m_cachedStructureInlineCapacity)), regT3); inlineProperty.link(this); compileGetDirectOffset(regT2, regT1, regT0, regT3); emitStore(dst, regT1, regT0); map(m_bytecodeOffset + OPCODE_LENGTH(op_get_by_pname), dst, regT1, regT0); } void JIT::emitSlow_op_get_by_pname(Instruction* currentInstruction, Vector::iterator& iter) { unsigned dst = currentInstruction[1].u.operand; unsigned base = currentInstruction[2].u.operand; unsigned property = currentInstruction[3].u.operand; linkSlowCaseIfNotJSCell(iter, property); linkSlowCase(iter); linkSlowCaseIfNotJSCell(iter, base); linkSlowCase(iter); linkSlowCase(iter); JITStubCall stubCall(this, cti_op_get_by_val_generic); stubCall.addArgument(base); stubCall.addArgument(property); stubCall.call(dst); } void JIT::emit_op_get_scoped_var(Instruction* currentInstruction) { int dst = currentInstruction[1].u.operand; int index = currentInstruction[2].u.operand; int skip = currentInstruction[3].u.operand; emitGetFromCallFrameHeaderPtr(JSStack::ScopeChain, regT2); bool checkTopLevel = m_codeBlock->codeType() == FunctionCode && m_codeBlock->needsFullScopeChain(); ASSERT(skip || !checkTopLevel); if (checkTopLevel && skip--) { Jump activationNotCreated; if (checkTopLevel) activationNotCreated = branch32(Equal, tagFor(m_codeBlock->activationRegister()), TrustedImm32(JSValue::EmptyValueTag)); loadPtr(Address(regT2, JSScope::offsetOfNext()), regT2); activationNotCreated.link(this); } while (skip--) loadPtr(Address(regT2, JSScope::offsetOfNext()), regT2); loadPtr(Address(regT2, JSVariableObject::offsetOfRegisters()), regT2); emitLoad(index, regT1, regT0, regT2); emitValueProfilingSite(); emitStore(dst, regT1, regT0); map(m_bytecodeOffset + OPCODE_LENGTH(op_get_scoped_var), dst, regT1, regT0); } void JIT::emit_op_put_scoped_var(Instruction* currentInstruction) { int index = currentInstruction[1].u.operand; int skip = currentInstruction[2].u.operand; int value = currentInstruction[3].u.operand; emitLoad(value, regT1, regT0); emitGetFromCallFrameHeaderPtr(JSStack::ScopeChain, regT2); bool checkTopLevel = m_codeBlock->codeType() == FunctionCode && m_codeBlock->needsFullScopeChain(); ASSERT(skip || !checkTopLevel); if (checkTopLevel && skip--) { Jump activationNotCreated; if (checkTopLevel) activationNotCreated = branch32(Equal, tagFor(m_codeBlock->activationRegister()), TrustedImm32(JSValue::EmptyValueTag)); loadPtr(Address(regT2, JSScope::offsetOfNext()), regT2); activationNotCreated.link(this); } while (skip--) loadPtr(Address(regT2, JSScope::offsetOfNext()), regT2); loadPtr(Address(regT2, JSVariableObject::offsetOfRegisters()), regT3); emitStore(index, regT1, regT0, regT3); emitWriteBarrier(regT2, regT1, regT0, regT1, ShouldFilterImmediates, WriteBarrierForVariableAccess); } void JIT::emit_op_init_global_const(Instruction* currentInstruction) { WriteBarrier* registerPointer = currentInstruction[1].u.registerPointer; int value = currentInstruction[2].u.operand; JSGlobalObject* globalObject = m_codeBlock->globalObject(); emitLoad(value, regT1, regT0); if (Heap::isWriteBarrierEnabled()) { move(TrustedImmPtr(globalObject), regT2); emitWriteBarrier(globalObject, regT1, regT3, ShouldFilterImmediates, WriteBarrierForVariableAccess); } store32(regT1, registerPointer->tagPointer()); store32(regT0, registerPointer->payloadPointer()); map(m_bytecodeOffset + OPCODE_LENGTH(op_init_global_const), value, regT1, regT0); } void JIT::emit_op_init_global_const_check(Instruction* currentInstruction) { WriteBarrier* registerPointer = currentInstruction[1].u.registerPointer; int value = currentInstruction[2].u.operand; JSGlobalObject* globalObject = m_codeBlock->globalObject(); emitLoad(value, regT1, regT0); addSlowCase(branchTest8(NonZero, AbsoluteAddress(currentInstruction[3].u.predicatePointer))); if (Heap::isWriteBarrierEnabled()) { move(TrustedImmPtr(globalObject), regT2); emitWriteBarrier(globalObject, regT1, regT3, ShouldFilterImmediates, WriteBarrierForVariableAccess); } store32(regT1, registerPointer->tagPointer()); store32(regT0, registerPointer->payloadPointer()); unmap(); } void JIT::emitSlow_op_init_global_const_check(Instruction* currentInstruction, Vector::iterator& iter) { linkSlowCase(iter); JITStubCall stubCall(this, cti_op_init_global_const_check); stubCall.addArgument(regT1, regT0); stubCall.addArgument(TrustedImm32(currentInstruction[4].u.operand)); stubCall.call(); } void JIT::resetPatchGetById(RepatchBuffer& repatchBuffer, StructureStubInfo* stubInfo) { repatchBuffer.relink(stubInfo->callReturnLocation, cti_op_get_by_id); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelPtrAtOffset(stubInfo->patch.baseline.u.get.structureToCompare), reinterpret_cast(unusedPointer)); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelCompactAtOffset(stubInfo->patch.baseline.u.get.displacementLabel1), 0); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelCompactAtOffset(stubInfo->patch.baseline.u.get.displacementLabel2), 0); repatchBuffer.relink(stubInfo->hotPathBegin.jumpAtOffset(stubInfo->patch.baseline.u.get.structureCheck), stubInfo->callReturnLocation.labelAtOffset(-stubInfo->patch.baseline.u.get.coldPathBegin)); } void JIT::resetPatchPutById(RepatchBuffer& repatchBuffer, StructureStubInfo* stubInfo) { if (isDirectPutById(stubInfo)) repatchBuffer.relink(stubInfo->callReturnLocation, cti_op_put_by_id_direct); else repatchBuffer.relink(stubInfo->callReturnLocation, cti_op_put_by_id); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabelPtrAtOffset(stubInfo->patch.baseline.u.put.structureToCompare), reinterpret_cast(unusedPointer)); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabel32AtOffset(stubInfo->patch.baseline.u.put.displacementLabel1), 0); repatchBuffer.repatch(stubInfo->hotPathBegin.dataLabel32AtOffset(stubInfo->patch.baseline.u.put.displacementLabel2), 0); } } // namespace JSC #endif // USE(JSVALUE32_64) #endif // ENABLE(JIT) ",16173,True,3317.659364192923,median "--- title: Συχνές Ερωτήσεις Σχετικά με τις Λίστες Ηλεκτρονικού Ταχυδρομείου του FreeBSD authors: - author: Η Ομάδα Τεκμηρίωσης του FreeBSD releaseinfo: ""$FreeBSD: head/el_GR.ISO8859-7/articles/mailing-list-faq/article.xml 43184 2013-11-13 07:52:45Z hrs $"" --- = Συχνές Ερωτήσεις Σχετικά με τις Λίστες Ηλεκτρονικού Ταχυδρομείου του FreeBSD :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :source-highlighter: rouge :experimental: :figure-caption: Figure include::share/authors.adoc[] include::share/gr/mailing-lists.adoc[lines=10..-1] include::share/gr/urls.adoc[] [.abstract-title] Περίληψη Το άρθρο αυτό αποτελεί τις συχνές ερωτήσεις για τις λίστες ταχυδρομείου του FreeBSD. Αν ενδιαφέρεστε να βοηθήσετε σε αυτό το έργο, στείλτε ένα email στην {freebsd-doc}. Η τελευταία έκδοση αυτού του εγγράφου είναι πάντοτε διαθέσιμη στην link:{mailing-list-faq}[Δικτυακή τοποθεσία του FreeBSD]. Μπορείτε επίσης να το κατεβάσετε ως ένα μεγάλο αρχείο link:.[HTML] ή και ως απλό κείμενο, PostScript, PDF, κ.λ.π. από τον link:ftp://ftp.FreeBSD.org/pub/FreeBSD/doc/[Διακομιστή FTP του FreeBSD]. Μπορεί επίσης να θέλετε να link:https://www.FreeBSD.org/search/[ψάξετε σε αυτό το άρθρο]. ''' toc::[] [[introduction]] [.title] == Εισαγωγή Όπως συνηθίζεται στα κείμενα των Συχνών Ερωτήσεων (FAQ), το κείμενο αυτό περιέχει τις πιο συχνές ερωτήσεις που σχετίζονται με τις λίστες ταχυδρομείου του FreeBSD (και φυσικά τις απαντάει!). Αν και ο αρχικός σκοπός των FAQ ήταν να μειώσουν το εύρος ζώνης που απαιτείται από την συνεχόμενη απάντηση των ίδιων και ίδιων ερωτήσεων, τα FAQ τελικά καθιερώθηκαν ως μια πολύ χρήσιμη αυτόνομη πηγή πληροφοριών. Το κείμενο αυτό προσπαθεί να αντιπροσωπεύσει την κοινά αποδεκτή γνώμη της κοινότητας και ως τέτοιο, δεν μπορεί σε καμιά περίπτωση να θεωρηθεί ότι είναι απόλυτα __έγκυρο__. Αν ωστόσο βρείτε τεχνικά λάθη ή έχετε να προτείνετε θέματα που πρέπει να προστεθούν, παρακαλούμε στείλτε μας μια αναφορά προβλήματος (PR) ή ένα email στην {freebsd-doc}. Ευχαριστούμε! === Ποιος είναι ο σκοπός των λιστών ταχυδρομείου του FreeBSD; Οι λίστες ταχυδρομείου του FreeBSD αποτελούν το βασικό κανάλι επικοινωνίας για την κοινότητα του FreeBSD. Καλύπτουν πολλές διαφορετικές περιοχές θεμάτων και ενδιαφερόντων. === Ποιο είναι το κοινό για τις λίστες ταχυδρομείου του FreeBSD; Αυτό εξαρτάται από τον κανονισμό της κάθε λίστας. Μερικές λίστες είναι περισσότερο προσανατολισμένες στους προγραμματιστές. Άλλες προσανατολίζονται περισσότερο στην κοινότητα του FreeBSD ως σύνολο. Παρακαλούμε δείτε http://lists.FreeBSD.org/mailman/listinfo[αυτή τη λίστα] για την τρέχουσα περίληψη. === Είναι όλες οι λίστες του FreeBSD ανοιχτές για συμμετοχή από τον καθένα; Και πάλι, αυτό εξαρτάται από τον κανονισμό της κάθε λίστας. Σας παρακαλούμε να διαβάσετε τον κανονισμό της λίστας που σας ενδιαφέρει πριν αρχίσετε να δημοσιεύετε σε αυτήν και να τον σέβεστε σε κάθε δημοσίευση σας. Αυτό βοηθάει όλους τους συμμετέχοντες να έχουν την καλύτερη δυνατή εμπειρία από τις λίστες μας. Αν διαβάζοντας τους κανονισμούς για τις παραπάνω λίστες, δεν μπορείτε ακόμα να αποφασίσετε σε ποια λίστα να στείλετε την ερώτηση σας, μάλλον θα πρέπει να την στείλετε στην {freebsd-questions} (αλλά δείτε πρώτα παρακάτω). Σημειώστε επίσης ότι κατά παράδοση οι λίστες είναι ανοιχτές και σε άτομα που δεν έχουν εγγραφεί σε αυτές. Αυτή η επιλογή είναι εσκεμμένη, με σκοπό να βοηθήσει τους νέους χρήστες να εισέλθουν πιο εύκολα στην κοινότητα του FreeBSD, και να ενισχύσει την ανοιχτή ανταλλαγή ιδεών. Ωστόσο, λόγω κακής χρήσης από συγκεκριμένα άτομα, κάποιες λίστες έχουν τώρα τον περιορισμό ότι κάθε μήνυμα από μη-μέλος θα πρέπει να ελέγχεται χειροκίνητα για να εξασφαλιστεί ότι είναι κατάλληλο. === Πως μπορώ να εγγραφώ; Μπορείτε να χρησιμοποιήσετε την http://lists.FreeBSD.org/mailman/listinfo[διεπαφή Web του Mailman] για να γραφείτε σε οποιαδήποτε από τις δημόσιες λίστες. === Πως μπορώ να διαγραφώ; Με τον ίδιο τρόπο που εγγραφήκατε. Ή μπορείτε επίσης να ακολουθήσετε τις οδηγίες που βρίσκονται στο τέλος κάθε μηνύματος που στέλνει η λίστα. Σας παρακαλούμε μη στέλνετε μηνύματα διαγραφής απευθείας σε δημόσιες λίστες. Πρώτα από όλα, αυτό δεν θα επιτύχει το σκοπό σας, και δεύτερον θα εκνευρίσει τους υπάρχοντες συνδρομητές οι οποίοι θα λογομαχήσουν εναντίον σας. Πρόκειται για κλασικό λάθος κατά τη χρήση λιστών ταχυδρομείου και σας παρακαλούμε να προσπαθήσετε να το αποφύγετε. === Είναι διαθέσιμα τα αρχεία των λιστών; Ναι. Μπορείτε να τα βρείτε http://docs.FreeBSD.org/mail/[εδώ], ταξινομημένα κατά θέμα. === Είναι διαθέσιμες οι λίστες σε μορφή περίληψης; Ναι. Δείτε http://lists.FreeBSD.org/mailman/listinfo[τη διεπαφή web του Mailman]. [[etiquette]] [.title] == Συμπεριφορά (Etiquette) στις Λίστες Η συμμετοχή στις λίστες ηλεκτρονικού ταχυδρομείου, όπως και η συμμετοχή σε οποιαδήποτε κοινότητα, απαιτεί μια κοινή βάση επικοινωνίας. Σας παρακαλούμε να κάνετε μόνο κατάλληλες δημοσιεύσεις, και να ακολουθείτε τους κοινούς κανόνες συμπεριφοράς. === Τι πρέπει να κάνω πριν από μια δημοσίευση; Διαβάζοντας αυτό το κείμενο, έχετε ήδη κάνει το πιο σημαντικό βήμα. Ωστόσο, αν είστε νέος στο FreeBSD, θα πρέπει πρώτα να εξοικειωθείτε με το λογισμικό και όλη την κοινωνική ιστορία που το περιβάλλει, διαβάζοντας τα διάφορα link:https://www.FreeBSD.org/docs/books/[άρθρα και βιβλία] τα οποία είναι διαθέσιμα. Ιδιαίτερο ενδιαφέρον έχουν link:{faq}[Οι Συχνές Ερωτήσεις (FAQ) του FreeBSD], το link:{handbook}[Εγχειρίδιο του FreeBSD] καθώς και τα άρθρα link:{freebsd-questions}[Πως να χρησιμοποιείτε με επιτυχία τη λίστα ηλεκτρονικού ταχυδρομείου FreeBSD-questions], link:{explaining-bsd}[Περιγραφή των Συστημάτων BSD], και link:{new-users}[Για Χρήστες Νέους τόσο στο FreeBSD όσο και στο UNIX(R)]. Θεωρείται γενικά κακή συμπεριφορά να ρωτήσετε μια ερώτηση η οποία μπορεί να απαντηθεί από κάποιο από τα παραπάνω κείμενα. Αυτό δεν συμβαίνει επειδή οι εθελοντές που δουλεύουν σε αυτό το έργο είναι κακοί άνθρωποι, αλλά επειδή όταν έχουν απαντήσει την ίδια ερώτηση πολλές φορές, αρχίζει να τους ενοχλεί. Αυτό συμβαίνει ειδικά αν υπάρχει διαθέσιμη η απάντηση της ερώτησης. Να θυμάστε πάντα ότι σχεδόν όλη η δουλειά στο FreeBSD γίνεται από εθελοντές και τελικά είμαστε απλώς άνθρωποι. === Τι δημοσίευση μπορεί να θεωρηθεί ακατάλληλη; * Η δημοσίευση πρέπει να είναι σύμφωνη με τους κανονισμούς της λίστας. * Οι προσωπικές επιθέσεις είναι γενικά ανεπιθύμητες. Σαν καλοί διαδικτυακοί πολίτες, θα πρέπει να προσπαθούμε να κρατάμε υψηλά επίπεδα συμπεριφοράς. * Το spam δεν επιτρέπεται ποτέ. Γίνεται επεξεργασία στις λίστες για να απαγορευτούν οι δημοσιεύσεις σε όσους παραβαίνουν αυτό τον κανόνα. === Ποια θεωρείται σωστή συμπεριφορά στην αποστολή μηνυμάτων στις λίστες; * Παρακαλούμε να κάνετε αναδίπλωση των γραμμών κάθε 75 χαρακτήρες. Δεν χρησιμοποιούν όλοι GUI προγράμματα για να διαβάζουν το mail τους. * Παρακαλούμε σεβαστείτε το γεγονός ότι το εύρος ζώνης δεν είναι απεριόριστο. Δεν διαβάζει καθένας το email του μέσω συνδέσεων υψηλής ταχύτητας, έτσι αν το μήνυμα σας περιέχει κάτι σαν το περιεχόμενο του αρχείου [.filename]#config.log# ή ένα εκτεταμένο stack trace, σας παρακαλούμε να ανεβάσετε αυτές τις πληροφορίες σε κάποια δικτυακή τοποθεσία και να στείλετε ένα σύνδεσμο προς αυτές. Να θυμάστε επίσης ότι γίνεται αρχειοθέτηση αυτών των μηνυμάτων, έτσι αν στείλετε ένα τεράστιο μήνυμα θα μεγαλώσετε και το μέγεθος των αρχείων, ακόμα και όταν αυτές οι πληροφορίες δεν θα είναι πια χρήσιμες. * Μορφοποιήστε το μήνυμα σας ώστε να είναι ευανάγνωστο και σας παρακαλούμε ΜΗ ΦΩΝΑΖΕΤΕ!!!. Μην υποτιμάτε το αποτέλεσμα που θα έχει ένα φτωχά μορφοποιημένο μήνυμα, και αυτό δεν συμβαίνει μόνο στις λίστες του FreeBSD. Το μήνυμα σας είναι το μόνο που σας γνωστοποιεί στους υπόλοιπους ανθρώπους, και αν είναι άσχημα μορφοποιημένο, γεμάτο θαυμαστικά, θα αφήσει στους άλλους άσχημη εντύπωση για εσάς. * Χρησιμοποιήστε την κατάλληλη γλώσσα για τη λίστα ταχυδρομείου που πρόκειται να στείλετε μήνυμα. Μπορείτε να δείτε link:https://www.FreeBSD.org/community/mailinglists/[εδώ] τις λίστες που υπάρχουν σε γλώσσες εκτός της Αγγλικής. + Όσο αφορά τις Αγγλικές λίστες, αντιλαμβανόμαστε ότι για πολλούς η Αγγλική δεν είναι η μητρική τους γλώσσα και δείχνουμε κατανόηση. Θεωρείται κακή συμπεριφορά να κατακρίνετε όσους δεν έχουν τα Αγγλικά ως μητρική γλώσσα για λάθη γραμματικής ή ορθογραφίας. Το FreeBSD έχει μια πολύ καλή παράδοση σε αυτό το θέμα, σας παρακαλούμε να μας βοηθήσετε να τη διατηρήσουμε. * Παρακαλούμε χρησιμοποιήστε ένα πρόγραμμα αποστολής ταχυδρομείου (MUA) που να ακολουθεί σωστά τα πρότυπα. Πολλά από τα άσχημα μορφοποιημένα μηνύματα προέρχονται από http://www.lemis.com/email.html[κακής ποιότητας ή κακορυθμισμένα προγράμματα ταχυδρομείου]. Τα παρακάτω προγράμματα είναι γνωστό ότι στέλνουν προβληματικά μηνύματα, χωρίς εσείς να το γνωρίζετε: ** cc:Mail ** Eudora(R) (παλιότερες εκδόσεις) ** exmh ** Microsoft(R) Exchange ** Microsoft(R) Internet Mail ** Microsoft(R) Outlook(R) ** Netscape(R) (παλιότερες εκδόσεις) + Όπως μπορείτε να δείτε, πολλά από τα προβληματικά προγράμματα προέρχονται από τον κόσμο της Microsoft. Αν είναι δυνατόν χρησιμοποιήστε ένα πρόγραμμα που να προέρχεται από το UNIX(R). Αν πρέπει να χρησιμοποιήσετε ένα πρόγραμμα σε περιβάλλον Microsoft, φροντίστε να είναι ρυθμισμένο σωστά. Προσπαθήστε να μην χρησιμοποιήσετε MIME: αρκετός κόσμος χρησιμοποιεί προγράμματα ταχυδρομείου που δεν τα πάνε πολύ καλά με το MIME. * Βεβαιωθείτε ότι η ώρα και η ζώνη ώρας στον υπολογιστή σας είναι σωστά ρυθμισμένα. Αυτό μπορεί να φαίνεται κάπως ανόητο, ειδικά καθώς το μήνυμα σας θα φτάσει έτσι και αλλιώς, αλλά αρκετοί άνθρωποι σε αυτές τις λίστες λαμβάνουν εκατοντάδες μηνύματα κάθε μέρα. Συχνά τα ταξινομούν κατά θέμα και ημερομηνία, έτσι αν το μήνυμα σας έρθει μετά την πρώτη απάντηση θα θεωρήσουν ότι το έχασαν και δεν θα ασχοληθούν να το ψάξουν. * Πολλές φορές οι πληροφορίες που πρέπει να παρέχετε περιέχουν την έξοδο προγραμμάτων όπως το man:dmesg[8], ή τα μηνύματα που εμφανίζονται στην κονσόλα, τα οποία συνήθως γράφονται στο [.filename]#/var/log/messages#. Μην προσπαθήσετε να αντιγράψετε αυτές τις πληροφορίες πληκτρολογώντας τις ξανά: όχι μόνο είναι βασανιστικό, αλλά είναι σχεδόν σίγουρο ότι θα κάνετε κάποιο λάθος. Για να στείλετε τα περιεχόμενα κάποιου αρχείου καταγραφής, είτε αντιγράψτε το αρχείο και χρησιμοποιήστε κάποιο συντάκτη κειμένου για να κόψετε τα κομμάτια που σας ενδιαφέρουν, ή κάντε αποκοπή και επικόλληση μέσα στο μήνυμα σας. Για την έξοδο προγραμμάτων όπως το `dmesg`, χρησιμοποιήστε ανακατεύθυνση της εξόδου σε ένα αρχείο και στείλτε αυτό. Για παράδειγμα: + [source,bash] .... % dmesg > /tmp/dmesg.out .... + Το παραπάνω θα ανακατευθύνει τις πληροφορίες στο αρχείο [.filename]#/tmp/dmesg.out#. * Όταν χρησιμοποιείτε αποκοπή και επικόλληση να έχετε υπόψη σας ότι αυτές οι λειτουργίες μπορεί να καταστρέψουν το νόημα των μηνυμάτων. Αυτό συμβαίνει ιδιαίτερα όταν στέλνετε αρχεία όπως τα [.filename]#Makefiles#, όπου το `tab` είναι σημαντικός χαρακτήρας. Πρόκειται για πολύ κοινό και ενοχλητικό πρόβλημα ειδικά σε μηνύματα που απευθύνονται στη link:https://www.FreeBSD.org/support/gnats[Βάση Δεδομένων Προβλημάτων GNATS]. Τα [.filename]#Makefiles# όπου τα tabs έχουν αλλάξει είτε σε κενά ή στον ενοχλητικό χαρακτήρα `=3B` δημιουργούν πολλά ενοχλητικά προβλήματα στους committers. === Τι πρέπει να έχω υπόψη μου όσο αφορά τη συμπεριφορά στη λίστα όταν απαντάω σε κάποιο υπάρχον μήνυμα; * Παρακαλούμε να συμπεριλάβετε το σχετικό κείμενο από το αρχικό κείμενο. Περιορίστε το στο ελάχιστο, αλλά μη το παρακάνετε. Θα πρέπει κάποιος που δεν έχει δει το αρχικό μήνυμα να μπορεί να καταλάβει σε τι αναφέρεται η συζήτηση. + Αυτό είναι ιδιαίτερα σημαντικό σε μηνύματα του τύπου ""Ναι και σε μένα συμβαίνει το ίδιο"", όπου το αρχικό μήνυμα μπορεί να ήταν αρκετές δεκάδες ή εκατοντάδες γραμμές. * Χρησιμοποιήστε κάποια τεχνική με την οποία να γίνεται δυνατή η αναγνώριση του κειμένου που ανήκει στο αρχικό μήνυμα και του κειμένου που προσθέσατε. Μια συνηθισμένη σύμβαση είναι να χρησιμοποιείται το ""`> `"" μπροστά από το αρχικό μήνυμα. Είναι επίσης καλή ιδέα να αφήνετε κενό διάστημα μετά το ""`> `"" και κενές γραμμές ανάμεσα στο δικό σας και το αρχικό, ώστε το τελικό αποτέλεσμα να είναι πιο ευανάγνωστο. * Να βεβαιώνεστε πάντα ότι οι αναφορές στον αρχικό συγγραφέα του μηνύματος είναι σωστές. Συχνά οι άνθρωποι προσβάλλονται αν τους εμφανίζετε να έχουν γράψει λέξεις ενώ αυτό δεν συμβαίνει. * Παρακαλούμε μην κάνετε `top post`. Αυτό σημαίνει να μην ξεκινάτε την απάντηση σας πάνω από το κείμενο του μηνύματος στο οποίο απαντάτε. + ** Απ: Γιατί αντιστρέφει τη λογική ροή της συζήτησης. ** Ερ: Γιατί θεωρείται κακό το top posting; + (Ευχαριστούμε το Randy Bush για το ανέκδοτο.) [[recurring]] [.title] == Επαναλαμβανόμενα Θέματα στις Λίστες Ταχυδρομείου Η συμμετοχή στις λίστες ταχυδρομείου, όπως και η συμμετοχή σε κάθε κοινότητα, απαιτεί μια κοινή βάση επικοινωνίας. Πολλές από τις λίστες ταχυδρομείου προϋποθέτουν γνώση της ιστορίας του Project. Ειδικότερα, φαίνεται ότι κάποια θέματα προκύπτουν ξανά και ξανά στα νεώτερα μέλη της κοινότητας. Είναι ευθύνη του καθένα που συμμετέχει να φροντίζει ώστε τα μηνύματα του να μην εμπίπτουν σε κάποια από αυτές τις κατηγορίες. Με τον τρόπο αυτό, βοηθάτε τις λίστες ταχυδρομείου να μην ξεφεύγουν από το θέμα τους, και πιθανόν προφυλάσσετε και τον εαυτό σας από τυχόν λεκτικές επιθέσεις (flames). Η καλύτερη μέθοδος για να αποφύγετε το παραπάνω πρόβλημα είναι να εξοικειωθείτε με τα http://docs.FreeBSD.org/mail/[αρχεία των λιστών] για να μπορέσετε να καταλάβετε το ιστορικό της συζήτησης. Ιδιαίτερα χρήσιμη για αυτό το σκοπό θα σας φανεί και η link:https://www.FreeBSD.org/search/#mailinglists[λειτουργία αναζήτησης της λίστας]. (Αν η μέθοδος αυτή δεν φέρει το επιθυμητό αποτέλεσμα, συμπληρώστε την με μια αναζήτηση μέσω της μηχανής αναζήτησης που προτιμάτε). Όταν θα έχετε εξοικειωθεί με τα αρχεία της λίστας, όχι μόνο θα γνωρίζετε ποια θέματα έχουν συζητηθεί παλιότερα, αλλά και με ποιο τρόπο εξελίσσονται συνήθως οι συζητήσεις σε αυτή τη λίστα, ποιοι είναι οι συμμετέχοντες και σε ποιο κοινό απευθύνεται. Είναι πάντοτε καλό να γνωρίζετε εκ των προτέρων τα παραπάνω πριν στείλετε μήνυμα σε οποιαδήποτε λίστα (όχι μόνο του FreeBSD). Δεν υπάρχει αμφιβολία ότι τα αρχεία έχουν μεγάλη έκταση και μερικές ερωτήσεις φαίνονται να επαναλαμβάνονται πιο συχνά από άλλες, μερικές φορές σαν απαντήσεις όπου το θέμα που αναγράφεται στο μήνυμα δεν αντιπροσωπεύει πλέον το νέο περιεχόμενο. Ωστόσο πέφτει σε σας το βάρος να κάνετε όλη την εργασία που χρειάζεται ώστε να αποφύγετε αυτά τα επαναλαμβανόμενα θέματα. [[bikeshed]] [.title] == Τι είναι το ""Bikeshed""; Κυριολεκτικά το `bikeshed` είναι ένα μικρό εξωτερικό καταφύγιο όπου κάποιος μπορεί να φυλάξει το δίτροχο του (υπόστεγο ποδηλάτων). Στην ορολογία του FreeBSD ωστόσο, η λέξη αυτή χρησιμοποιείται για να αναφερόμαστε σε θέματα συζήτησης που είναι τόσο απλά ώστε (σχεδόν) καθένας να μπορεί να εκφέρει μια γνώμη για αυτά - και πολύ συχνά συμβαίνει ακριβώς αυτό. Η γέννηση αυτού του όρου εξηγείται με περισσότερη λεπτομέρεια σε link:{faq}#BIKESHED-PAINTING[αυτό το κείμενο]. Θα πρέπει να κατανοείτε την έννοια αυτού του όρου πριν αρχίσετε να στέλνετε μηνύματα σε οποιαδήποτε λίστα του FreeBSD. Πιο γενικά, το bikeshed είναι ένα θέμα το οποίο τείνει να δημιουργεί περισσότερες παράπλευρες συζητήσεις και λεκτικούς διαξιφισμούς, αν δεν έχετε διαβάσει σχετικά με την προϊστορία του. Σας παρακαλούμε να μας βοηθήσετε να κρατήσουμε τις λίστες ταχυδρομείου όσο το δυνατόν πιο χρήσιμες γίνεται για τον περισσότερο κόσμο, προσπαθώντας να αποφύγετε τα bikesheds όποτε είναι δυνατόν. Ευχαριστούμε! [[acknowledgments]] [.title] == Ευχαριστίες `{grog}`:: Ο αρχικός συγγραφέας του περισσότερου υλικού που αφορά τους κανονισμούς των λιστών, που προέρχονται από το άρθρο link:{freebsd-questions}[Πως να χρησιμοποιείτε με επιτυχία την λίστα ηλεκτρονικού ταχυδρομείου FreeBSD-questions]. `{linimon}`:: Δημιουργία του πρόχειρου αντίγραφου αυτού του FAQ. ",12246,True,3003.217983763436,median "class ZCL_GEOCODER_CES definition public final create public . public section. interfaces IF_GEOCODING_TOOL . class-data XNL type ABAP_CHAR1 value %_NEWLINE ##NO_TEXT. data JSON_DESERIALIZER type STRING value 'ABAP' ##NO_TEXT. methods HTTP_SEND importing !POST_DATA type STRING optional !URL type STRING optional !METHOD type STRING default 'GET' !HTTP_RFC_DEST type RFCDEST optional !FORM_FIELDS type TIHTTPNVP optional !CONTENT_TYPE type STRING optional exporting !HTTP_STATUS_CODE type I !HTTP_STATUS_MESSAGE type STRING value(RESPONSE_TEXT) type STRING exceptions SEND_ERROR RECEIVE_ERROR ERROR_CREATE_BY_URL ERROR_CREATE_BY_DEST PLEASE_SET_DESTINATION . class-methods GET_ABAP_REGION_BY_NAME importing !REGION type STRING !COUNTRY type LAND1 returning value(REG_CODE) type REGIO . class-methods GET_ABAP_REGION_BY_POSTALCODE importing !POSTALCODE type AD_PSTCD1 !COUNTRY type LAND1 optional returning value(REGION) type REGIO . protected section. methods GEOCODE_ONE_ADDRESS_GOOGLE importing !AES_ADDRESS type AES_ADDR !XINFO type GEOCDXINFO optional !ALT_STRING type STRING optional changing !RESULTS type GEOCD_RES_TABLE !CHOICE type GEOCD_CHOICE_TABLE !RELEVANT_FIELDS type GEOCD_ADDR_RELFIELDS_SORTEDTAB !MESSAGES type AES_MSG_TABLE !CONTAINERS type AESC_SORTEDTABLE !CORRECTED_ADDRESSES type AES_ADDR_SORTEDTABLE exceptions HTTP_SEND_ERROR JSON_PARSE_ERROR ZCX_JSON . methods GEOCODE_ONE_ADDRESS_HCPQM importing !AES_ADDRESS type AES_ADDR !XINFO type GEOCDXINFO optional !ALT_STRING type STRING optional changing !RESULTS type GEOCD_RES_TABLE !CHOICE type GEOCD_CHOICE_TABLE !RELEVANT_FIELDS type GEOCD_ADDR_RELFIELDS_SORTEDTAB !MESSAGES type AES_MSG_TABLE !CONTAINERS type AESC_SORTEDTABLE !CORRECTED_ADDRESSES type AES_ADDR_SORTEDTABLE exceptions HTTP_SEND_ERROR ZCX_JSON . private section. data HTTP_RFC_DEST type RFC_DEST . data GEOSERVICE type STRING value 'GOOGLE' ##NO_TEXT. data APIKEY type STRING . methods GET_CUSTOMIZING importing !SRCID type GEOSRCID exporting !RFC_DEST type RFCDEST !GEOSERVICE type STRING !APIKEY type STRING . methods SET_SAP_PRECISION importing !ACCURACY type I returning value(SAP_PRECISION) type STRING . methods PARSE_GMAPS_JSON importing !JSON_TEXT type STRING exporting !GEOCODE_HEADER type GEOCODE_HEADER_TYPE !PLACEMARKS type PLACEMARK_TTAB exceptions JSON_PARSE_ERROR ZCX_JSON . methods DESERIALIZE_JSON importing !JSON_STRING type STRING !DATA_TYPE type STRING optional changing value(ABAP_DATA) type ANY raising ZCX_JSON . ENDCLASS. CLASS ZCL_GEOCODER_CES IMPLEMENTATION. method DESERIALIZE_JSON. type-pools: abap. data: rtab type abap_trans_resbind_tab, rlin type abap_trans_resbind, oexcp type ref to cx_root, etext type string, json_xtext type xstring, json_text type string. data: datadesc type ref to cl_abap_typedescr, strudesc type ref to cl_abap_structdescr, l_comp type line of abap_compdescr_tab, dataref type ref to data. field-symbols: type any. break-point id z_cesar. case me->json_deserializer. when 'ABAP'. call method zcl_json_handler=>json2abap exporting json_string = json_string changing abap_data = abap_data. when 'TRID'. "" First, built table rtab for id transformation strudesc ?= cl_abap_structdescr=>describe_by_data( abap_data ). loop at strudesc->components into l_comp. rlin-name = l_comp-name. assign component l_comp-name of structure abap_data to . get reference of into dataref. rlin-value = dataref. append rlin to rtab. clear rlin. clear dataref. endloop. "" Second, convert JSON variable names to upper case. json_xtext = cl_abap_codepage=>convert_to( json_string ). data(reader) = cl_sxml_string_reader=>create( json_xtext ). data(writer) = cast if_sxml_writer( cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ) ). do. data(node) = reader->read_next_node( ). if node is initial. exit. endif. if node->type = if_sxml_node=>co_nt_element_open. data(attributes) = cast if_sxml_open_element( node )->get_attributes( ). loop at attributes assigning field-symbol(). if ->qname-name = 'name'. ->set_value( to_upper( ->get_value( ) ) ). endif. endloop. endif. writer->write_node( node ). enddo. break-point id z_cesar. json_xtext = cast cl_sxml_string_writer( writer )->get_output( ) . json_text = cl_abap_codepage=>convert_from( json_xtext ). try. "" Then, do the transformation: call transformation id source xml json_text result (rtab). catch cx_root into oexcp. etext = oexcp->if_message~get_text( ). raise exception type zcx_json exporting message = etext. endtry. when others. endcase. break-point id z_cesar. endmethod. method GEOCODE_ONE_ADDRESS_GOOGLE. data: lv_address type adrc_struc, lv_result type geocd_ress, lv_choice type geocd_choi, lv_aesc type aesc_tabs, lv_message type aes_msg, aesc_container type aesc, ls_container type line of aesc_sortedtable, corr_address type line of aes_addr_sortedtable, wa_aesc type aesc_struc. data: lv_address_query type string, "" Parámetro address para google maps form_fields type tihttpnvp, waff type ihttpnvp, jsonresp type string, * cxmlresp type xstring, geocode_header type geocode_header_type, placemarks type placemark_ttab, wa_placemark type line of placemark_ttab, lv_timezone_r3 type timezone, lv_timestamp type timestamp, abap_country type land1, str_country type landx, iso_country type intca, li type i, idx type i. if alt_string is not initial. lv_address_query = alt_string. else. if aes_address-address-street is not initial. * concatenate aes_address-address-street ' ' into lv_address_query. lv_address_query = aes_address-address-street. endif. if aes_address-address-house_num1 is not initial. concatenate lv_address_query aes_address-address-house_num1 into lv_address_query separated by space. endif. if aes_address-address-post_code1 is not initial. concatenate lv_address_query aes_address-address-post_code1 into lv_address_query separated by space. endif. if aes_address-address-city1 is not initial. concatenate lv_address_query aes_address-address-city1 into lv_address_query separated by space. endif. if aes_address-address-country is not initial. call function 'DR_GET_COUNTRY_NAME' EXPORTING country = aes_address-address-country language = 'E' IMPORTING name = str_country. concatenate lv_address_query str_country into lv_address_query separated by space. endif. endif. * Conecta con google waff-name = 'key'. waff-value = me->apikey. append waff to form_fields. clear waff. waff-name = 'address'. waff-value = lv_address_query. append waff to form_fields. clear waff. ** Google option for components=country: waff-name = 'components'. concatenate 'country' aes_address-address-country into waff-value separated by ':'. append waff to form_fields. clear waff. call method me->http_send exporting * POST_DATA = * URL = method = 'GET' http_rfc_dest = me->http_rfc_dest form_fields = form_fields importing * HTTP_STATUS_CODE = * HTTP_STATUS_MESSAGE = response_text = jsonresp exceptions send_error = 1 receive_error = 2 error_create_by_url = 3 error_create_by_dest = 4 please_set_destination = 5 others = 6. if sy-subrc <> 0. raise http_send_error. endif. * * data conv type ref to CL_ABAP_CONV_IN_CE. * data xlen type i. * conv = CL_ABAP_CONV_IN_CE=>create( encoding = 'UTF-8' ). "" ISO-8859-1 * conv->convert( exporting input = cxmlresp importing data = xmlresp len = xlen ). * Parse google geocode JSON results call method me->parse_gmaps_json EXPORTING json_text = jsonresp IMPORTING geocode_header = geocode_header placemarks = placemarks EXCEPTIONS json_parse_error = 1. if sy-subrc <> 0. raise json_parse_error. endif. * Prepara result y choices, solo si google devuelve OK lv_result-id = aes_address-id. lv_result-info = geocode_header-status. if geocode_header-status eq 'OK'. describe table placemarks lines li. * Dominio de valores para res: *0 Geocodificación con éxito. Resultado unívoco. *1 Geocodificación innecesaria (ninguna modificación relevante) *2 Resultado no unívoco. La mejor selección (proceso de fondo) *3 Resultado no unívoco. Existe selección de dirección. *4 Resultado no unívoco. Ning.selección dirección (demasiados) *5 Geocodificación no ha tenido éxito. Lon=Lat=Alt=invariable *6 Herramienta no competente. Lon=Lat=Alt=invariable. if li eq 1. lv_result-res = 0. lv_result-info = 'Univoque Address'. elseif li gt 1. lv_result-res = 3. lv_result-info = 'Multiple Choice'. else. lv_result-res = 5. lv_result-info = 'Cannot Geocode Address'. endif. idx = 0. loop at placemarks into wa_placemark. add 1 to idx. lv_address = aes_address-address. ls_container-id = aes_address-id. lv_choice-id = aes_address-id. lv_choice-ranking = idx. lv_choice-percentage = '100'. * Longitud y latitud y otros datos de geocodificación wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'SRCID'. wa_aesc-value = xinfo-srcid. append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'LONGITUDE'. wa_aesc-value = wa_placemark-longitude. append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'LATITUDE'. wa_aesc-value = wa_placemark-latitude. append wa_aesc to aesc_container. clear wa_aesc. * wa_aesc-service = 'GEOCODING'. * wa_aesc-field = 'ALTITUDE'. * wa_aesc-value = wa_placemark-altitude. * append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'PRECISID'. wa_aesc-value = wa_placemark-accuracy. "" Use google accuracy for that???? append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'TZONE'. * take the r/3 timezone for country data country type land1. country = wa_placemark-country. call function 'TZON_LOCATION_TIMEZONE' EXPORTING if_country = country IMPORTING ef_timezone = lv_timezone_r3 EXCEPTIONS no_timezone_found = 1 others = 2. if sy-subrc eq 0. wa_aesc-value = lv_timezone_r3. endif. append wa_aesc to aesc_container. clear wa_aesc. * Timestamp geocoding get time stamp field lv_timestamp. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'SRCTSTMP'. wa_aesc-value = lv_timestamp. append wa_aesc to aesc_container. clear wa_aesc. ls_container-container = aesc_container. * add container to Choices Dialog lv_choice-container = aesc_container. lv_address-city1 = wa_placemark-locality. lv_address-city2 = wa_placemark-distrito. lv_address-post_code1 = wa_placemark-postalcodenumber. lv_address-street = wa_placemark-street. lv_address-house_num1 = wa_placemark-street_number. iso_country = wa_placemark-country. call function 'COUNTRY_CODE_ISO_TO_SAP_ABA' exporting iso_code = iso_country importing sap_code = abap_country * NOT_UNIQUE = exceptions not_found = 1 others = 2. if sy-subrc eq 0. lv_address-country = abap_country. endif. lv_address-region = get_abap_region_by_name( REGION = wa_placemark-provincia_name COUNTRY = abap_country ). if lv_address-region is initial. lv_address-region = get_abap_region_by_postalcode( postalcode = lv_address-post_code1 country = abap_country ). endif. lv_choice-address = lv_address. lv_choice-addr_short = wa_placemark-fulladdress. append lv_choice to choice. "" Solo si el resultado es unívoco devuelve containers y dirección corregida if lv_result-res = 0. modify table containers from ls_container. corr_address-id = aes_address-id. corr_address-address = lv_address. append corr_address to corrected_addresses. endif. ""lv_result-res = 0 break-point id z_cesar. "" Y borras variables temporales clear corr_address. clear lv_choice. clear lv_address. clear ls_container. clear aesc_container. endloop. "" Placemarks else. "" Google Status other than OK *5 Geocodificación no ha tenido éxito. Lon=Lat=Alt=invariable * lv_result-res = 5. lv_result-res = 6. lv_result-info = 'Failed Geocoding'. endif. "" Google Status OK append lv_result to results. endmethod. method GEOCODE_ONE_ADDRESS_HCPQM. data: lv_address type adrc_struc, lv_result type geocd_ress, lv_choice type geocd_choi, lv_aesc type aesc_tabs, lv_message type aes_msg, aesc_container type aesc, ls_container type line of aesc_sortedtable, corr_address type line of aes_addr_sortedtable, wa_aesc type aesc_struc. data: lv_address_query type string, "" Parámetro address para google maps form_fields type tihttpnvp, waff type ihttpnvp, jsontext type string, jsonquery type string, jsonresp type string, * cxmlresp type xstring, geocode_header type geocode_header_type, placemarks type placemark_ttab, wa_placemark type line of placemark_ttab, lv_timezone_r3 type timezone, lv_timestamp type timestamp, abap_country type land1, str_country type landx, iso_country type intca, li type i, idx type i, http_status_code type i, http_status_msg type string. * Prepare JSON query data: addressinput type hcp_query_addrinput. data: outputfields type stringtab. data: hcpresponse type hcp_response. append 'addr_latitude' to outputfields. append 'addr_longitude' to outputfields. append 'geo_asmt_level' to outputfields. append 'geo_info_code' to outputfields. append 'geo_info_code_msg' to outputfields. append 'std_addr_prim_name1_4' to outputfields. append 'std_addr_prim_number_full' to outputfields. append 'std_addr_secaddr_no_floor_room' to outputfields. append 'std_addr_floor_number' to outputfields. append 'std_addr_room_number' to outputfields. append 'std_addr_building_name1_2' to outputfields. append 'addr_remainder_extra_pmb_full' to outputfields. append 'std_addr_point_of_ref1_2' to outputfields. append 'std_addr_locality3_4_full' to outputfields. append 'std_addr_locality_full' to outputfields. append 'std_addr_locality2_full' to outputfields. append 'std_addr_region_full' to outputfields. append 'std_addr_postcode_full' to outputfields. append 'std_addr_country_2char' to outputfields. append 'std_addr_po_box_number' to outputfields. append 'std_addr_po_box_locality_full' to outputfields. append 'std_addr_po_box_region_full' to outputfields. append 'std_addr_po_box_postcode_full' to outputfields. append 'std_addr_po_box_country_2char' to outputfields. append 'addr_info_code' to outputfields. append 'addr_info_code_msg' to outputfields. append 'addr_po_box_info_code' to outputfields. append 'addr_po_box_info_code_msg' to outputfields. * Fill address input addressinput-street = aes_address-address-street. addressinput-house_num = aes_address-address-house_num1. addressinput-locality = aes_address-address-city1. addressinput-postcode = aes_address-address-post_code1. addressinput-country = aes_address-address-country. * Prepare post json query jsonquery = zcl_json_handler=>abap2json( name = 'addressInput' abap_data = addressinput ). jsontext = zcl_json_handler=>abap2json( name = 'outputFields' abap_data = outputfields ). concatenate '{' jsonquery ',' jsontext '}' into jsonquery. break-point id z_cesar. call method me->http_send exporting POST_DATA = jsonquery * URL = method = 'POST' http_rfc_dest = me->http_rfc_dest content_type = 'application/json' * form_fields = form_fields importing HTTP_STATUS_CODE = http_status_code HTTP_STATUS_MESSAGE = http_status_msg response_text = jsonresp exceptions send_error = 1 receive_error = 2 error_create_by_url = 3 error_create_by_dest = 4 please_set_destination = 5 others = 6. if sy-subrc <> 0. raise http_send_error. endif. break-point id z_cesar. deserialize_json( exporting json_string = jsonresp changing abap_data = hcpresponse ). break-point id z_cesar. * HCP indicates success by 200 at HTTP status level if http_status_code eq 200. "" HCP only returns unique address, no multiple lists lv_result-res = 0. lv_result-info = 'Univoque Address'. lv_address = aes_address-address. ls_container-id = aes_address-id. lv_choice-id = aes_address-id. lv_choice-ranking = 1. lv_choice-percentage = '100'. * Set longitude, latitude and others wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'SRCID'. wa_aesc-value = xinfo-srcid. append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'LONGITUDE'. wa_aesc-value = hcpresponse-addr_longitude. append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'LATITUDE'. wa_aesc-value = hcpresponse-addr_latitude. append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'PRECISID'. wa_aesc-value = hcpresponse-geo_asmt_level. "" Use google accuracy for that???? append wa_aesc to aesc_container. clear wa_aesc. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'TZONE'. * take the r/3 timezone for country data country type land1. country = wa_placemark-country. call function 'TZON_LOCATION_TIMEZONE' EXPORTING if_country = country IMPORTING ef_timezone = lv_timezone_r3 EXCEPTIONS no_timezone_found = 1 others = 2. if sy-subrc eq 0. wa_aesc-value = lv_timezone_r3. endif. append wa_aesc to aesc_container. clear wa_aesc. * Timestamp geocoding get time stamp field lv_timestamp. wa_aesc-service = 'GEOCODING'. wa_aesc-field = 'SRCTSTMP'. wa_aesc-value = lv_timestamp. append wa_aesc to aesc_container. clear wa_aesc. ls_container-container = aesc_container. lv_choice-container = aesc_container. lv_address-city1 = hcpresponse-std_addr_locality_full. * lv_address-city2 = wa_placemark-distrito. lv_address-post_code1 = hcpresponse-std_addr_postcode_full. lv_address-street = hcpresponse-std_addr_prim_name1_4. lv_address-house_num1 = hcpresponse-std_addr_prim_number_full. iso_country = hcpresponse-std_addr_country_2char. call function 'COUNTRY_CODE_ISO_TO_SAP_ABA' exporting iso_code = iso_country importing sap_code = abap_country * NOT_UNIQUE = exceptions not_found = 1 others = 2. if sy-subrc eq 0. lv_address-country = abap_country. endif. lv_address-region = get_abap_region_by_name( REGION = hcpresponse-std_addr_region_full COUNTRY = abap_country ). if lv_address-region is initial. lv_address-region = get_abap_region_by_postalcode( postalcode = lv_address-post_code1 country = abap_country ). endif. lv_choice-address = lv_address. lv_choice-addr_short = lv_address-street. append lv_choice to choice. "" Solo si el resultado es unívoco devuelve containers y dirección corregida if lv_result-res = 0. modify table containers from ls_container. corr_address-id = aes_address-id. corr_address-address = lv_address. append corr_address to corrected_addresses. endif. ""lv_result-res = 0 append lv_result to results. endif. endmethod. method GET_ABAP_REGION_BY_NAME. types: begin of reglist_type, bezei type string, bland type regio, end of reglist_type. data reglist type hashed table of reglist_type with unique key bezei. field-symbols type reglist_type. select * from T005U into corresponding fields of table reglist where land1 eq country and spras eq SY-LANGU. if sy-subrc eq 0. read table reglist with table key bezei = region assigning . if sy-subrc eq 0. reg_code = -bland. endif. endif. endmethod. method GET_ABAP_REGION_BY_POSTALCODE. "" Get region from postal code "" It only works like this in France and Spain: (AFAIK) "" The first two digits indicate the 'département' (France) or ""provicia"" (Spain). data(pcode) = postalcode. condense pcode. if strlen( pcode ) eq 5. region = substring( val = pcode off = 0 len = 2 ). endif. endmethod. method GET_CUSTOMIZING. data: lv_geocd2cls type geocd2cls. * read http rfc dest from customizing select single * from geocd2cls into lv_geocd2cls where srcid = srcid. if sy-subrc ne 0. * if nothing found set a ""sensible"" default rfc_dest = 'HTTP_GMAPS_GEOCODE_SIM'. geoservice = 'GOOGLE'. exit. else. rfc_dest = lv_geocd2cls-rfc_dest. if lv_geocd2cls-funcname is not initial. geoservice = lv_geocd2cls-funcname. translate geoservice to upper case. endif. apikey = lv_geocd2cls-infostring. endif. endmethod. method HTTP_SEND. data client type ref to if_http_client. data destination(255) type c. data errcode type sysubrc. data errmesg type string. data oref type ref to cx_root. if http_rfc_dest is not initial. destination = http_rfc_dest. call method cl_http_client=>create_by_destination exporting destination = destination importing client = client exceptions argument_not_found = 1 destination_not_found = 2 destination_no_authority = 3 plugin_not_active = 4 internal_error = 5 others = 6. if sy-subrc <> 0. raise error_create_by_dest. endif. elseif url is not initial. call method cl_http_client=>create_by_url exporting url = url * PROXY_HOST = * PROXY_SERVICE = * SSL_ID = * SAP_USERNAME = * SAP_CLIENT = importing client = client exceptions argument_not_found = 1 plugin_not_active = 2 internal_error = 3 others = 4 . if sy-subrc <> 0. raise error_create_by_url. endif. else. raise please_set_destination. endif. client->request->set_method( method ). if method eq 'POST' and post_data is not initial. client->request->set_cdata( post_data ). if content_type is not initial. client->request->set_content_type( content_type ). endif. endif. if form_fields is not initial. client->request->set_form_fields( form_fields ). endif. try. client->send( ). catch cx_root into oref. endtry. client->get_last_error( importing code = errcode message = errmesg ). if errcode ne 0. raise send_error. endif. try. client->receive( ). catch cx_root into oref. endtry. client->get_last_error( importing code = errcode message = errmesg ). if errcode ne 0. raise receive_error. endif. client->response->get_status( importing code = http_status_code reason = http_status_message ). response_text = client->response->get_cdata( ). endmethod. method IF_GEOCODING_TOOL~GEOCODE. break-point id z_cesar. data method_name type string. data: lv_aes_address type aes_addr. * Get HTTP rfc destination from customizing: get_customizing( exporting srcid = xinfo-srcid importing rfc_dest = me->http_rfc_dest geoservice = me->geoservice apikey = me->apikey ). * Set method for geoservice: concatenate 'GEOCODE_ONE_ADDRESS_' me->geoservice into method_name. * Process addresses: loop at addresses into lv_aes_address. * geocode addresses one by one call method (method_name) exporting aes_address = lv_aes_address xinfo = xinfo changing results = results choice = choice relevant_fields = relevant_fields messages = messages containers = containers corrected_addresses = corrected_addresses. endloop. endmethod. method PARSE_GMAPS_JSON. data google_results type zgoogle_results_type. data grestabfortrid type table of zgoogle_results_type. data res_wa type ZGOOGLE_RESULTS_ITEM. data adc_wa type ZGOOGLE_ADDCOMP_ITEM. data res_type type string. "" result types data adc_type type string. "" address components types data wa_placemark type line of placemark_ttab. * Process Google returned JSON: CALL METHOD ME->DESERIALIZE_JSON EXPORTING JSON_STRING = json_text DATA_TYPE = 'ZGOOGLE_RESULTS_TYPE' CHANGING ABAP_DATA = google_results. geocode_header-status = google_results-status. geocode_header-error_message = google_results-error_message. if google_results-status ne 'OK'. exit. endif. loop at google_results-results into res_wa. wa_placemark-id = res_wa-place_id. wa_placemark-fulladdress = res_wa-formatted_address. wa_placemark-accuracy = res_wa-geometry-location_type. wa_placemark-longitude = res_wa-geometry-location-lng. wa_placemark-latitude = res_wa-geometry-location-lat. find first occurrence of 'street_address' in table res_wa-types. if sy-subrc eq 0. "" process it, it looks like a street address loop at res_wa-address_components into adc_wa. data adcomp type string. read table adc_wa-types index 1 into adcomp. if adcomp eq 'political'. read table adc_wa-types index 2 into adcomp. endif. case adcomp. when 'street_number'. wa_placemark-street_number = adc_wa-long_name. when 'route'. wa_placemark-street = adc_wa-long_name. when 'locality'. wa_placemark-locality = adc_wa-long_name. when 'administrative_area_level_2'. wa_placemark-provincia = adc_wa-short_name. wa_placemark-provincia_name = adc_wa-long_name. when 'administrative_area_level_1'. wa_placemark-comunidad = adc_wa-long_name. when 'country'. wa_placemark-country = adc_wa-short_name. wa_placemark-country_name = adc_wa-long_name. when 'postal_code'. wa_placemark-postalcodenumber = adc_wa-long_name. endcase. endloop. endif. append wa_placemark to placemarks. clear wa_placemark. endloop. endmethod. method SET_SAP_PRECISION. * This method sets SAP APO defined precission codes * for geocoding, as defined in a SAP APO system. * The mapping is a bit ""subjective"" as there is not one-to-one correspondence. * It is not always possible to map service accuracy to APO precision. * SAP precission codes (in APO system): *0000 No existen datos *0100 Mundo *0200 Continente *0300 País *0400 Región *0500 Límite de municipio *0600 Código postal *0700 Población *0800 Distrito *0900 Punto medio de calle *1000 Punto medio rango números casas (sección de calle) *1100 Número casa (interpolado) *1200 Número casa (exacto) *1300 Número casa c/suplemento (p. ej., Neurottstr.7b) case accuracy. when 0. sap_precision = '0000'. when 1. sap_precision = '0300'. when 2. sap_precision = '0400'. when 3. sap_precision = '0500'. when 4. sap_precision = '0700'. when 5. sap_precision = '0600'. when 6. sap_precision = '0900'. when 7. sap_precision = '1000'. when 8 or 9. sap_precision = '1300'. when others. "" which others? endcase. endmethod. ENDCLASS. ",7803,False,1505.0355720585828,median "= v1.RoleBinding {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] RoleBinding references a role, but does not contain it. It can reference a Role in the same namespace or a ClusterRole in the global namespace. It adds who information via Subjects and namespace information by which namespace it exists in. RoleBindings in a given namespace only have effect in that namespace. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
roleRef:
apiGroup:
kind:
name:
subjects:
- apiGroup:
kind:
name:
namespace:
++++ == Operations [[Post-apis-rbac.authorization.k8s.io-v1-rolebindings]] === Create a RoleBinding Create a RoleBinding ==== HTTP request ---- POST /apis/rbac.authorization.k8s.io/v1/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""RoleBinding"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/rolebindings <<'EOF' { ""kind"": ""RoleBinding"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.RoleBinding |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBinding |201 Created|v1.RoleBinding |202 Accepted|v1.RoleBinding |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings]] === Create a RoleBinding in a namespace Create a RoleBinding ==== HTTP request ---- POST /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""RoleBinding"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings <<'EOF' { ""kind"": ""RoleBinding"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.RoleBinding |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBinding |201 Created|v1.RoleBinding |202 Accepted|v1.RoleBinding |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings-name]] === Get a RoleBinding in a namespace Read the specified RoleBinding ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the RoleBinding |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBinding |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-rbac.authorization.k8s.io-v1-rolebindings]] === Get all RoleBindings List or watch objects of kind RoleBinding ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/rolebindings ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBindingList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings]] === Get all RoleBindings in a namespace List or watch objects of kind RoleBinding ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBindingList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-watch-namespaces-namespace-rolebindings-name]] === Watch a RoleBinding in a namespace Watch changes to an object of kind RoleBinding ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/rolebindings/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/rolebindings/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the RoleBinding |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-watch-rolebindings]] === Watch all RoleBindings Watch individual changes to a list of RoleBinding ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/watch/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/watch/rolebindings ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-watch-namespaces-namespace-rolebindings]] === Watch all RoleBindings in a namespace Watch individual changes to a list of RoleBinding ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/rolebindings ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings-name]] === Update a RoleBinding in a namespace Replace the specified RoleBinding ==== HTTP request ---- PUT /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""RoleBinding"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME <<'EOF' { ""kind"": ""RoleBinding"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.RoleBinding |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the RoleBinding |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBinding |201 Created|v1.RoleBinding |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings-name]] === Patch a RoleBinding in a namespace Partially update the specified RoleBinding ==== HTTP request ---- PATCH /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the RoleBinding |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleBinding |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings-name]] === Delete a RoleBinding in a namespace Delete a RoleBinding ==== HTTP request ---- DELETE /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the RoleBinding |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-rolebindings]] === Delete all RoleBindings in a namespace Delete collection of RoleBinding ==== HTTP request ---- DELETE /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12523,False,2439.543710658294,median "CLASS zcl_otlp_encode_trace DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. * MIT License, Copyright (c) 2022 Heliconia Labs * https://github.com/heliconialabs/abap-opentelemetry CLASS-METHODS encode IMPORTING !it_resource_spans TYPE zif_otlp_model_trace=>ty_resource_spans RETURNING VALUE(rv_hex) TYPE xstring . PROTECTED SECTION. CLASS-METHODS to_xstring IMPORTING !iv_string TYPE string RETURNING VALUE(rv_xstring) TYPE xstring . CLASS-METHODS encode_resource_spans IMPORTING !is_resource_spans TYPE zif_otlp_model_trace=>ty_resource_span RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_scope_spans IMPORTING !is_scope_spans TYPE zif_otlp_model_trace=>ty_scope_spans RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_instrumentation_scope IMPORTING !is_instrumentation_scope TYPE zif_otlp_model_common=>ty_instrumentation_scope RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_span IMPORTING !is_span TYPE zif_otlp_model_trace=>ty_span RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_resource IMPORTING !is_resource TYPE zif_otlp_model_resource=>ty_resource RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_key_value IMPORTING !is_key_value TYPE zif_otlp_model_common=>ty_key_value RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_any_value IMPORTING !is_any_value TYPE zif_otlp_model_common=>ty_any_value RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_status IMPORTING !is_status TYPE zif_otlp_model_trace=>ty_status RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_link IMPORTING !is_link TYPE zif_otlp_model_trace=>ty_link RETURNING VALUE(rv_hex) TYPE xstring . CLASS-METHODS encode_event IMPORTING !is_event TYPE zif_otlp_model_trace=>ty_event RETURNING VALUE(rv_hex) TYPE xstring . PRIVATE SECTION. ENDCLASS. CLASS ZCL_OTLP_ENCODE_TRACE IMPLEMENTATION. METHOD encode. DATA(lo_stream) = NEW lcl_protobuf_stream( ). * top level, message TracesData LOOP AT it_resource_spans INTO DATA(ls_resource_span). lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_resource_spans( ls_resource_span ) ). ENDLOOP. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_any_value. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_any_value-string_value IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_any_value-string_value ) ). ELSEIF is_any_value-bool_value IS NOT INITIAL. ASSERT 1 = 'todo'. ELSEIF is_any_value-int_value IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_any_value-int_value ). ELSEIF is_any_value-double_value IS NOT INITIAL. ASSERT 1 = 'out of scope'. ELSEIF is_any_value-array_value IS NOT INITIAL. ASSERT 1 = 'out of scope'. ELSEIF is_any_value-kvlist_value IS NOT INITIAL. ASSERT 1 = 'out of scope'. ELSEIF is_any_value-bytes_value IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 7 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( is_any_value-bytes_value ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_event. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_event-time_unix_nano IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-bit64 ) ). lo_stream->encode_fixed64( is_event-time_unix_nano ). ENDIF. IF is_event-name IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_event-name ) ). ENDIF. LOOP AT is_event-attributes INTO DATA(ls_attribute). lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_key_value( ls_attribute ) ). ENDLOOP. IF is_event-dropped_attributes_count IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 4 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_event-dropped_attributes_count ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_instrumentation_scope. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_instrumentation_scope-name IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_instrumentation_scope-name ) ). ENDIF. IF is_instrumentation_scope-version IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_instrumentation_scope-version ) ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_key_value. DATA(lo_stream) = NEW lcl_protobuf_stream( ). lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_key_value-key ) ). lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_any_value( is_key_value-value ) ). rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_link. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_link-trace_id IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( is_link-trace_id ). ENDIF. IF is_link-span_id IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( is_link-span_id ). ENDIF. lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_link-trace_state ) ). LOOP AT is_link-attributes INTO DATA(ls_attribute). lo_stream->encode_field_and_type( VALUE #( field_number = 4 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_key_value( ls_attribute ) ). ENDLOOP. IF is_link-dropped_attributes_count IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 5 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_link-dropped_attributes_count ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_resource. DATA(lo_stream) = NEW lcl_protobuf_stream( ). LOOP AT is_resource-attributes INTO DATA(ls_attribute). lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_key_value( ls_attribute ) ). ENDLOOP. IF is_resource-dropped_attributes_count IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_resource-dropped_attributes_count ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_resource_spans. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_resource_spans-resource IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_resource( is_resource_spans-resource ) ). ENDIF. LOOP AT is_resource_spans-scope_spans INTO DATA(ls_scope_spans). lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_scope_spans( ls_scope_spans ) ). ENDLOOP. IF is_resource_spans-schema_url IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_resource_spans-schema_url ) ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_scope_spans. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_scope_spans-scope IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_instrumentation_scope( is_scope_spans-scope ) ). ENDIF. LOOP AT is_scope_spans-spans INTO DATA(ls_span). lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_span( ls_span ) ). ENDLOOP. IF is_scope_spans-schema_url IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_scope_spans-schema_url ) ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_span. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_span-trace_id IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 1 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( is_span-trace_id ). ENDIF. IF is_span-span_id IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( is_span-span_id ). ENDIF. IF is_span-trace_state IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_span-trace_state ) ). ENDIF. IF is_span-parent_span_id IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 4 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( is_span-parent_span_id ). ENDIF. IF is_span-name IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 5 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_span-name ) ). ENDIF. IF is_span-kind IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 6 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_span-kind ). ENDIF. IF is_span-start_time_unix_nano IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 7 wire_type = lcl_protobuf_stream=>gc_wire_type-bit64 ) ). lo_stream->encode_fixed64( is_span-start_time_unix_nano ). ENDIF. IF is_span-end_time_unix_nano IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 8 wire_type = lcl_protobuf_stream=>gc_wire_type-bit64 ) ). lo_stream->encode_fixed64( is_span-end_time_unix_nano ). ENDIF. LOOP AT is_span-attributes INTO DATA(ls_attribute). lo_stream->encode_field_and_type( VALUE #( field_number = 9 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_key_value( ls_attribute ) ). ENDLOOP. IF is_span-dropped_attributes_count IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 10 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_span-dropped_attributes_count ). ENDIF. LOOP AT is_span-events INTO DATA(ls_event). lo_stream->encode_field_and_type( VALUE #( field_number = 11 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_event( ls_event ) ). ENDLOOP. IF is_span-dropped_events_count IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 12 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_span-dropped_events_count ). ENDIF. LOOP AT is_span-links INTO DATA(ls_link). lo_stream->encode_field_and_type( VALUE #( field_number = 13 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_link( ls_link ) ). ENDLOOP. IF is_span-dropped_links_count IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 14 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_span-dropped_links_count ). ENDIF. IF is_span-status IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 14 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( encode_status( is_span-status ) ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD encode_status. DATA(lo_stream) = NEW lcl_protobuf_stream( ). IF is_status-message IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 2 wire_type = lcl_protobuf_stream=>gc_wire_type-length_delimited ) ). lo_stream->encode_delimited( to_xstring( is_status-message ) ). ENDIF. IF is_status-code IS NOT INITIAL. lo_stream->encode_field_and_type( VALUE #( field_number = 3 wire_type = lcl_protobuf_stream=>gc_wire_type-varint ) ). lo_stream->encode_varint( is_status-code ). ENDIF. rv_hex = lo_stream->get( ). ENDMETHOD. METHOD to_xstring. * argh, steampunk compatibility DATA lo_conv TYPE REF TO object. TRY. CALL METHOD ('CL_ABAP_CONV_CODEPAGE')=>create_out RECEIVING instance = lo_conv. CALL METHOD lo_conv->('IF_ABAP_CONV_OUT~CONVERT') EXPORTING source = iv_string RECEIVING result = rv_xstring. CATCH cx_sy_dyn_call_illegal_class. DATA(lv_conv_out_class) = 'CL_ABAP_CONV_OUT_CE'. * workaround for not triggering static analysis error in Steampunk CALL METHOD (lv_conv_out_class)=>create EXPORTING encoding = 'UTF-8' RECEIVING conv = lo_conv. CALL METHOD lo_conv->('CONVERT') EXPORTING data = iv_string IMPORTING buffer = rv_xstring. ENDTRY. ENDMETHOD. ENDCLASS. ",4151,False,1233.3300885356957,median "[[debezium-mysql-component]] = Debezium MySQL Connector Component :docTitle: Debezium MySQL Connector :artifactId: camel-debezium-mysql :description: Capture changes from a MySQL database. :since: 3.0 :supportLevel: Stable :component-header: Only consumer is supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/debezium-mysql.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Debezium MySQL component is wrapper around https://debezium.io/[Debezium] using https://debezium.io/documentation/reference/0.9/operations/embedded.html[Debezium Embedded], which enables Change Data Capture from MySQL database using Debezium without the need for Kafka or Kafka Connect. *Note on handling failures:* Per https://debezium.io/documentation/reference/0.9/operations/embedded.html#_handling_failures[Debezium Embedded Engine] documentation, the engines is actively recording source offsets and periodically flushes these offsets to a persistent storage, so when the application is restarted or crashed, the engine will resume from the last recorded offset. Thus, at normal operation, your downstream routes will receive each event exactly once, however in case of an application crash (not having a graceful shutdown), the application will resume from the last recorded offset, which may result in receiving duplicate events immediately after the restart. Therefore, your downstream routes should be tolerant enough of such case and deduplicate events if needed. *Note:* The Debezium MySQL component is currently not supported in OSGi Maven users will need to add the following dependency to their `pom.xml` for this component. [source,xml] ---- org.apache.camel camel-debezium-mysql x.x.x ---- == URI format [source,text] --------------------------- debezium-mysql:name[?options] --------------------------- *Note:* Due to licensing issues, you will need to add the dependency for `mysql-conenctor-java` if you are using MySQL connector, just add the following to your POM file: [source,xml] ---- mysql mysql-connector-java 8.0.15 ---- == Options // component options: START The Debezium MySQL Connector component supports 80 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *additionalProperties* (common) | Additional properties for debezium components in case they can't be set directly on the camel configurations (e.g: setting Kafka Connect properties needed by Debezium engine, for example setting KafkaOffsetBackingStore), the properties have to be prefixed with additionalProperties.. E.g: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=\\http://localhost:8811/avro | | Map | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *configuration* (consumer) | Allow pre-configured Configurations to be set. | | MySqlConnectorEmbeddedDebeziumConfiguration | *internalKeyConverter* (consumer) | The Converter class that should be used to serialize and deserialize key data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *internalValueConverter* (consumer) | The Converter class that should be used to serialize and deserialize value data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *offsetCommitPolicy* (consumer) | The name of the Java class of the commit policy. It defines when offsets commit has to be triggered based on the number of events processed and the time elapsed since the last commit. This class must implement the interface 'OffsetCommitPolicy'. The default is a periodic commit policy based upon time intervals. | io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy | String | *offsetCommitTimeoutMs* (consumer) | Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. The default is 5 seconds. | 5s | long | *offsetFlushIntervalMs* (consumer) | Interval at which to try committing offsets. The default is 1 minute. | 60s | long | *offsetStorage* (consumer) | The name of the Java class that is responsible for persistence of connector offsets. | org.apache.kafka.connect.storage.FileOffsetBackingStore | String | *offsetStorageFileName* (consumer) | Path to file where offsets are to be stored. Required when offset.storage is set to the FileOffsetBackingStore. | | String | *offsetStoragePartitions* (consumer) | The number of partitions used when creating the offset storage topic. Required when offset.storage is set to the 'KafkaOffsetBackingStore'. | | int | *offsetStorageReplicationFactor* (consumer) | Replication factor used when creating the offset storage topic. Required when offset.storage is set to the KafkaOffsetBackingStore | | int | *offsetStorageTopic* (consumer) | The name of the Kafka topic where offsets are to be stored. Required when offset.storage is set to the KafkaOffsetBackingStore. | | String | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *bigintUnsignedHandlingMode* (mysql) | Specify how BIGINT UNSIGNED columns should be represented in change events, including:'precise' uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'long' (the default) represents values using Java's 'long', which may not offer the precision but will be far easier to use in consumers. | long | String | *binaryHandlingMode* (mysql) | Specify how binary (blob, binary, etc.) columns should be represented in change events, including:'bytes' represents binary data as byte array (default)'base64' represents binary data as base64-encoded string'hex' represents binary data as hex-encoded (base16) string | bytes | String | *binlogBufferSize* (mysql) | The size of a look-ahead buffer used by the binlog reader to decide whether the transaction in progress is going to be committed or rolled back. Use 0 to disable look-ahead buffering. Defaults to 0 (i.e. buffering is disabled). | 0 | int | *columnBlacklist* (mysql) | Regular expressions matching columns to exclude from change events (deprecated, use column.exclude.list instead) | | String | *columnExcludeList* (mysql) | Regular expressions matching columns to exclude from change events | | String | *columnIncludeList* (mysql) | Regular expressions matching columns to include in change events | | String | *connectKeepAlive* (mysql) | Whether a separate thread should be used to ensure the connection is kept alive. | true | boolean | *connectKeepAliveIntervalMs* (mysql) | Interval in milliseconds to wait for connection checking if keep alive thread is used. | 1m | long | *connectTimeoutMs* (mysql) | Maximum time in milliseconds to wait after trying to connect to the database before timing out. | 30s | int | *databaseExcludeList* (mysql) | A comma-separated list of regular expressions that match database names to be excluded from monitoring | | String | *databaseHistory* (mysql) | The name of the DatabaseHistory class that should be used to store and recover database schema changes. The configuration properties for the history are prefixed with the 'database.history.' string. | io.debezium.relational.history.FileDatabaseHistory | String | *databaseHistoryFileFilename* (mysql) | The path to the file that will be used to record the database history | | String | *databaseHistoryKafkaBootstrap{zwsp}Servers* (mysql) | A list of host/port pairs that the connector will use for establishing the initial connection to the Kafka cluster for retrieving database schema history previously stored by the connector. This should point to the same Kafka cluster used by the Kafka Connect process. | | String | *databaseHistoryKafkaRecovery{zwsp}Attempts* (mysql) | The number of attempts in a row that no data are returned from Kafka before recover completes. The maximum amount of time to wait after receiving no data is (recovery.attempts) x (recovery.poll.interval.ms). | 100 | int | *databaseHistoryKafkaRecovery{zwsp}PollIntervalMs* (mysql) | The number of milliseconds to wait while polling for persisted data during recovery. | 100ms | int | *databaseHistoryKafkaTopic* (mysql) | The name of the topic for the database schema history | | String | *databaseHistorySkipUnparseable{zwsp}Ddl* (mysql) | Controls the action Debezium will take when it meets a DDL statement in binlog, that it cannot parse.By default the connector will stop operating but by changing the setting it can ignore the statements which it cannot parse. If skipping is enabled then Debezium can miss metadata changes. | false | boolean | *databaseHistoryStoreOnly{zwsp}MonitoredTablesDdl* (mysql) | Controls what DDL will Debezium store in database history.By default (false) Debezium will store all incoming DDL statements. If set to truethen only DDL that manipulates a monitored table will be stored. | false | boolean | *databaseHostname* (mysql) | Resolvable hostname or IP address of the MySQL database server. | | String | *databaseIncludeList* (mysql) | The databases for which changes are to be captured | | String | *databaseInitialStatements* (mysql) | A semicolon separated list of SQL statements to be executed when a JDBC connection (not binlog reading connection) to the database is established. Note that the connector may establish JDBC connections at its own discretion, so this should typically be used for configuration of session parameters only,but not for executing DML statements. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. | | String | *databaseJdbcDriver* (mysql) | JDBC Driver class name used to connect to the MySQL database server. | class com.mysql.cj.jdbc.Driver | String | *databasePassword* (mysql) | *Required* Password of the MySQL database user to be used when connecting to the database. | | String | *databasePort* (mysql) | Port of the MySQL database server. | 3306 | int | *databaseServerId* (mysql) | A numeric ID of this database client, which must be unique across all currently-running database processes in the cluster. This connector joins the MySQL database cluster as another server (with this unique ID) so it can read the binlog. By default, a random number is generated between 5400 and 6400. | | long | *databaseServerIdOffset* (mysql) | Only relevant if parallel snapshotting is configured. During parallel snapshotting, multiple (4) connections open to the database client, and they each need their own unique connection ID. This offset is used to generate those IDs from the base configured cluster ID. | 10000 | long | *databaseServerName* (mysql) | *Required* Unique name that identifies the database server and all recorded offsets, and that is used as a prefix for all schemas and topics. Each distinct installation should have a separate namespace and be monitored by at most one Debezium connector. | | String | *databaseSslKeystore* (mysql) | Location of the Java keystore file containing an application process's own certificate and private key. | | String | *databaseSslKeystorePassword* (mysql) | Password to access the private key from the keystore file specified by 'ssl.keystore' configuration property or the 'javax.net.ssl.keyStore' system or JVM property. This password is used to unlock the keystore file (store password), and to decrypt the private key stored in the keystore (key password). | | String | *databaseSslMode* (mysql) | Whether to use an encrypted connection to MySQL. Options include'disabled' (the default) to use an unencrypted connection; 'preferred' to establish a secure (encrypted) connection if the server supports secure connections, but fall back to an unencrypted connection otherwise; 'required' to use a secure (encrypted) connection, and fail if one cannot be established; 'verify_ca' like 'required' but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates, or fail if no valid matching CA certificates are found; or'verify_identity' like 'verify_ca' but additionally verify that the server certificate matches the host to which the connection is attempted. | disabled | String | *databaseSslTruststore* (mysql) | Location of the Java truststore file containing the collection of CA certificates trusted by this application process (trust store). | | String | *databaseSslTruststorePassword* (mysql) | Password to unlock the keystore file (store password) specified by 'ssl.trustore' configuration property or the 'javax.net.ssl.trustStore' system or JVM property. | | String | *databaseUser* (mysql) | Name of the MySQL database user to be used when connecting to the database. | | String | *decimalHandlingMode* (mysql) | Specify how DECIMAL and NUMERIC columns should be represented in change events, including:'precise' (the default) uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'string' uses string to represent values; 'double' represents values using Java's 'double', which may not offer the precision but will be far easier to use in consumers. | precise | String | *enableTimeAdjuster* (mysql) | MySQL allows user to insert year value as either 2-digit or 4-digit. In case of two digit the value is automatically mapped into 1970 - 2069.false - delegates the implicit conversion to the databasetrue - (the default) Debezium makes the conversion | true | boolean | *eventDeserializationFailure{zwsp}HandlingMode* (mysql) | Specify how failures during deserialization of binlog events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *eventProcessingFailureHandling{zwsp}Mode* (mysql) | Specify how failures during processing of events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its position is raised, causing the connector to be stopped; 'warn' the problematic event and its position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *gtidNewChannelPosition* (mysql) | If set to 'latest', when connector sees new GTID, it will start consuming gtid channel from the server latest executed gtid position. If 'earliest' (the default) connector starts reading channel from first available (not purged) gtid position on the server. | earliest | String | *gtidSourceExcludes* (mysql) | The source UUIDs used to exclude GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *gtidSourceFilterDmlEvents* (mysql) | If set to true, we will only produce DML events into Kafka for transactions that were written on mysql servers with UUIDs matching the filters defined by the gtid.source.includes or gtid.source.excludes configuration options, if they are specified. | true | boolean | *gtidSourceIncludes* (mysql) | The source UUIDs used to include GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *heartbeatIntervalMs* (mysql) | Length of an interval in milli-seconds in in which the connector periodically sends heartbeat messages to a heartbeat topic. Use 0 to disable heartbeat messages. Disabled by default. | 0ms | int | *heartbeatTopicsPrefix* (mysql) | The prefix that is used to name heartbeat topics.Defaults to __debezium-heartbeat. | __debezium-heartbeat | String | *includeQuery* (mysql) | Whether the connector should include the original SQL query that generated the change event. Note: This option requires MySQL be configured with the binlog_rows_query_log_events option set to ON. Query will not be present for events generated from snapshot. WARNING: Enabling this option may expose tables or fields explicitly blacklisted or masked by including the original SQL statement in the change event. For this reason the default value is 'false'. | false | boolean | *includeSchemaChanges* (mysql) | Whether the connector should publish changes in the database schema to a Kafka topic with the same name as the database server ID. Each schema change will be recorded using a key that contains the database name and whose value include logical description of the new schema and optionally the DDL statement(s).The default is 'true'. This is independent of how the connector internally records database history. | true | boolean | *inconsistentSchemaHandlingMode* (mysql) | Specify how binlog events that belong to a table missing from internal schema representation (i.e. internal representation is not consistent with database) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'skip' the problematic event will be skipped. | fail | String | *maxBatchSize* (mysql) | Maximum size of each batch of source records. Defaults to 2048. | 2048 | int | *maxQueueSize* (mysql) | Maximum size of the queue for change events read from the database log but not yet recorded or forwarded. Defaults to 8192, and should always be larger than the maximum batch size. | 8192 | int | *messageKeyColumns* (mysql) | A semicolon-separated list of expressions that match fully-qualified tables and column(s) to be used as message key. Each expression must match the pattern ':',where the table names could be defined as (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the specific connector,and the key columns are a comma-separated list of columns representing the custom key. For any table without an explicit key configuration the table's primary key column(s) will be used as message key.Example: dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id | | String | *pollIntervalMs* (mysql) | Frequency in milliseconds to wait for new change events to appear after receiving no events. Defaults to 500ms. | 500ms | long | *skippedOperations* (mysql) | The comma-separated list of operations to skip during streaming, defined as: 'c' for inserts/create; 'u' for updates; 'd' for deletes. By default, no operations will be skipped. | | String | *snapshotDelayMs* (mysql) | The number of milliseconds to delay before a snapshot will begin. | 0ms | long | *snapshotEventsAsInserts* (mysql) | Whether or not to mark snapshot events as normal inserts (op 'c'). If disabled, the standard functionality of emitting these records as reads (op 'r') will be used. | true | boolean | *snapshotFetchSize* (mysql) | The maximum number of records that should be loaded into memory while performing a snapshot | | int | *snapshotLockingMode* (mysql) | Controls how long the connector holds onto the global read lock while it is performing a snapshot. The default is 'minimal', which means the connector holds the global read lock (and thus prevents any updates) for just the initial portion of the snapshot while the database schemas and other metadata are being read. The remaining work in a snapshot involves selecting all rows from each table, and this can be done using the snapshot process' REPEATABLE READ transaction even when the lock is no longer held and other operations are updating the database. However, in some cases it may be desirable to block all writes for the entire duration of the snapshot; in such cases set this property to 'extended'. Using a value of 'none' will prevent the connector from acquiring any table locks during the snapshot process. This mode can only be used in combination with snapshot.mode values of 'schema_only' or 'schema_only_recovery' and is only safe to use if no schema changes are happening while the snapshot is taken. | minimal | String | *snapshotMode* (mysql) | The criteria for running a snapshot upon startup of the connector. Options include: 'when_needed' to specify that the connector run a snapshot upon startup whenever it deems it necessary; 'schema_only' to only take a snapshot of the schema (table structures) but no actual data; 'initial' (the default) to specify the connector can run a snapshot only when no offsets are available for the logical server name; 'initial_only' same as 'initial' except the connector should stop after completing the snapshot and before it would normally read the binlog; and'never' to specify the connector should never run a snapshot and that upon first startup the connector should read from the beginning of the binlog. The 'never' mode should be used with care, and only when the binlog is known to contain all history. | initial | String | *snapshotNewTables* (mysql) | BETA FEATURE: On connector restart, the connector will check if there have been any new tables added to the configuration, and snapshot them. There is presently only two options:'off': Default behavior. Do not snapshot new tables.'parallel': The snapshot of the new tables will occur in parallel to the continued binlog reading of the old tables. When the snapshot completes, an independent binlog reader will begin reading the events for the new tables until it catches up to present time. At this point, both old and new binlog readers will be momentarily halted and new binlog reader will start that will read the binlog for all configured tables. The parallel binlog reader will have a configured server id of 10000 the primary binlog reader's server id. | off | String | *snapshotSelectStatement{zwsp}Overrides* (mysql) | This property contains a comma-separated list of fully-qualified tables (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on thespecific connectors . Select statements for the individual tables are specified in further configuration properties, one for each table, identified by the id 'snapshot.select.statement.overrides.DB_NAME.TABLE_NAME' or 'snapshot.select.statement.overrides.SCHEMA_NAME.TABLE_NAME', respectively. The value of those properties is the select statement to use when retrieving data from the specific table during snapshotting. A possible use case for large append-only tables is setting a specific point where to start (resume) snapshotting, in case a previous snapshotting was interrupted. | | String | *sourceStructVersion* (mysql) | A version of the format of the publicly visible source part in the message | v2 | String | *tableBlacklist* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring (deprecated, use table.exclude.list instead) | | String | *tableExcludeList* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring | | String | *tableIgnoreBuiltin* (mysql) | Flag specifying whether built-in tables should be ignored. | true | boolean | *tableIncludeList* (mysql) | The tables for which changes are to be captured | | String | *tableWhitelist* (mysql) | The tables for which changes are to be captured (deprecated, use table.include.list instead) | | String | *timePrecisionMode* (mysql) | Time, date and timestamps can be represented with different kinds of precisions, including:'adaptive_time_microseconds': the precision of date and timestamp values is based the database column's precision; but time fields always use microseconds precision;'connect': always represents time, date and timestamp values using Kafka Connect's built-in representations for Time, Date, and Timestamp, which uses millisecond precision regardless of the database columns' precision. | adaptive_time_microseconds | String | *tombstonesOnDelete* (mysql) | Whether delete operations should be represented by a delete event and a subsquenttombstone event (true) or only by a delete event (false). Emitting the tombstone event (the default behavior) allows Kafka to completely delete all events pertaining to the given key once the source record got deleted. | false | boolean |=== // component options: END // endpoint options: START The Debezium MySQL Connector endpoint is configured using URI syntax: ---- debezium-mysql:name ---- with the following path and query parameters: === Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *name* | *Required* Unique name for the connector. Attempting to register again with the same name will fail. | | String |=== === Query Parameters (80 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *additionalProperties* (common) | Additional properties for debezium components in case they can't be set directly on the camel configurations (e.g: setting Kafka Connect properties needed by Debezium engine, for example setting KafkaOffsetBackingStore), the properties have to be prefixed with additionalProperties.. E.g: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=\\http://localhost:8811/avro | | Map | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *internalKeyConverter* (consumer) | The Converter class that should be used to serialize and deserialize key data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *internalValueConverter* (consumer) | The Converter class that should be used to serialize and deserialize value data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *offsetCommitPolicy* (consumer) | The name of the Java class of the commit policy. It defines when offsets commit has to be triggered based on the number of events processed and the time elapsed since the last commit. This class must implement the interface 'OffsetCommitPolicy'. The default is a periodic commit policy based upon time intervals. | io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy | String | *offsetCommitTimeoutMs* (consumer) | Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. The default is 5 seconds. | 5s | long | *offsetFlushIntervalMs* (consumer) | Interval at which to try committing offsets. The default is 1 minute. | 60s | long | *offsetStorage* (consumer) | The name of the Java class that is responsible for persistence of connector offsets. | org.apache.kafka.connect.storage.FileOffsetBackingStore | String | *offsetStorageFileName* (consumer) | Path to file where offsets are to be stored. Required when offset.storage is set to the FileOffsetBackingStore. | | String | *offsetStoragePartitions* (consumer) | The number of partitions used when creating the offset storage topic. Required when offset.storage is set to the 'KafkaOffsetBackingStore'. | | int | *offsetStorageReplicationFactor* (consumer) | Replication factor used when creating the offset storage topic. Required when offset.storage is set to the KafkaOffsetBackingStore | | int | *offsetStorageTopic* (consumer) | The name of the Kafka topic where offsets are to be stored. Required when offset.storage is set to the KafkaOffsetBackingStore. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *bigintUnsignedHandlingMode* (mysql) | Specify how BIGINT UNSIGNED columns should be represented in change events, including:'precise' uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'long' (the default) represents values using Java's 'long', which may not offer the precision but will be far easier to use in consumers. | long | String | *binaryHandlingMode* (mysql) | Specify how binary (blob, binary, etc.) columns should be represented in change events, including:'bytes' represents binary data as byte array (default)'base64' represents binary data as base64-encoded string'hex' represents binary data as hex-encoded (base16) string | bytes | String | *binlogBufferSize* (mysql) | The size of a look-ahead buffer used by the binlog reader to decide whether the transaction in progress is going to be committed or rolled back. Use 0 to disable look-ahead buffering. Defaults to 0 (i.e. buffering is disabled). | 0 | int | *columnBlacklist* (mysql) | Regular expressions matching columns to exclude from change events (deprecated, use column.exclude.list instead) | | String | *columnExcludeList* (mysql) | Regular expressions matching columns to exclude from change events | | String | *columnIncludeList* (mysql) | Regular expressions matching columns to include in change events | | String | *connectKeepAlive* (mysql) | Whether a separate thread should be used to ensure the connection is kept alive. | true | boolean | *connectKeepAliveIntervalMs* (mysql) | Interval in milliseconds to wait for connection checking if keep alive thread is used. | 1m | long | *connectTimeoutMs* (mysql) | Maximum time in milliseconds to wait after trying to connect to the database before timing out. | 30s | int | *databaseExcludeList* (mysql) | A comma-separated list of regular expressions that match database names to be excluded from monitoring | | String | *databaseHistory* (mysql) | The name of the DatabaseHistory class that should be used to store and recover database schema changes. The configuration properties for the history are prefixed with the 'database.history.' string. | io.debezium.relational.history.FileDatabaseHistory | String | *databaseHistoryFileFilename* (mysql) | The path to the file that will be used to record the database history | | String | *databaseHistoryKafkaBootstrap{zwsp}Servers* (mysql) | A list of host/port pairs that the connector will use for establishing the initial connection to the Kafka cluster for retrieving database schema history previously stored by the connector. This should point to the same Kafka cluster used by the Kafka Connect process. | | String | *databaseHistoryKafkaRecovery{zwsp}Attempts* (mysql) | The number of attempts in a row that no data are returned from Kafka before recover completes. The maximum amount of time to wait after receiving no data is (recovery.attempts) x (recovery.poll.interval.ms). | 100 | int | *databaseHistoryKafkaRecovery{zwsp}PollIntervalMs* (mysql) | The number of milliseconds to wait while polling for persisted data during recovery. | 100ms | int | *databaseHistoryKafkaTopic* (mysql) | The name of the topic for the database schema history | | String | *databaseHistorySkipUnparseable{zwsp}Ddl* (mysql) | Controls the action Debezium will take when it meets a DDL statement in binlog, that it cannot parse.By default the connector will stop operating but by changing the setting it can ignore the statements which it cannot parse. If skipping is enabled then Debezium can miss metadata changes. | false | boolean | *databaseHistoryStoreOnly{zwsp}MonitoredTablesDdl* (mysql) | Controls what DDL will Debezium store in database history.By default (false) Debezium will store all incoming DDL statements. If set to truethen only DDL that manipulates a monitored table will be stored. | false | boolean | *databaseHostname* (mysql) | Resolvable hostname or IP address of the MySQL database server. | | String | *databaseIncludeList* (mysql) | The databases for which changes are to be captured | | String | *databaseInitialStatements* (mysql) | A semicolon separated list of SQL statements to be executed when a JDBC connection (not binlog reading connection) to the database is established. Note that the connector may establish JDBC connections at its own discretion, so this should typically be used for configuration of session parameters only,but not for executing DML statements. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. | | String | *databaseJdbcDriver* (mysql) | JDBC Driver class name used to connect to the MySQL database server. | class com.mysql.cj.jdbc.Driver | String | *databasePassword* (mysql) | *Required* Password of the MySQL database user to be used when connecting to the database. | | String | *databasePort* (mysql) | Port of the MySQL database server. | 3306 | int | *databaseServerId* (mysql) | A numeric ID of this database client, which must be unique across all currently-running database processes in the cluster. This connector joins the MySQL database cluster as another server (with this unique ID) so it can read the binlog. By default, a random number is generated between 5400 and 6400. | | long | *databaseServerIdOffset* (mysql) | Only relevant if parallel snapshotting is configured. During parallel snapshotting, multiple (4) connections open to the database client, and they each need their own unique connection ID. This offset is used to generate those IDs from the base configured cluster ID. | 10000 | long | *databaseServerName* (mysql) | *Required* Unique name that identifies the database server and all recorded offsets, and that is used as a prefix for all schemas and topics. Each distinct installation should have a separate namespace and be monitored by at most one Debezium connector. | | String | *databaseSslKeystore* (mysql) | Location of the Java keystore file containing an application process's own certificate and private key. | | String | *databaseSslKeystorePassword* (mysql) | Password to access the private key from the keystore file specified by 'ssl.keystore' configuration property or the 'javax.net.ssl.keyStore' system or JVM property. This password is used to unlock the keystore file (store password), and to decrypt the private key stored in the keystore (key password). | | String | *databaseSslMode* (mysql) | Whether to use an encrypted connection to MySQL. Options include'disabled' (the default) to use an unencrypted connection; 'preferred' to establish a secure (encrypted) connection if the server supports secure connections, but fall back to an unencrypted connection otherwise; 'required' to use a secure (encrypted) connection, and fail if one cannot be established; 'verify_ca' like 'required' but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates, or fail if no valid matching CA certificates are found; or'verify_identity' like 'verify_ca' but additionally verify that the server certificate matches the host to which the connection is attempted. | disabled | String | *databaseSslTruststore* (mysql) | Location of the Java truststore file containing the collection of CA certificates trusted by this application process (trust store). | | String | *databaseSslTruststorePassword* (mysql) | Password to unlock the keystore file (store password) specified by 'ssl.trustore' configuration property or the 'javax.net.ssl.trustStore' system or JVM property. | | String | *databaseUser* (mysql) | Name of the MySQL database user to be used when connecting to the database. | | String | *decimalHandlingMode* (mysql) | Specify how DECIMAL and NUMERIC columns should be represented in change events, including:'precise' (the default) uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'string' uses string to represent values; 'double' represents values using Java's 'double', which may not offer the precision but will be far easier to use in consumers. | precise | String | *enableTimeAdjuster* (mysql) | MySQL allows user to insert year value as either 2-digit or 4-digit. In case of two digit the value is automatically mapped into 1970 - 2069.false - delegates the implicit conversion to the databasetrue - (the default) Debezium makes the conversion | true | boolean | *eventDeserializationFailure{zwsp}HandlingMode* (mysql) | Specify how failures during deserialization of binlog events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *eventProcessingFailureHandling{zwsp}Mode* (mysql) | Specify how failures during processing of events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its position is raised, causing the connector to be stopped; 'warn' the problematic event and its position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *gtidNewChannelPosition* (mysql) | If set to 'latest', when connector sees new GTID, it will start consuming gtid channel from the server latest executed gtid position. If 'earliest' (the default) connector starts reading channel from first available (not purged) gtid position on the server. | earliest | String | *gtidSourceExcludes* (mysql) | The source UUIDs used to exclude GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *gtidSourceFilterDmlEvents* (mysql) | If set to true, we will only produce DML events into Kafka for transactions that were written on mysql servers with UUIDs matching the filters defined by the gtid.source.includes or gtid.source.excludes configuration options, if they are specified. | true | boolean | *gtidSourceIncludes* (mysql) | The source UUIDs used to include GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *heartbeatIntervalMs* (mysql) | Length of an interval in milli-seconds in in which the connector periodically sends heartbeat messages to a heartbeat topic. Use 0 to disable heartbeat messages. Disabled by default. | 0ms | int | *heartbeatTopicsPrefix* (mysql) | The prefix that is used to name heartbeat topics.Defaults to __debezium-heartbeat. | __debezium-heartbeat | String | *includeQuery* (mysql) | Whether the connector should include the original SQL query that generated the change event. Note: This option requires MySQL be configured with the binlog_rows_query_log_events option set to ON. Query will not be present for events generated from snapshot. WARNING: Enabling this option may expose tables or fields explicitly blacklisted or masked by including the original SQL statement in the change event. For this reason the default value is 'false'. | false | boolean | *includeSchemaChanges* (mysql) | Whether the connector should publish changes in the database schema to a Kafka topic with the same name as the database server ID. Each schema change will be recorded using a key that contains the database name and whose value include logical description of the new schema and optionally the DDL statement(s).The default is 'true'. This is independent of how the connector internally records database history. | true | boolean | *inconsistentSchemaHandlingMode* (mysql) | Specify how binlog events that belong to a table missing from internal schema representation (i.e. internal representation is not consistent with database) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'skip' the problematic event will be skipped. | fail | String | *maxBatchSize* (mysql) | Maximum size of each batch of source records. Defaults to 2048. | 2048 | int | *maxQueueSize* (mysql) | Maximum size of the queue for change events read from the database log but not yet recorded or forwarded. Defaults to 8192, and should always be larger than the maximum batch size. | 8192 | int | *messageKeyColumns* (mysql) | A semicolon-separated list of expressions that match fully-qualified tables and column(s) to be used as message key. Each expression must match the pattern ':',where the table names could be defined as (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the specific connector,and the key columns are a comma-separated list of columns representing the custom key. For any table without an explicit key configuration the table's primary key column(s) will be used as message key.Example: dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id | | String | *pollIntervalMs* (mysql) | Frequency in milliseconds to wait for new change events to appear after receiving no events. Defaults to 500ms. | 500ms | long | *skippedOperations* (mysql) | The comma-separated list of operations to skip during streaming, defined as: 'c' for inserts/create; 'u' for updates; 'd' for deletes. By default, no operations will be skipped. | | String | *snapshotDelayMs* (mysql) | The number of milliseconds to delay before a snapshot will begin. | 0ms | long | *snapshotEventsAsInserts* (mysql) | Whether or not to mark snapshot events as normal inserts (op 'c'). If disabled, the standard functionality of emitting these records as reads (op 'r') will be used. | true | boolean | *snapshotFetchSize* (mysql) | The maximum number of records that should be loaded into memory while performing a snapshot | | int | *snapshotLockingMode* (mysql) | Controls how long the connector holds onto the global read lock while it is performing a snapshot. The default is 'minimal', which means the connector holds the global read lock (and thus prevents any updates) for just the initial portion of the snapshot while the database schemas and other metadata are being read. The remaining work in a snapshot involves selecting all rows from each table, and this can be done using the snapshot process' REPEATABLE READ transaction even when the lock is no longer held and other operations are updating the database. However, in some cases it may be desirable to block all writes for the entire duration of the snapshot; in such cases set this property to 'extended'. Using a value of 'none' will prevent the connector from acquiring any table locks during the snapshot process. This mode can only be used in combination with snapshot.mode values of 'schema_only' or 'schema_only_recovery' and is only safe to use if no schema changes are happening while the snapshot is taken. | minimal | String | *snapshotMode* (mysql) | The criteria for running a snapshot upon startup of the connector. Options include: 'when_needed' to specify that the connector run a snapshot upon startup whenever it deems it necessary; 'schema_only' to only take a snapshot of the schema (table structures) but no actual data; 'initial' (the default) to specify the connector can run a snapshot only when no offsets are available for the logical server name; 'initial_only' same as 'initial' except the connector should stop after completing the snapshot and before it would normally read the binlog; and'never' to specify the connector should never run a snapshot and that upon first startup the connector should read from the beginning of the binlog. The 'never' mode should be used with care, and only when the binlog is known to contain all history. | initial | String | *snapshotNewTables* (mysql) | BETA FEATURE: On connector restart, the connector will check if there have been any new tables added to the configuration, and snapshot them. There is presently only two options:'off': Default behavior. Do not snapshot new tables.'parallel': The snapshot of the new tables will occur in parallel to the continued binlog reading of the old tables. When the snapshot completes, an independent binlog reader will begin reading the events for the new tables until it catches up to present time. At this point, both old and new binlog readers will be momentarily halted and new binlog reader will start that will read the binlog for all configured tables. The parallel binlog reader will have a configured server id of 10000 the primary binlog reader's server id. | off | String | *snapshotSelectStatement{zwsp}Overrides* (mysql) | This property contains a comma-separated list of fully-qualified tables (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on thespecific connectors . Select statements for the individual tables are specified in further configuration properties, one for each table, identified by the id 'snapshot.select.statement.overrides.DB_NAME.TABLE_NAME' or 'snapshot.select.statement.overrides.SCHEMA_NAME.TABLE_NAME', respectively. The value of those properties is the select statement to use when retrieving data from the specific table during snapshotting. A possible use case for large append-only tables is setting a specific point where to start (resume) snapshotting, in case a previous snapshotting was interrupted. | | String | *sourceStructVersion* (mysql) | A version of the format of the publicly visible source part in the message | v2 | String | *tableBlacklist* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring (deprecated, use table.exclude.list instead) | | String | *tableExcludeList* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring | | String | *tableIgnoreBuiltin* (mysql) | Flag specifying whether built-in tables should be ignored. | true | boolean | *tableIncludeList* (mysql) | The tables for which changes are to be captured | | String | *tableWhitelist* (mysql) | The tables for which changes are to be captured (deprecated, use table.include.list instead) | | String | *timePrecisionMode* (mysql) | Time, date and timestamps can be represented with different kinds of precisions, including:'adaptive_time_microseconds': the precision of date and timestamp values is based the database column's precision; but time fields always use microseconds precision;'connect': always represents time, date and timestamp values using Kafka Connect's built-in representations for Time, Date, and Timestamp, which uses millisecond precision regardless of the database columns' precision. | adaptive_time_microseconds | String | *tombstonesOnDelete* (mysql) | Whether delete operations should be represented by a delete event and a subsquenttombstone event (true) or only by a delete event (false). Emitting the tombstone event (the default behavior) allows Kafka to completely delete all events pertaining to the given key once the source record got deleted. | false | boolean |=== // endpoint options: END For more information about configuration: https://debezium.io/documentation/reference/0.10/operations/embedded.html#engine-properties[https://debezium.io/documentation/reference/0.10/operations/embedded.html#engine-properties] https://debezium.io/documentation/reference/0.10/connectors/mysql.html#connector-properties[https://debezium.io/documentation/reference/0.10/connectors/mysql.html#connector-properties] == Message headers === Consumer headers The following headers are available when consuming change events from Debezium. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | DebeziumConstants.HEADER_IDENTIFIER | ""CamelDebeziumIdentifier"" | String | The identifier of the connector, normally is this format ""+++{server-name}.{database-name}.{table-name}+++"". | DebeziumConstants.HEADER_KEY | ""CamelDebeziumKey"" | Struct | The key of the event, normally is the table Primary Key. | DebeziumConstants.HEADER_SOURCE_METADATA | ""CamelDebeziumSourceMetadata"" | Map | The metadata about the source event, for example `table` name, database `name`, log position, etc, please refer to the Debezium documentation for more info. | DebeziumConstants.HEADER_OPERATION | ""CamelDebeziumOperation"" | String | If presents, the type of event operation. Values for the connector are `c` for create (or insert), `u` for update, `d` for delete or `r` in case of a snapshot event. | DebeziumConstants.HEADER_TIMESTAMP | ""CamelDebeziumTimestamp"" | Long | If presents, the time (using the system clock in the JVM) at which the connector processed the event. | DebeziumConstants.HEADER_BEFORE | ""CamelDebeziumBefore"" | Struct | If presents, contains the state of the row before the event occurred. |=== == Message body The message body if is not `null` (in case of tombstones), it contains the state of the row after the event occurred as `Struct` format or `Map` format if you use the included Type Converter from `Struct` to `Map` (please look below for more explanation). == Samples === Consuming events Here is a very simple route that you can use in order to listen to Debezium events from MySQL connector. [source,java] ---- from(""debezium-mysql:dbz-test-1?offsetStorageFileName=/usr/offset-file-1.dat&databaseHostName=localhost&databaseUser=debezium&databasePassword=dbz&databaseServerName=my-app-connector&databaseHistoryFileName=/usr/history-file-1.dat"") .log(""Event received from Debezium : ${body}"") .log("" with this identifier ${headers.CamelDebeziumIdentifier}"") .log("" with these source metadata ${headers.CamelDebeziumSourceMetadata}"") .log("" the event occured upon this operation '${headers.CamelDebeziumSourceOperation}'"") .log("" on this database '${headers.CamelDebeziumSourceMetadata[db]}' and this table '${headers.CamelDebeziumSourceMetadata[table]}'"") .log("" with the key ${headers.CamelDebeziumKey}"") .log("" the previous value is ${headers.CamelDebeziumBefore}"") ---- By default, the component will emit the events in the body and `CamelDebeziumBefore` header as https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Struct.html[`Struct`] data type, the reasoning behind this, is to perceive the schema information in case is needed. However, the component as well contains a xref:manual::type-converter.adoc[Type Converter] that converts from default output type of https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Struct.html[`Struct`] to `Map` in order to leverage Camel's rich xref:manual::data-format.adoc[Data Format] types which many of them work out of box with `Map` data type. To use it, you can either add `Map.class` type when you access the message e.g: `exchange.getIn().getBody(Map.class)`, or you can convert the body always to `Map` from the route builder by adding `.convertBodyTo(Map.class)` to your Camel Route DSL after `from` statement. We mentioned above about the schema, which can be used in case you need to perform advance data transformation and the schema is needed for that. If you choose not to convert your body to `Map`, you can obtain the schema information as https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Schema.html[`Schema`] type from `Struct` like this: [source,java] ---- from(""debezium-mysql:[name]?[options]]) .process(exchange -> { final Struct bodyValue = exchange.getIn().getBody(Struct.class); final Schema schemaValue = bodyValue.schema(); log.info(""Body value is :"" + bodyValue); log.info(""With Schema : "" + schemaValue); log.info(""And fields of :"" + schemaValue.fields()); log.info(""Field name has `"" + schemaValue.field(""name"").schema() + ""` type""); }); ---- *Important Note:* This component is a thin wrapper around Debezium Engine as mentioned, therefore before using this component in production, you need to understand how Debezium works and how configurations can reflect the expected behavior, especially in regards to https://debezium.io/documentation/reference/0.9/operations/embedded.html#_handling_failures[handling failures]. include::camel-spring-boot::page$debezium-mysql-starter.adoc[] ",12108,True,3001.869082361825,median "int _ZN12PlayerObject10updateJumpEPvf(int arg0) { delta = intrinsic_movss(delta, xmm0); r15 = arg0; r14 = *(int8_t *)(r15 + 0x778); rax = 0x0; rbx = 0xd5; if (r14 == 0x0) { rbx = 0x0; } *(int32_t *)(r15 + 0x754) = rbx; rax = rand(); xmm0 = intrinsic_cvtsi2ss(0x0, rax); xmm0 = intrinsic_mulss(xmm0, *(int32_t *)its 0.0); xmm0 = intrinsic_mulss(xmm0, *(int32_t *)value 1000.00); rax = intrinsic_cvttss2si(rax, xmm0); *(int32_t *)(r15 + 0x750) = rax; *(int32_t *)(r15 + 0x74c) = rbx + rax; r10 = *(int8_t *)(r15 + 0x778); xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x618)); rdx = *(int8_t *)(r15 + 0x745); r9 = *(int8_t *)(r15 + 0x774); rax = rdx; if (r9 != 0x0) { rax = (*(int8_t *)(r15 + 0x746) != 0x0 ? 0x1 : 0x0) & (rdx != 0x0 ? 0x1 : 0x0); } rcx = *(int8_t *)(r15 + 0x770); r8 = *(int8_t *)(r15 + 0x772); if (r8 == 0x0) goto loc_10021976c; loc_10021972a : xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x77c)); asm{ cmpneqss xmm1, dword [value 1.0] }; rsi = zero_extend_32(xmm1) & 0x1; rdi = 0x1; xmm5 = intrinsic_movss(xmm5, *(int32_t *)0x100510eb8); if (rcx == 0x0) goto loc_100219813; loc_100219756 : if (rsi == 0x0) { xmm6 = intrinsic_movss(xmm6, *(int32_t *)value 1.0); } else { xmm6 = intrinsic_movss(xmm6, *(int32_t *)0x10050d3dc); } goto loc_100219856; loc_100219856 : xmm2 = intrinsic_movss(xmm2, *(int32_t *)0x10050c764); xmm7 = intrinsic_movaps(xmm7, xmm2); xmm7 = intrinsic_divss(xmm7, xmm6); xmm8 = intrinsic_movss(xmm8, *(int32_t *)0x100510ebc); xmm8 = intrinsic_divss(xmm8, xmm6); r8 = *(int8_t *)(r15 + 0x776); xmm1 = intrinsic_movsd(xmm1, *(r15 + 0x760)); xmm3 = intrinsic_xorpd(xmm3, xmm3); if (r8 != 0x0) { xmm3 = intrinsic_ucomisd(xmm3, xmm1); if (xmm3 >= 0x0) { xmm4 = intrinsic_movaps(xmm4, *(int128_t *)value -0.00); xmm4 = intrinsic_xorps(xmm4, xmm7); xmm4 = intrinsic_cvtss2sd(xmm4, xmm4); xmm1 = intrinsic_ucomisd(xmm1, xmm4); if (xmm1 <= 0x0) { xmm1 = intrinsic_ucomisd(xmm1, xmm3); if (xmm1 >= 0x0) { xmm3 = intrinsic_movaps(xmm3, *(int128_t *)value -0.00); xmm3 = intrinsic_xorps(xmm3, xmm8); xmm3 = intrinsic_cvtss2sd(xmm3, xmm3); xmm3 = intrinsic_ucomisd(xmm3, xmm1); if (xmm3 > 0x0) { *(int8_t *)(r15 + 0x732) = 0x0; } } } else { *(int8_t *)(r15 + 0x732) = 0x0; } } else { xmm1 = intrinsic_ucomisd(xmm1, xmm3); if (xmm1 >= 0x0) { xmm3 = intrinsic_movaps(xmm3, *(int128_t *)value -0.00); xmm3 = intrinsic_xorps(xmm3, xmm8); xmm3 = intrinsic_cvtss2sd(xmm3, xmm3); xmm3 = intrinsic_ucomisd(xmm3, xmm1); if (xmm3 > 0x0) { *(int8_t *)(r15 + 0x732) = 0x0; } } } } else { xmm1 = intrinsic_ucomisd(xmm1, xmm3); if (xmm1 >= 0x0) { xmm4 = intrinsic_cvtss2sd(xmm4, xmm7); xmm4 = intrinsic_ucomisd(xmm4, xmm1); if (xmm4 <= 0x0) { xmm3 = intrinsic_ucomisd(xmm3, xmm1); if (xmm3 >= 0x0) { xmm3 = intrinsic_cvtss2sd(0x0, xmm8); xmm1 = intrinsic_ucomisd(xmm1, xmm3); if (xmm1 > 0x0) { *(int8_t *)(r15 + 0x732) = 0x0; } } } else { *(int8_t *)(r15 + 0x732) = 0x0; } } else { xmm3 = intrinsic_ucomisd(xmm3, xmm1); if (xmm3 >= 0x0) { xmm3 = intrinsic_cvtss2sd(0x0, xmm8); xmm1 = intrinsic_ucomisd(xmm1, xmm3); if (xmm1 > 0x0) { *(int8_t *)(r15 + 0x732) = 0x0; } } } } if (rdi == 0x0) goto loc_100219921; loc_1002198f4 : rax = *(int8_t *)(r15 + 0x732); if (rdx == 0x0) goto loc_1002199ab; loc_100219903 : if (rax != 0x0) goto loc_1002199b3; loc_10021990b : xmm2 = intrinsic_movss(xmm2, *(int32_t *)value -1.00); if (r8 == 0x0) { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm1); } else { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); } goto loc_100219a22; loc_100219a22 : if ((COND_BYTE_SET(G)) != 0x0) { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.5); } else { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.4); } goto loc_100219ae9; loc_100219ae9 : rax = 0x0; rax = r8 == 0x0 ? 0x1 : 0x0; xmm0 = intrinsic_cvtss2sd(0x0, intrinsic_divss(intrinsic_mulss(intrinsic_mulss(intrinsic_mulss(intrinsic_mulss(xmm5, delta), *(int32_t *)(0x10050d470 + rax * 0x4)), xmm2), xmm0), xmm6)); xmm1 = intrinsic_subsd(xmm1, xmm0); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm1); if (rdx != 0x0) { *(int8_t *)(r15 + 0x7a0) = 0x0; if (*(int8_t *)(r15 + 0x732) == 0x0) { if (*(int8_t *)(r15 + 0x773) == 0x0) { if (r8 != 0x0) { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value -8); xmm0 = intrinsic_divss(xmm0, xmm6); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_movss(xmm1, *(int32_t *)0x100510ec0); xmm1 = intrinsic_divss(xmm1, xmm6); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); } else { xmm0 = intrinsic_cvtss2sd(0x0, xmm8); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_cvtss2sd(0x0, xmm7); } *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), intrinsic_minsd(xmm1, xmm0)); } } } else { if (*(int8_t *)(r15 + 0x732) == 0x0) { if (*(int8_t *)(r15 + 0x773) == 0x0) { if (r8 != 0x0) { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value -8); xmm0 = intrinsic_divss(xmm0, xmm6); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_movss(xmm1, *(int32_t *)0x100510ec0); xmm1 = intrinsic_divss(xmm1, xmm6); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); } else { xmm0 = intrinsic_cvtss2sd(0x0, xmm8); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_cvtss2sd(0x0, xmm7); } *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), intrinsic_minsd(xmm1, xmm0)); } } } goto loc_100219da5; loc_100219da5 : rbx = stack[2044]; r14 = stack[2045]; r15 = stack[2046]; rsp = rsp + 0x98; rbp = stack[2047]; return rax; loc_1002199b3 : xmm2 = 0x0; if (r8 == 0x0) goto loc_1002199c3; loc_1002199bb : xmm2 = 0x0; xmm1 = intrinsic_ucomisd(xmm1, xmm2); if (xmm1 > 0x0) goto loc_1002199c9; loc_1002199d7 : xmm2 = intrinsic_movss(xmm2, *(int32_t *)value 0.8); if (rdx == 0x0) goto loc_1002199f2; loc_1002199e3 : if (r8 != 0x0) { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); } else { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm1); } goto loc_100219a22; loc_1002199f2 : if (r8 == 0x0) { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm1); } else { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); } goto loc_100219ad2; loc_100219ad2 : if ((COND_BYTE_SET(G)) == 0x0) { xmm2 = intrinsic_movss(xmm2, *(int32_t *)value 1.2); } xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.4); goto loc_100219ae9; loc_1002199c9 : xmm2 = intrinsic_movss(xmm2, *(int32_t *)value -1.00); if (rdx != 0x0) goto loc_1002199e3; goto loc_1002199f2; loc_1002199c3 : xmm2 = intrinsic_ucomisd(xmm2, xmm1); if (xmm2 <= 0x0) goto loc_1002199d7; goto loc_1002199c9; loc_1002199ab : if (rax == 0x0) goto loc_100219a99; goto loc_1002199b3; loc_100219a99 : xmm2 = intrinsic_movss(xmm2, *(int32_t *)value 0.8); if (r8 != 0x0) { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); } else { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm1); } goto loc_100219ad2; loc_100219921 : if (*(int8_t *)(r15 + 0x771) != 0x0) { if ((*(int8_t *)(r15 + 0x746) != 0x0) && (rdx != 0x0)) { if (rsi == 0x0) { xmm2 = intrinsic_movss(xmm2, *(int32_t *)0x10050ca5c); } r14 = r15 + 0x760; rax = 0x0; *(int8_t *)(r15 + 0x746) = 0x0; xmm2 = intrinsic_mulss(xmm2, *(int32_t *)(0x10050d470 + (COND_BYTE_SET(E)) * 0x4)); xmm2 = intrinsic_mulss(xmm2, xmm6); xmm0 = intrinsic_cvtss2sd(0x0, xmm2); var_68 = intrinsic_movss(var_68, xmm5); var_64 = intrinsic_movss(var_64, xmm6); var_90 = intrinsic_movaps(var_90, xmm7); var_80 = intrinsic_movaps(var_80, xmm8); if (r8 != 0x0) { xmm1 = intrinsic_ucomisd(xmm1, xmm0); if (xmm1 > 0x0) { *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm0); if ((*(int8_t *)(r15 + 0x769) != 0x0) || (*(int8_t *)(r15 + 0x768) != 0x0)) { xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x76c)); xmm3 = intrinsic_xorpd(xmm3, xmm3); xmm1 = intrinsic_ucomiss(xmm1, xmm3); if (xmm1 > 0x0) { xmm2 = intrinsic_mulss(xmm2, *(int32_t *)value 1.4); xmm1 = intrinsic_mulss(xmm1, *(int32_t *)value 0.5); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); xmm1 = intrinsic_addsd(xmm1, xmm0); xmm0 = intrinsic_cvtss2sd(0x0, xmm2); xmm0 = intrinsic_minsd(xmm0, xmm1); *r14 = intrinsic_movsd(*r14, xmm0); } } } } else { xmm0 = intrinsic_ucomisd(xmm0, xmm1); if (xmm0 > 0x0) { *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm0); if ((*(int8_t *)(r15 + 0x769) != 0x0) || (*(int8_t *)(r15 + 0x768) != 0x0)) { xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x76c)); xmm3 = intrinsic_xorpd(xmm3, xmm3); xmm1 = intrinsic_ucomiss(xmm1, xmm3); if (xmm1 > 0x0) { xmm2 = intrinsic_mulss(xmm2, *(int32_t *)value 1.4); xmm1 = intrinsic_mulss(xmm1, *(int32_t *)value 0.5); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); xmm1 = intrinsic_addsd(xmm1, xmm0); xmm0 = intrinsic_cvtss2sd(0x0, xmm2); xmm0 = intrinsic_minsd(xmm0, xmm1); *r14 = intrinsic_movsd(*r14, xmm0); } } } } rax = sub_10021c780(r15); xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x618)); r8 = *(int8_t *)(r15 + 0x776); xmm1 = intrinsic_movsd(xmm1, *r14); xmm5 = intrinsic_movss(xmm5, var_68); xmm6 = intrinsic_movss(xmm6, var_64); xmm7 = intrinsic_movaps(xmm7, var_90); xmm8 = intrinsic_movaps(xmm8, var_80); } if (r8 != 0x0) { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); } else { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm1); } rax = 0x0; rdx = r8 == 0x0 ? 0x1 : 0x0; if ((COND_BYTE_SET(G)) == 0x0) { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 1.2); } else { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.8); } rax = rdx; xmm1 = intrinsic_cvtss2sd(0x0, intrinsic_divss(intrinsic_mulss(intrinsic_mulss(intrinsic_mulss(intrinsic_mulss(xmm5, delta), *(int32_t *)(0x10050d470 + rax * 0x4)), xmm0), *(int32_t *)0x10050c978), xmm6)); xmm1 = intrinsic_addsd(xmm1, *(r15 + 0x760)); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm1); if (*(int8_t *)(r15 + 0x745) != 0x0) { *(int8_t *)(r15 + 0x7a0) = 0x0; } if (*(int8_t *)(r15 + 0x732) == 0x0) { if (*(int8_t *)(r15 + 0x773) == 0x0) { if (r8 != 0x0) { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value -8); xmm0 = intrinsic_divss(xmm0, xmm6); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_movss(xmm1, *(int32_t *)0x100510ec0); xmm1 = intrinsic_divss(xmm1, xmm6); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); } else { xmm0 = intrinsic_cvtss2sd(0x0, xmm8); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_cvtss2sd(0x0, xmm7); } *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), intrinsic_minsd(xmm1, xmm0)); } } } else { xmm0 = intrinsic_movsd(xmm0, *0x10050c8c8); xmm2 = intrinsic_movsd(xmm2, *0x10050c8d0); xmm3 = intrinsic_movapd(xmm3, xmm0); if (r8 != 0x0) { xmm3 = intrinsic_movapd(xmm3, xmm2); } xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x780)); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); xmm1 = intrinsic_mulsd(xmm1, *(r15 + 0x608)); xmm1 = intrinsic_mulsd(xmm1, xmm3); if (rdx == 0x0) { xmm0 = intrinsic_movapd(xmm0, xmm2); } xmm1 = intrinsic_mulsd(xmm1, xmm0); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm1); if (*(int8_t *)(r15 + 0x732) == 0x0) { if (*(int8_t *)(r15 + 0x773) == 0x0) { if (r8 != 0x0) { xmm0 = intrinsic_movss(xmm0, *(int32_t *)value -8); xmm0 = intrinsic_divss(xmm0, xmm6); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_movss(xmm1, *(int32_t *)0x100510ec0); xmm1 = intrinsic_divss(xmm1, xmm6); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); } else { xmm0 = intrinsic_cvtss2sd(0x0, xmm8); xmm0 = intrinsic_maxsd(xmm0, xmm1); xmm1 = intrinsic_cvtss2sd(0x0, xmm7); } *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), intrinsic_minsd(xmm1, xmm0)); } } } goto loc_100219da5; loc_100219813 : xmm1 = zero_extend_32(*(int32_t *)(0x10050e370 + rsi * 0x4)); if (*(int8_t *)(r15 + 0x771) == 0x0) goto loc_100219835; loc_100219829 : rdi = 0x0; if (rsi == 0x0) { xmm6 = intrinsic_movss(xmm6, *(int32_t *)value 1.0); } else { xmm6 = intrinsic_movss(xmm6, *(int32_t *)0x10050d3dc); } goto loc_100219856; loc_100219835 : if (*(int8_t *)(r15 + 0x773) == 0x0) goto loc_100219b45; loc_100219843 : rdi = 0x0; if (rsi != 0x0) { xmm6 = intrinsic_movss(xmm6, *(int32_t *)0x10050d3dc); } else { xmm6 = intrinsic_movss(xmm6, *(int32_t *)value 1.0); } goto loc_100219856; loc_100219b45 : if (r8 != 0x0) goto loc_100219b61; loc_100219b4a : rcx = 0x0; rsi = r9 == 0x0 ? 0x1 : 0x0; if (*(int8_t *)(r15 + 0x775) == 0x0) goto loc_100219e2c; loc_100219b61 : xmm2 = intrinsic_movss(xmm2, *(int32_t *)value 0.60); if (rax == 0x0) goto loc_100219b98; loc_100219b6d : if (r10 == 0x0) goto loc_100219b98; loc_100219b72 : if ((*(int8_t *)(r15 + 0x775) == 0x0) || (*(int8_t *)(r15 + 0x779) != 0x0)) goto loc_100219b8a; loc_100219fc7 : rdi = r15; rbx = stack[2044]; r14 = stack[2045]; r15 = stack[2046]; rsp = rsp + 0x98; rbp = stack[2047]; rax = PlayerObject::spiderTestJump(rdi, 0x0); return rax; loc_100219b8a : if (*(int8_t *)(r15 + 0x779) == 0x0) goto loc_100219ec9; loc_100219b98 : if (*(int8_t *)(r15 + 0x7a1) == 0x0) goto loc_100219dfd; loc_100219ba6 : if (((r9 == 0x0) || (rdx == 0x0)) || (*(int8_t *)(r15 + 0x758) != 0x0)) goto loc_100219db0; loc_100219bc5 : xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x674)); xmm3 = intrinsic_movss(xmm3, *(int32_t *)value 1.5); xmm3 = intrinsic_ucomiss(xmm3, xmm1); if (xmm3 <= 0x0) goto loc_100219db0; loc_100219bdf : *(int32_t *)(r15 + 0x674) = intrinsic_movss(*(int32_t *)(r15 + 0x674), intrinsic_addss(intrinsic_mulss(intrinsic_movss(xmm2, delta), *(int32_t *)value 0.10), xmm1)); rax = *(int8_t *)(r15 + 0x776); xmm1 = intrinsic_movsd(xmm1, *(r15 + 0x760)); if (rax != 0x0) goto loc_100219df1; loc_100219e48 : if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm1); if (xmm0 <= 0x0) goto loc_100219da5; loc_100219e70 : *(int8_t *)(r15 + 0x7a1) = 0x0; *(int8_t *)(r15 + 0x62a) = 0x1; *(int8_t *)(r15 + 0x7a0) = 0x0; if (r9 == 0x0) goto loc_10021a195; loc_100219e91 : rbx = *(r15 + 0x6a8); rax = std::basic_string, std::allocator >::basic_string(var_58, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_58); rax = var_58; goto loc_10021a382; loc_10021a382 : if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); } } goto loc_100219da5; loc_10021a195 : if (*(int8_t *)(r15 + 0x775) == 0x0) goto loc_100219da5; loc_10021a1a3 : rbx = *(r15 + 0x6b0); rax = std::basic_string, std::allocator >::basic_string(var_50, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_50); rax = var_50; goto loc_10021a382; loc_100219df1 : xmm0 = intrinsic_addsd(xmm0, xmm0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); if (xmm1 <= 0x0) goto loc_100219da5; goto loc_100219e70; loc_100219db0 : xmm5 = intrinsic_mulss(xmm5, delta); rax = *(int8_t *)(r15 + 0x776); rcx = 0x0; xmm2 = intrinsic_mulss(xmm2, intrinsic_mulss(xmm5, *(int32_t *)(0x10050d470 + (rax == 0x0 ? 0x1 : 0x0) * 0x4))); xmm2 = intrinsic_cvtss2sd(xmm2, xmm2); xmm1 = intrinsic_movsd(xmm1, *(r15 + 0x760)); xmm1 = intrinsic_subsd(xmm1, xmm2); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm1); if (rax == 0x0) goto loc_100219e48; goto loc_100219df1; loc_100219dfd : rax = *(int8_t *)(r15 + 0x776); xmm1 = intrinsic_movsd(xmm1, *(r15 + 0x760)); if (rax != 0x0) { xmm3 = intrinsic_movapd(xmm3, xmm0); xmm3 = intrinsic_addsd(xmm3, xmm3); xmm1 = intrinsic_ucomisd(xmm1, xmm3); if (xmm1 > 0x0) { *(int8_t *)(r15 + 0x778) = 0x0; } } else { COND = *(int8_t *)(r15 + 0x7d1) == 0x0; xmm3 = intrinsic_movapd(xmm3, xmm0); if (!COND) { xmm3 = intrinsic_movapd(xmm3, *(int128_t *)0x10050e430); xmm3 = intrinsic_xorpd(xmm3, xmm0); } xmm3 = intrinsic_cvtsd2ss(xmm3, xmm3); xmm3 = intrinsic_addss(xmm3, xmm3); xmm3 = intrinsic_cvtss2sd(xmm3, xmm3); xmm3 = intrinsic_ucomisd(xmm3, xmm1); if (xmm3 > 0x0) { *(int8_t *)(r15 + 0x778) = 0x0; } } rcx = 0x0; rax = 0x10050d470; xmm2 = intrinsic_mulss(xmm2, intrinsic_mulss(intrinsic_mulss(xmm5, delta), *(int32_t *)(rax + (COND_BYTE_SET(E)) * 0x4))); xmm2 = intrinsic_cvtss2sd(xmm2, xmm2); xmm1 = intrinsic_subsd(xmm1, xmm2); if (0x10050d470 != 0x0) { xmm2 = intrinsic_movsd(xmm2, *0x100511098); xmm2 = intrinsic_minsd(xmm2, xmm1); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm2); if (!CPU_FLAGS & NE) { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm2); if (xmm0 > 0x0) { if (r8 == 0x0) { rax = r9 != 0x0 ? 0x1 : 0x0; if (((((*(int8_t *)(r15 + 0x775) == 0x0) && (rax == 0x0)) && (PlayerObject::fadeOutStreak2(r15, 0x0) == 0x0)) && (*(int8_t *)(r15 + 0x768) == 0x0)) && (*(int8_t *)(r15 + 0x554) == 0x0)) { rax = PlayerObject::runRotateAction(r15, 0x1, rdx); } } xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x760)); xmm0 = intrinsic_ucomisd(xmm0, *0x100510160); rax = xmm0 > 0x0 ? 0x1 : 0x0; xmm1 = intrinsic_movsd(xmm1, *0x1005110a0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); rcx = xmm1 > 0x0 ? 0x1 : 0x0; if (*(int8_t *)(r15 + 0x776) != 0x0) { rcx = rax; } if (rcx == 0x1) { if (((*(int8_t *)(r15 + 0x774) != 0x0) && (*(int8_t *)(r15 + 0x7a0) != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { r14 = *(r15 + 0x6a8); rax = std::basic_string, std::allocator >::basic_string(var_48, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(r14, var_48); rax = var_48; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); } } r14 = r15 + 0x7a0; *(int8_t *)r14 = 0x0; } else { r14 = r15 + 0x7a0; if (((*(int8_t *)(r15 + 0x775) != 0x0) && (*(int8_t *)r14 != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { rbx = *(r15 + 0x6b0); rax = std::basic_string, std::allocator >::basic_string(var_40, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_40); rax = var_40; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); *(int8_t *)r14 = 0x0; } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } } } } else { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm2 = intrinsic_ucomisd(xmm2, xmm0); if (xmm2 > 0x0) { if (r8 == 0x0) { rax = r9 != 0x0 ? 0x1 : 0x0; if (((((*(int8_t *)(r15 + 0x775) == 0x0) && (rax == 0x0)) && (PlayerObject::fadeOutStreak2(r15, 0x0) == 0x0)) && (*(int8_t *)(r15 + 0x768) == 0x0)) && (*(int8_t *)(r15 + 0x554) == 0x0)) { rax = PlayerObject::runRotateAction(r15, 0x1, rdx); } } xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x760)); xmm0 = intrinsic_ucomisd(xmm0, *0x100510160); rax = xmm0 > 0x0 ? 0x1 : 0x0; xmm1 = intrinsic_movsd(xmm1, *0x1005110a0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); rcx = xmm1 > 0x0 ? 0x1 : 0x0; if (*(int8_t *)(r15 + 0x776) != 0x0) { rcx = rax; } if (rcx == 0x1) { if (((*(int8_t *)(r15 + 0x774) != 0x0) && (*(int8_t *)(r15 + 0x7a0) != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { r14 = *(r15 + 0x6a8); rax = std::basic_string, std::allocator >::basic_string(var_48, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(r14, var_48); rax = var_48; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); } } r14 = r15 + 0x7a0; *(int8_t *)r14 = 0x0; } else { r14 = r15 + 0x7a0; if (((*(int8_t *)(r15 + 0x775) != 0x0) && (*(int8_t *)r14 != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { rbx = *(r15 + 0x6b0); rax = std::basic_string, std::allocator >::basic_string(var_40, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_40); rax = var_40; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); *(int8_t *)r14 = 0x0; } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } } } } } else { xmm2 = intrinsic_movsd(xmm2, *0x100511090); xmm2 = intrinsic_maxsd(xmm2, xmm1); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm2); if (!CPU_FLAGS & E) { xmm0 = intrinsic_addsd(xmm0, xmm0); xmm2 = intrinsic_ucomisd(xmm2, xmm0); if (xmm2 > 0x0) { if (r8 == 0x0) { rax = r9 != 0x0 ? 0x1 : 0x0; if (((((*(int8_t *)(r15 + 0x775) == 0x0) && (rax == 0x0)) && (PlayerObject::fadeOutStreak2(r15, 0x0) == 0x0)) && (*(int8_t *)(r15 + 0x768) == 0x0)) && (*(int8_t *)(r15 + 0x554) == 0x0)) { rax = PlayerObject::runRotateAction(r15, 0x1, rdx); } } xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x760)); xmm0 = intrinsic_ucomisd(xmm0, *0x100510160); rax = xmm0 > 0x0 ? 0x1 : 0x0; xmm1 = intrinsic_movsd(xmm1, *0x1005110a0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); rcx = xmm1 > 0x0 ? 0x1 : 0x0; if (*(int8_t *)(r15 + 0x776) != 0x0) { rcx = rax; } if (rcx == 0x1) { if (((*(int8_t *)(r15 + 0x774) != 0x0) && (*(int8_t *)(r15 + 0x7a0) != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { r14 = *(r15 + 0x6a8); rax = std::basic_string, std::allocator >::basic_string(var_48, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(r14, var_48); rax = var_48; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); } } r14 = r15 + 0x7a0; *(int8_t *)r14 = 0x0; } else { r14 = r15 + 0x7a0; if (((*(int8_t *)(r15 + 0x775) != 0x0) && (*(int8_t *)r14 != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { rbx = *(r15 + 0x6b0); rax = std::basic_string, std::allocator >::basic_string(var_40, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_40); rax = var_40; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); *(int8_t *)r14 = 0x0; } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } } } } else { if (*(int8_t *)(r15 + 0x7d1) != 0x0) { xmm0 = intrinsic_xorpd(xmm0, *(int128_t *)0x10050e430); } xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); xmm0 = intrinsic_addss(xmm0, xmm0); xmm0 = intrinsic_cvtss2sd(xmm0, xmm0); xmm0 = intrinsic_ucomisd(xmm0, xmm2); if (xmm0 > 0x0) { if (r8 == 0x0) { rax = r9 != 0x0 ? 0x1 : 0x0; if (((((*(int8_t *)(r15 + 0x775) == 0x0) && (rax == 0x0)) && (PlayerObject::fadeOutStreak2(r15, 0x0) == 0x0)) && (*(int8_t *)(r15 + 0x768) == 0x0)) && (*(int8_t *)(r15 + 0x554) == 0x0)) { rax = PlayerObject::runRotateAction(r15, 0x1, rdx); } } xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x760)); xmm0 = intrinsic_ucomisd(xmm0, *0x100510160); rax = xmm0 > 0x0 ? 0x1 : 0x0; xmm1 = intrinsic_movsd(xmm1, *0x1005110a0); xmm1 = intrinsic_ucomisd(xmm1, xmm0); rcx = xmm1 > 0x0 ? 0x1 : 0x0; if (*(int8_t *)(r15 + 0x776) != 0x0) { rcx = rax; } if (rcx == 0x1) { if (((*(int8_t *)(r15 + 0x774) != 0x0) && (*(int8_t *)(r15 + 0x7a0) != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { r14 = *(r15 + 0x6a8); rax = std::basic_string, std::allocator >::basic_string(var_48, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(r14, var_48); rax = var_48; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); } } r14 = r15 + 0x7a0; *(int8_t *)r14 = 0x0; } else { r14 = r15 + 0x7a0; if (((*(int8_t *)(r15 + 0x775) != 0x0) && (*(int8_t *)r14 != 0x0)) && (*(int8_t *)(r15 + 0x6b8) == 0x0)) { rbx = *(r15 + 0x6b0); rax = std::basic_string, std::allocator >::basic_string(var_40, ""fall_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_40); rax = var_40; if (rax + 0xffffffffffffffe8 != std::string::_Rep::_S_empty_rep_storage) { *(int32_t *)(rax + 0xfffffffffffffff8) = lock intrinsic_xadd(*(int32_t *)(rax + 0xfffffffffffffff8), 0xffffffff); if (0xffffffff <= 0x0) { rsi = var_38; rax = std::string::_Rep::_M_destroy(); *(int8_t *)r14 = 0x0; } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } else { *(int8_t *)r14 = 0x0; } } } } } } goto loc_100219da5; loc_100219ec9 : *(int8_t *)(r15 + 0x7a1) = 0x1; *(int8_t *)(r15 + 0x7a0) = 0x0; *(int8_t *)(r15 + 0x778) = 0x0; *(int8_t *)(r15 + 0x746) = 0x0; *(int8_t *)(r15 + 0x758) = 0x0; *(int32_t *)(r15 + 0x674) = 0x0; xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x610)); xmm0 = intrinsic_cvtsd2ss(xmm0, xmm0); if (r9 != 0x0) { xmm0 = intrinsic_mulss(xmm0, *(int32_t *)value 0.5); } if (r14 == 0x0) { *(int8_t *)(r15 + 0x732) = 0x1; xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 1/32); } rax = *(int8_t *)(r15 + 0x776); rcx = 0x0; xmm3 = intrinsic_movss(xmm3, *(int32_t *)(0x10050d470 + (rax == 0x0 ? 0x1 : 0x0) * 0x4)); xmm1 = intrinsic_mulss(xmm1, intrinsic_mulss(xmm0, xmm3)); xmm0 = intrinsic_cvtss2sd(0x0, xmm1); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm0); if ((*(int8_t *)(r15 + 0x769) != 0x0) || (*(int8_t *)(r15 + 0x768) != 0x0)) { xmm2 = intrinsic_movss(xmm2, *(int32_t *)(r15 + 0x76c)); xmm3 = intrinsic_mulss(xmm3, xmm2); xmm4 = 0x0; xmm3 = intrinsic_ucomiss(xmm3, xmm4); if (xmm3 > 0x0) { xmm3 = intrinsic_movsd(xmm3, *(r15 + 0x7d8)); xmm3 = intrinsic_subsd(xmm3, *(r15 + 0x500)); xmm4 = intrinsic_movsd(xmm4, *0x100511070); xmm4 = intrinsic_ucomisd(xmm4, xmm3); if (xmm4 > 0x0) { xmm3 = intrinsic_mulsd(xmm3, *0x100511078); xmm3 = intrinsic_maxsd(xmm3, *0x100511080); } else { xmm3 = intrinsic_movsd(xmm3, *0x10050c8c8); } xmm1 = intrinsic_mulss(xmm1, *(int32_t *)value 1.4); if (r8 == 0x0) { xmm2 = intrinsic_cvtsd2ss(0x0, intrinsic_mulsd(xmm3, intrinsic_cvtss2sd(xmm2, xmm2))); } xmm2 = intrinsic_mulss(xmm2, *(int32_t *)0x10050cee4); xmm0 = intrinsic_addsd(xmm0, intrinsic_cvtss2sd(xmm2, xmm2)); xmm1 = intrinsic_cvtss2sd(xmm1, xmm1); if (rax != 0x0) { xmm1 = intrinsic_maxsd(xmm1, xmm0); } else { xmm1 = intrinsic_minsd(xmm1, xmm0); } *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm1); } } *(int8_t *)(r15 + 0x62b) = 0x1; rax = ftime(var_38); rax = (0xfffff & var_38) * 0x3e8; xmm0 = intrinsic_cvtsi2sd(0x0, (var_30 & 0xffff) + rax); xmm0 = intrinsic_divsd(xmm0, *0x10050c940); *(r15 + 0x640) = intrinsic_movsd(*(r15 + 0x640), xmm0); if (*(int8_t *)(r15 + 0x62c) != 0x0) { rax = PlayLayer::incrementJumps(*(GameManager::sharedState() + 0x180)); *(int8_t *)(r15 + 0x7c0) = 0x1; } if (*(int8_t *)(r15 + 0x772) == 0x0) goto loc_10021a345; loc_10021a2f1 : rsi = 0x0; rax = PlayerObject::flipGravity(r15, *(int8_t *)(r15 + 0x776) == 0x0 ? 0x1 : 0x0, 0x1); xmm0 = intrinsic_movsd(xmm0, *(r15 + 0x760)); xmm0 = intrinsic_mulsd(xmm0, *0x100511088); *(r15 + 0x760) = intrinsic_movsd(*(r15 + 0x760), xmm0); *(int8_t *)(r15 + 0x62f) = 0x0; *(int8_t *)(r15 + 0x745) = 0x0; goto loc_10021a336; loc_10021a336 : if (*(int8_t *)(r15 + 0x774) != 0x0) goto loc_10021a34f; goto loc_100219da5; loc_10021a34f : rbx = *(r15 + 0x6a8); rax = std::basic_string, std::allocator >::basic_string(var_60, ""jump_loop"", var_20); xmm0 = intrinsic_movss(xmm0, *(int32_t *)value 0.10); rax = CCAnimatedSprite::tweenToAnimation(rbx, var_60); rax = var_60; goto loc_10021a382; loc_10021a345 : if (*(int8_t *)(r15 + 0x774) == 0x0) goto loc_10021a3b3; goto loc_10021a34f; loc_10021a3b3 : if (*(int8_t *)(r15 + 0x775) != 0x0) goto loc_10021a336; loc_10021a3c1 : rax = PlayerObject::runRotateAction(r15, 0x1, 0x10050d470); if (*(int8_t *)(r15 + 0x774) != 0x0) goto loc_10021a34f; goto loc_100219da5; loc_100219e2c : xmm2 = intrinsic_movss(xmm2, *(int32_t *)(0x100511068 + rsi * 0x4)); if (rax != 0x0) goto loc_100219b6d; goto loc_100219b98; loc_10021976c : if (rcx == 0x0) goto loc_10021979f; loc_100219770 : xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x77c)); asm{ cmpneqss xmm1, dword [value 1.0] }; rsi = zero_extend_32(xmm1) & 0x1; rdi = 0x1; xmm5 = intrinsic_movss(xmm5, *(int32_t *)0x100510eb8); if (rsi == 0x0) { xmm6 = intrinsic_movss(xmm6, *(int32_t *)value 1.0); } else { xmm6 = intrinsic_movss(xmm6, *(int32_t *)0x10050d3dc); } goto loc_100219856; loc_10021979f : if (((*(int8_t *)(r15 + 0x771) != 0x0) || (*(int8_t *)(r15 + 0x773) != 0x0)) || (*(int8_t *)(r15 + 0x775) != 0x0)) goto loc_1002197bd; loc_1002197f6 : xmm5 = intrinsic_cvtsd2ss(xmm5, xmm0); xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x77c)); asm{ cmpneqss xmm1, dword [value 1.0] }; rsi = zero_extend_32(xmm1) & 0x1; goto loc_100219813; loc_1002197bd : xmm1 = intrinsic_movss(xmm1, *(int32_t *)(r15 + 0x77c)); asm{ cmpneqss xmm1, dword [value 1.0] }; rsi = zero_extend_32(xmm1) & 0x1; xmm1 = zero_extend_32(*(int32_t *)(0x10050e370 + rsi * 0x4)); xmm5 = intrinsic_movss(xmm5, *(int32_t *)0x100510eb8); if (*(int8_t *)(r15 + 0x771) != 0x0) goto loc_100219829; }",16180,True,4233.218540470246,median "// Copyright 2012 the V8 project 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 ""src/compiler.h"" #include #include #include ""src/asmjs/asm-js.h"" #include ""src/asmjs/asm-typer.h"" #include ""src/ast/ast-numbering.h"" #include ""src/ast/prettyprinter.h"" #include ""src/ast/scopes.h"" #include ""src/bootstrapper.h"" #include ""src/codegen.h"" #include ""src/compilation-cache.h"" #include ""src/compiler-dispatcher/optimizing-compile-dispatcher.h"" #include ""src/compiler/pipeline.h"" #include ""src/crankshaft/hydrogen.h"" #include ""src/debug/debug.h"" #include ""src/debug/liveedit.h"" #include ""src/deoptimizer.h"" #include ""src/frames-inl.h"" #include ""src/full-codegen/full-codegen.h"" #include ""src/globals.h"" #include ""src/heap/heap.h"" #include ""src/interpreter/interpreter.h"" #include ""src/isolate-inl.h"" #include ""src/log-inl.h"" #include ""src/messages.h"" #include ""src/parsing/parser.h"" #include ""src/parsing/rewriter.h"" #include ""src/parsing/scanner-character-streams.h"" #include ""src/runtime-profiler.h"" #include ""src/snapshot/code-serializer.h"" #include ""src/vm-state-inl.h"" namespace v8 { namespace internal { // A wrapper around a CompilationInfo that detaches the Handles from // the underlying DeferredHandleScope and stores them in info_ on // destruction. class CompilationHandleScope final { public: explicit CompilationHandleScope(CompilationInfo* info) : deferred_(info->isolate()), info_(info) {} ~CompilationHandleScope() { info_->set_deferred_handles(deferred_.Detach()); } private: DeferredHandleScope deferred_; CompilationInfo* info_; }; // Helper that times a scoped region and records the elapsed time. struct ScopedTimer { explicit ScopedTimer(base::TimeDelta* location) : location_(location) { DCHECK(location_ != NULL); timer_.Start(); } ~ScopedTimer() { *location_ += timer_.Elapsed(); } base::ElapsedTimer timer_; base::TimeDelta* location_; }; // ---------------------------------------------------------------------------- // Implementation of CompilationJob CompilationJob::Status CompilationJob::PrepareJob() { DCHECK(ThreadId::Current().Equals(info()->isolate()->thread_id())); DisallowJavascriptExecution no_js(isolate()); if (FLAG_trace_opt && info()->IsOptimizing()) { OFStream os(stdout); os << ""[compiling method "" << Brief(*info()->closure()) << "" using "" << compiler_name_; if (info()->is_osr()) os << "" OSR""; os << ""]"" << std::endl; } // Delegate to the underlying implementation. DCHECK(state() == State::kReadyToPrepare); ScopedTimer t(&time_taken_to_prepare_); return UpdateState(PrepareJobImpl(), State::kReadyToExecute); } CompilationJob::Status CompilationJob::ExecuteJob() { std::unique_ptr no_allocation; std::unique_ptr no_handles; std::unique_ptr no_deref; std::unique_ptr no_dependency_change; if (can_execute_on_background_thread()) { no_allocation.reset(new DisallowHeapAllocation()); no_handles.reset(new DisallowHandleAllocation()); no_deref.reset(new DisallowHandleDereference()); no_dependency_change.reset(new DisallowCodeDependencyChange()); } else { DCHECK(ThreadId::Current().Equals(info()->isolate()->thread_id())); } // Delegate to the underlying implementation. DCHECK(state() == State::kReadyToExecute); ScopedTimer t(&time_taken_to_execute_); return UpdateState(ExecuteJobImpl(), State::kReadyToFinalize); } CompilationJob::Status CompilationJob::FinalizeJob() { DCHECK(ThreadId::Current().Equals(info()->isolate()->thread_id())); DisallowCodeDependencyChange no_dependency_change; DisallowJavascriptExecution no_js(isolate()); DCHECK(!info()->dependencies()->HasAborted()); // Delegate to the underlying implementation. DCHECK(state() == State::kReadyToFinalize); ScopedTimer t(&time_taken_to_finalize_); return UpdateState(FinalizeJobImpl(), State::kSucceeded); } CompilationJob::Status CompilationJob::RetryOptimization(BailoutReason reason) { DCHECK(info_->IsOptimizing()); info_->RetryOptimization(reason); state_ = State::kFailed; return FAILED; } CompilationJob::Status CompilationJob::AbortOptimization(BailoutReason reason) { DCHECK(info_->IsOptimizing()); info_->AbortOptimization(reason); state_ = State::kFailed; return FAILED; } void CompilationJob::RecordUnoptimizedCompilationStats() const { int code_size; if (info()->has_bytecode_array()) { code_size = info()->bytecode_array()->SizeIncludingMetadata(); } else { code_size = info()->code()->SizeIncludingMetadata(); } Counters* counters = isolate()->counters(); // TODO(4280): Rename counters from ""baseline"" to ""unoptimized"" eventually. counters->total_baseline_code_size()->Increment(code_size); counters->total_baseline_compile_count()->Increment(1); // TODO(5203): Add timers for each phase of compilation. } void CompilationJob::RecordOptimizedCompilationStats() const { DCHECK(info()->IsOptimizing()); Handle function = info()->closure(); if (!function->IsOptimized()) { // Concurrent recompilation and OSR may race. Increment only once. int opt_count = function->shared()->opt_count(); function->shared()->set_opt_count(opt_count + 1); } double ms_creategraph = time_taken_to_prepare_.InMillisecondsF(); double ms_optimize = time_taken_to_execute_.InMillisecondsF(); double ms_codegen = time_taken_to_finalize_.InMillisecondsF(); if (FLAG_trace_opt) { PrintF(""[optimizing ""); function->ShortPrint(); PrintF("" - took %0.3f, %0.3f, %0.3f ms]\\n"", ms_creategraph, ms_optimize, ms_codegen); } if (FLAG_trace_opt_stats) { static double compilation_time = 0.0; static int compiled_functions = 0; static int code_size = 0; compilation_time += (ms_creategraph + ms_optimize + ms_codegen); compiled_functions++; code_size += function->shared()->SourceSize(); PrintF(""Compiled: %d functions with %d byte source size in %fms.\\n"", compiled_functions, code_size, compilation_time); } if (FLAG_hydrogen_stats) { isolate()->GetHStatistics()->IncrementSubtotals(time_taken_to_prepare_, time_taken_to_execute_, time_taken_to_finalize_); } } Isolate* CompilationJob::isolate() const { return info()->isolate(); } namespace { void AddWeakObjectToCodeDependency(Isolate* isolate, Handle object, Handle code) { Handle cell = Code::WeakCellFor(code); Heap* heap = isolate->heap(); if (heap->InNewSpace(*object)) { heap->AddWeakNewSpaceObjectToCodeDependency(object, cell); } else { Handle dep(heap->LookupWeakObjectToCodeDependency(object)); dep = DependentCode::InsertWeakCode(dep, DependentCode::kWeakCodeGroup, cell); heap->AddWeakObjectToCodeDependency(object, dep); } } } // namespace void CompilationJob::RegisterWeakObjectsInOptimizedCode(Handle code) { // TODO(turbofan): Move this to pipeline.cc once Crankshaft dies. Isolate* const isolate = code->GetIsolate(); DCHECK(code->is_optimized_code()); std::vector> maps; std::vector> objects; { DisallowHeapAllocation no_gc; int const mode_mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) | RelocInfo::ModeMask(RelocInfo::CELL); for (RelocIterator it(*code, mode_mask); !it.done(); it.next()) { RelocInfo::Mode mode = it.rinfo()->rmode(); if (mode == RelocInfo::CELL && code->IsWeakObjectInOptimizedCode(it.rinfo()->target_cell())) { objects.push_back(handle(it.rinfo()->target_cell(), isolate)); } else if (mode == RelocInfo::EMBEDDED_OBJECT && code->IsWeakObjectInOptimizedCode( it.rinfo()->target_object())) { Handle object(HeapObject::cast(it.rinfo()->target_object()), isolate); if (object->IsMap()) { maps.push_back(Handle::cast(object)); } else { objects.push_back(object); } } } } for (Handle map : maps) { if (map->dependent_code()->IsEmpty(DependentCode::kWeakCodeGroup)) { isolate->heap()->AddRetainedMap(map); } Map::AddDependentCode(map, DependentCode::kWeakCodeGroup, code); } for (Handle object : objects) { AddWeakObjectToCodeDependency(isolate, object, code); } code->set_can_have_weak_objects(true); } // ---------------------------------------------------------------------------- // Local helper methods that make up the compilation pipeline. namespace { bool Parse(ParseInfo* info) { // Create a canonical handle scope if compiling ignition bytecode. This is // required by the constant array builder to de-duplicate objects without // dereferencing handles. std::unique_ptr canonical; if (FLAG_ignition) canonical.reset(new CanonicalHandleScope(info->isolate())); return Parser::ParseStatic(info); } void RecordFunctionCompilation(CodeEventListener::LogEventsAndTags tag, CompilationInfo* info) { // Log the code generation. If source information is available include // script name and line number. Check explicitly whether logging is // enabled as finding the line number is not free. if (info->isolate()->logger()->is_logging_code_events() || info->isolate()->is_profiling()) { Handle shared = info->shared_info(); Handle