static int adb_mouse_poll(ADBDevice *d, uint8_t *obuf) { MouseState *s = ADB_MOUSE(d); int dx, dy; if (s->last_buttons_state == s->buttons_state && s->dx == 0 && s->dy == 0) return 0; dx = s->dx; if (dx < -63) dx = -63; else if (dx > 63) dx = 63; dy = s->dy; if (dy < -63) dy = -63; else if (dy > 63) dy = 63; s->dx -= dx; s->dy -= dy; s->last_buttons_state = s->buttons_state; dx &= 0x7f; dy &= 0x7f; if (!(s->buttons_state & MOUSE_EVENT_LBUTTON)) dy |= 0x80; if (!(s->buttons_state & MOUSE_EVENT_RBUTTON)) dx |= 0x80; obuf[0] = dy; obuf[1] = dx; return 2; }


lldp_decode(struct lldpd *cfg, char *frame, int s,
    struct lldpd_hardware *hardware,
    struct lldpd_chassis **newchassis, struct lldpd_port **newport)
{
	struct lldpd_chassis *chassis;
	struct lldpd_port *port;
	const char lldpaddr[] = LLDP_MULTICAST_ADDR;
	const char dot1[] = LLDP_TLV_ORG_DOT1;
	const char dot3[] = LLDP_TLV_ORG_DOT3;
	const char med[] = LLDP_TLV_ORG_MED;
	const char dcbx[] = LLDP_TLV_ORG_DCBX;
	unsigned char orgid[3];
	int length, gotend = 0, ttl_received = 0;
	int tlv_size, tlv_type, tlv_subtype;
	u_int8_t *pos, *tlv;
	char *b;
#ifdef ENABLE_DOT1
	struct lldpd_vlan *vlan = NULL;
	int vlan_len;
	struct lldpd_ppvid *ppvid;
	struct lldpd_pi *pi = NULL;
#endif
	struct lldpd_mgmt *mgmt;
	int af;
	u_int8_t addr_str_length, addr_str_buffer[32];
	u_int8_t addr_family, addr_length, *addr_ptr, iface_subtype;
	u_int32_t iface_number, iface;
#ifdef ENABLE_CUSTOM
	struct lldpd_custom *custom = NULL;
#endif

	log_debug("lldp", "receive LLDP PDU on %s",
	    hardware->h_ifname);

	if ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) {
		log_warn("lldp", "failed to allocate remote chassis");
		return -1;
	}
	TAILQ_INIT(&chassis->c_mgmt);
	if ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) {
		log_warn("lldp", "failed to allocate remote port");
		free(chassis);
		return -1;
	}
#ifdef ENABLE_DOT1
	TAILQ_INIT(&port->p_vlans);
	TAILQ_INIT(&port->p_ppvids);
	TAILQ_INIT(&port->p_pids);
#endif
#ifdef ENABLE_CUSTOM
	TAILQ_INIT(&port->p_custom_list);
#endif

	length = s;
	pos = (u_int8_t*)frame;

	if (length < 2*ETHER_ADDR_LEN + sizeof(u_int16_t)) {
		log_warnx("lldp", "too short frame received on %s", hardware->h_ifname);
		goto malformed;
	}
	if (PEEK_CMP(lldpaddr, ETHER_ADDR_LEN) != 0) {
		log_info("lldp", "frame not targeted at LLDP multicast address received on %s",
		    hardware->h_ifname);
		goto malformed;
	}
	PEEK_DISCARD(ETHER_ADDR_LEN);	/* Skip source address */
	if (PEEK_UINT16 != ETHERTYPE_LLDP) {
		log_info("lldp", "non LLDP frame received on %s",
		    hardware->h_ifname);
		goto malformed;
	}

	while (length && (!gotend)) {
		if (length < 2) {
			log_warnx("lldp", "tlv header too short received on %s",
			    hardware->h_ifname);
			goto malformed;
		}
		tlv_size = PEEK_UINT16;
		tlv_type = tlv_size >> 9;
		tlv_size = tlv_size & 0x1ff;
		(void)PEEK_SAVE(tlv);
		if (length < tlv_size) {
			log_warnx("lldp", "frame too short for tlv received on %s",
			    hardware->h_ifname);
			goto malformed;
		}
		switch (tlv_type) {
		case LLDP_TLV_END:
			if (tlv_size != 0) {
				log_warnx("lldp", "lldp end received with size not null on %s",
				    hardware->h_ifname);
				goto malformed;
			}
			if (length)
				log_debug("lldp", "extra data after lldp end on %s",
				    hardware->h_ifname);
			gotend = 1;
			break;
		case LLDP_TLV_CHASSIS_ID:
		case LLDP_TLV_PORT_ID:
			CHECK_TLV_SIZE(2, "Port Id");
			tlv_subtype = PEEK_UINT8;
			if ((tlv_subtype == 0) || (tlv_subtype > 7)) {
				log_warnx("lldp", "unknown subtype for tlv id received on %s",
				    hardware->h_ifname);
				goto malformed;
			}
			if ((b = (char *)calloc(1, tlv_size - 1)) == NULL) {
				log_warn("lldp", "unable to allocate memory for id tlv "
				    "received on %s",
				    hardware->h_ifname);
				goto malformed;
			}
			PEEK_BYTES(b, tlv_size - 1);
			if (tlv_type == LLDP_TLV_PORT_ID) {
				port->p_id_subtype = tlv_subtype;
				port->p_id = b;
				port->p_id_len = tlv_size - 1;
			} else {
				chassis->c_id_subtype = tlv_subtype;
				chassis->c_id = b;
				chassis->c_id_len = tlv_size - 1;
			}
			break;
		case LLDP_TLV_TTL:
			CHECK_TLV_SIZE(2, "TTL");
			chassis->c_ttl = PEEK_UINT16;
			ttl_received = 1;
			break;
		case LLDP_TLV_PORT_DESCR:
		case LLDP_TLV_SYSTEM_NAME:
		case LLDP_TLV_SYSTEM_DESCR:
			if (tlv_size < 1) {
				log_debug("lldp", "empty tlv received on %s",
				    hardware->h_ifname);
				break;
			}
			if ((b = (char *)calloc(1, tlv_size + 1)) == NULL) {
				log_warn("lldp", "unable to allocate memory for string tlv "
				    "received on %s",
				    hardware->h_ifname);
				goto malformed;
			}
			PEEK_BYTES(b, tlv_size);
			if (tlv_type == LLDP_TLV_PORT_DESCR)
				port->p_descr = b;
			else if (tlv_type == LLDP_TLV_SYSTEM_NAME)
				chassis->c_name = b;
			else chassis->c_descr = b;
			break;
		case LLDP_TLV_SYSTEM_CAP:
			CHECK_TLV_SIZE(4, "System capabilities");
			chassis->c_cap_available = PEEK_UINT16;
			chassis->c_cap_enabled = PEEK_UINT16;
			break;
		case LLDP_TLV_MGMT_ADDR:
			CHECK_TLV_SIZE(1, "Management address");
			addr_str_length = PEEK_UINT8;
			CHECK_TLV_SIZE(1 + addr_str_length, "Management address");
			PEEK_BYTES(addr_str_buffer, addr_str_length);
			addr_length = addr_str_length - 1;
			addr_family = addr_str_buffer[0];
			addr_ptr = &addr_str_buffer[1];
			CHECK_TLV_SIZE(1 + addr_str_length + 5, "Management address");
			iface_subtype = PEEK_UINT8;
			iface_number = PEEK_UINT32;

			af = lldpd_af_from_lldp_proto(addr_family);
			if (af == LLDPD_AF_UNSPEC)
				break;
			if (iface_subtype == LLDP_MGMT_IFACE_IFINDEX)
				iface = iface_number;
			else
				iface = 0;
			mgmt = lldpd_alloc_mgmt(af, addr_ptr, addr_length, iface);
			if (mgmt == NULL) {
				assert(errno == ENOMEM);
				log_warn("lldp", "unable to allocate memory "
							"for management address");
						goto malformed;
			}
			TAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries);
			break;
		case LLDP_TLV_ORG:
			CHECK_TLV_SIZE(4, "Organisational");
			PEEK_BYTES(orgid, sizeof(orgid));
			tlv_subtype = PEEK_UINT8;
			if (memcmp(dot1, orgid, sizeof(orgid)) == 0) {
#ifndef ENABLE_DOT1
				hardware->h_rx_unrecognized_cnt++;
#else
				/* Dot1 */
				switch (tlv_subtype) {
				case LLDP_TLV_DOT1_VLANNAME:
					CHECK_TLV_SIZE(7, "VLAN");
					if ((vlan = (struct lldpd_vlan *)calloc(1,
						    sizeof(struct lldpd_vlan))) == NULL) {
						log_warn("lldp", "unable to alloc vlan "
						    "structure for "
						    "tlv received on %s",
						    hardware->h_ifname);
						goto malformed;
					}
					vlan->v_vid = PEEK_UINT16;
					vlan_len = PEEK_UINT8;
					CHECK_TLV_SIZE(7 + vlan_len, "VLAN");
					if ((vlan->v_name =
						(char *)calloc(1, vlan_len + 1)) == NULL) {
						log_warn("lldp", "unable to alloc vlan name for "
						    "tlv received on %s",
						    hardware->h_ifname);
						goto malformed;
					}
					PEEK_BYTES(vlan->v_name, vlan_len);
					TAILQ_INSERT_TAIL(&port->p_vlans,
					    vlan, v_entries);
					vlan = NULL;
					break;
				case LLDP_TLV_DOT1_PVID:
					CHECK_TLV_SIZE(6, "PVID");
					port->p_pvid = PEEK_UINT16;
					break;
				case LLDP_TLV_DOT1_PPVID:
					CHECK_TLV_SIZE(7, "PPVID");
					/* validation needed */
					/* PPVID has to be unique if more than
					   one PPVID TLVs are received  -
					   discard if duplicate */
					/* if support bit is not set and
					   enabled bit is set - PPVID TLV is
					   considered error  and discarded */
					/* if PPVID > 4096 - bad and discard */
					if ((ppvid = (struct lldpd_ppvid *)calloc(1,
						    sizeof(struct lldpd_ppvid))) == NULL) {
						log_warn("lldp", "unable to alloc ppvid "
						    "structure for "
						    "tlv received on %s",
						    hardware->h_ifname);
						goto malformed;
					}
					ppvid->p_cap_status = PEEK_UINT8;
					ppvid->p_ppvid = PEEK_UINT16;
					TAILQ_INSERT_TAIL(&port->p_ppvids,
					    ppvid, p_entries);
					break;
				case LLDP_TLV_DOT1_PI:
					/* validation needed */
					/* PI has to be unique if more than
					   one PI TLVs are received  - discard
					   if duplicate ?? */
					CHECK_TLV_SIZE(5, "PI");
					if ((pi = (struct lldpd_pi *)calloc(1,
						    sizeof(struct lldpd_pi))) == NULL) {
						log_warn("lldp", "unable to alloc PI "
						    "structure for "
						    "tlv received on %s",
						    hardware->h_ifname);
						goto malformed;
					}
					pi->p_pi_len = PEEK_UINT8;
					CHECK_TLV_SIZE(5 + pi->p_pi_len, "PI");
					if ((pi->p_pi =
						(char *)calloc(1, pi->p_pi_len)) == NULL) {
						log_warn("lldp", "unable to alloc pid name for "
						    "tlv received on %s",
						    hardware->h_ifname);
						goto malformed;
					}
					PEEK_BYTES(pi->p_pi, pi->p_pi_len);
					TAILQ_INSERT_TAIL(&port->p_pids,
					    pi, p_entries);
					pi = NULL;
					break;
				default:
					/* Unknown Dot1 TLV, ignore it */
					hardware->h_rx_unrecognized_cnt++;
				}
#endif
			} else if (memcmp(dot3, orgid, sizeof(orgid)) == 0) {
#ifndef ENABLE_DOT3
				hardware->h_rx_unrecognized_cnt++;
#else
				/* Dot3 */
				switch (tlv_subtype) {
				case LLDP_TLV_DOT3_MAC:
					CHECK_TLV_SIZE(9, "MAC/PHY");
					port->p_macphy.autoneg_support = PEEK_UINT8;
					port->p_macphy.autoneg_enabled =
					    (port->p_macphy.autoneg_support & 0x2) >> 1;
					port->p_macphy.autoneg_support =
					    port->p_macphy.autoneg_support & 0x1;
					port->p_macphy.autoneg_advertised =
					    PEEK_UINT16;
					port->p_macphy.mau_type = PEEK_UINT16;
					break;
				case LLDP_TLV_DOT3_LA:
					CHECK_TLV_SIZE(9, "Link aggregation");
					PEEK_DISCARD_UINT8;
					port->p_aggregid = PEEK_UINT32;
					break;
				case LLDP_TLV_DOT3_MFS:
					CHECK_TLV_SIZE(6, "MFS");
					port->p_mfs = PEEK_UINT16;
					break;
				case LLDP_TLV_DOT3_POWER:
					CHECK_TLV_SIZE(7, "Power");
					port->p_power.devicetype = PEEK_UINT8;
					port->p_power.supported =
						(port->p_power.devicetype & 0x2) >> 1;
					port->p_power.enabled =
						(port->p_power.devicetype & 0x4) >> 2;
					port->p_power.paircontrol =
						(port->p_power.devicetype & 0x8) >> 3;
					port->p_power.devicetype =
						(port->p_power.devicetype & 0x1)?
						LLDP_DOT3_POWER_PSE:LLDP_DOT3_POWER_PD;
					port->p_power.pairs = PEEK_UINT8;
					port->p_power.class = PEEK_UINT8;
					/* 802.3at? */
					if (tlv_size >= 12) {
						port->p_power.powertype = PEEK_UINT8;
						port->p_power.source =
						    (port->p_power.powertype & (1<<5 | 1<<4)) >> 4;
						port->p_power.priority =
						    (port->p_power.powertype & (1<<1 | 1<<0));
						port->p_power.powertype =
						    (port->p_power.powertype & (1<<7))?
						    LLDP_DOT3_POWER_8023AT_TYPE1:
						    LLDP_DOT3_POWER_8023AT_TYPE2;
						port->p_power.requested = PEEK_UINT16;
						port->p_power.allocated = PEEK_UINT16;
					} else
						port->p_power.powertype =
						    LLDP_DOT3_POWER_8023AT_OFF;
					break;
				default:
					/* Unknown Dot3 TLV, ignore it */
					hardware->h_rx_unrecognized_cnt++;
				}
#endif
			} else if (memcmp(med, orgid, sizeof(orgid)) == 0) {
				/* LLDP-MED */
#ifndef ENABLE_LLDPMED
				hardware->h_rx_unrecognized_cnt++;
#else
				u_int32_t policy;
				unsigned loctype;
				unsigned power;

				switch (tlv_subtype) {
				case LLDP_TLV_MED_CAP:
					CHECK_TLV_SIZE(7, "LLDP-MED capabilities");
					chassis->c_med_cap_available = PEEK_UINT16;
					chassis->c_med_type = PEEK_UINT8;
					port->p_med_cap_enabled |=
					    LLDP_MED_CAP_CAP;
					break;
				case LLDP_TLV_MED_POLICY:
					CHECK_TLV_SIZE(8, "LLDP-MED policy");
					policy = PEEK_UINT32;
					if (((policy >> 24) < 1) ||
					    ((policy >> 24) > LLDP_MED_APPTYPE_LAST)) {
						log_info("lldp", "unknown policy field %d "
						    "received on %s",
						    policy,
						    hardware->h_ifname);
						break;
					}
					port->p_med_policy[(policy >> 24) - 1].type =
					    (policy >> 24);
					port->p_med_policy[(policy >> 24) - 1].unknown =
					    ((policy & 0x800000) != 0);
					port->p_med_policy[(policy >> 24) - 1].tagged =
					    ((policy & 0x400000) != 0);
					port->p_med_policy[(policy >> 24) - 1].vid =
					    (policy & 0x001FFE00) >> 9;
					port->p_med_policy[(policy >> 24) - 1].priority =
					    (policy & 0x1C0) >> 6;
					port->p_med_policy[(policy >> 24) - 1].dscp =
					    policy & 0x3F;
					port->p_med_cap_enabled |=
					    LLDP_MED_CAP_POLICY;
					break;
				case LLDP_TLV_MED_LOCATION:
					CHECK_TLV_SIZE(5, "LLDP-MED Location");
					loctype = PEEK_UINT8;
					if ((loctype < 1) ||
					    (loctype > LLDP_MED_LOCFORMAT_LAST)) {
						log_info("lldp", "unknown location type "
						    "received on %s",
						    hardware->h_ifname);
						break;
					}
					if ((port->p_med_location[loctype - 1].data =
						(char*)malloc(tlv_size - 5)) == NULL) {
						log_warn("lldp", "unable to allocate memory "
						    "for LLDP-MED location for "
						    "frame received on %s",
						    hardware->h_ifname);
						goto malformed;
					}
					PEEK_BYTES(port->p_med_location[loctype - 1].data,
					    tlv_size - 5);
					port->p_med_location[loctype - 1].data_len =
					    tlv_size - 5;
					port->p_med_location[loctype - 1].format = loctype;
					port->p_med_cap_enabled |=
					    LLDP_MED_CAP_LOCATION;
					break;
				case LLDP_TLV_MED_MDI:
					CHECK_TLV_SIZE(7, "LLDP-MED PoE-MDI");
					power = PEEK_UINT8;
					switch (power & 0xC0) {
					case 0x0:
						port->p_med_power.devicetype = LLDP_MED_POW_TYPE_PSE;
						port->p_med_cap_enabled |=
						    LLDP_MED_CAP_MDI_PSE;
						switch (power & 0x30) {
						case 0x0:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_UNKNOWN;
							break;
						case 0x10:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_PRIMARY;
							break;
						case 0x20:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_BACKUP;
							break;
						default:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_RESERVED;
						}
						break;
					case 0x40:
						port->p_med_power.devicetype = LLDP_MED_POW_TYPE_PD;
						port->p_med_cap_enabled |=
						    LLDP_MED_CAP_MDI_PD;
						switch (power & 0x30) {
						case 0x0:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_UNKNOWN;
							break;
						case 0x10:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_PSE;
							break;
						case 0x20:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_LOCAL;
							break;
						default:
							port->p_med_power.source =
							    LLDP_MED_POW_SOURCE_BOTH;
						}
						break;
					default:
						port->p_med_power.devicetype =
						    LLDP_MED_POW_TYPE_RESERVED;
					}
					if ((power & 0x0F) > LLDP_MED_POW_PRIO_LOW)
						port->p_med_power.priority =
						    LLDP_MED_POW_PRIO_UNKNOWN;
					else
						port->p_med_power.priority =
						    power & 0x0F;
					port->p_med_power.val = PEEK_UINT16;
					break;
				case LLDP_TLV_MED_IV_HW:
				case LLDP_TLV_MED_IV_SW:
				case LLDP_TLV_MED_IV_FW:
				case LLDP_TLV_MED_IV_SN:
				case LLDP_TLV_MED_IV_MANUF:
				case LLDP_TLV_MED_IV_MODEL:
				case LLDP_TLV_MED_IV_ASSET:
					if (tlv_size <= 4)
						b = NULL;
					else {
						if ((b = (char*)malloc(tlv_size - 3)) ==
						    NULL) {
							log_warn("lldp", "unable to allocate "
							    "memory for LLDP-MED "
							    "inventory for frame "
							    "received on %s",
							    hardware->h_ifname);
							goto malformed;
						}
						PEEK_BYTES(b, tlv_size - 4);
						b[tlv_size - 4] = '\0';
					}
					switch (tlv_subtype) {
					case LLDP_TLV_MED_IV_HW:
						chassis->c_med_hw = b;
						break;
					case LLDP_TLV_MED_IV_FW:
						chassis->c_med_fw = b;
						break;
					case LLDP_TLV_MED_IV_SW:
						chassis->c_med_sw = b;
						break;
					case LLDP_TLV_MED_IV_SN:
						chassis->c_med_sn = b;
						break;
					case LLDP_TLV_MED_IV_MANUF:
						chassis->c_med_manuf = b;
						break;
					case LLDP_TLV_MED_IV_MODEL:
						chassis->c_med_model = b;
						break;
					case LLDP_TLV_MED_IV_ASSET:
						chassis->c_med_asset = b;
						break;
					}
					port->p_med_cap_enabled |=
					    LLDP_MED_CAP_IV;
					break;
				default:
					/* Unknown LLDP MED, ignore it */
					hardware->h_rx_unrecognized_cnt++;
				}
#endif /* ENABLE_LLDPMED */
			} else if (memcmp(dcbx, orgid, sizeof(orgid)) == 0) {
				log_debug("lldp", "unsupported DCBX tlv received on %s - ignore",
				    hardware->h_ifname);
				hardware->h_rx_unrecognized_cnt++;
			} else {
				log_debug("lldp", "unknown org tlv [%02x:%02x:%02x] received on %s",
				    orgid[0], orgid[1], orgid[2],
				    hardware->h_ifname);
				hardware->h_rx_unrecognized_cnt++;
#ifdef ENABLE_CUSTOM
				custom = (struct lldpd_custom*)calloc(1, sizeof(struct lldpd_custom));
				if (!custom) {
					log_warn("lldp",
					    "unable to allocate memory for custom TLV");
					goto malformed;
				}
				custom->oui_info_len = tlv_size > 4 ? tlv_size - 4 : 0;
				memcpy(custom->oui, orgid, sizeof(custom->oui));
				custom->subtype = tlv_subtype;
				if (custom->oui_info_len > 0) {
					custom->oui_info = malloc(custom->oui_info_len);
					if (!custom->oui_info) {
						log_warn("lldp",
						    "unable to allocate memory for custom TLV data");
						goto malformed;
					}
					PEEK_BYTES(custom->oui_info, custom->oui_info_len);
				}
				TAILQ_INSERT_TAIL(&port->p_custom_list, custom, next);
				custom = NULL;
#endif
			}
			break;
		default:
			log_warnx("lldp", "unknown tlv (%d) received on %s",
			    tlv_type, hardware->h_ifname);
			goto malformed;
		}
		if (pos > tlv + tlv_size) {
			log_warnx("lldp", "BUG: already past TLV!");
			goto malformed;
		}
		PEEK_DISCARD(tlv + tlv_size - pos);
	}

	/* Some random check */
	if ((chassis->c_id == NULL) ||
	    (port->p_id == NULL) ||
	    (!ttl_received) ||
	    (gotend == 0)) {
		log_warnx("lldp", "some mandatory tlv are missing for frame received on %s",
		    hardware->h_ifname);
		goto malformed;
	}
	*newchassis = chassis;
	*newport = port;
	return 1;
malformed:
#ifdef ENABLE_CUSTOM
	free(custom);
#endif
#ifdef ENABLE_DOT1
	free(vlan);
	free(pi);
#endif
	lldpd_chassis_cleanup(chassis, 1);
	lldpd_port_cleanup(port, 1);
	free(port);
	return -1;
}


static int get_physical_address_data(CPUState *env, target_phys_addr_t *physical, int *prot, target_ulong address, int rw, int mmu_idx) { unsigned int i; uint64_t context; int is_user = (mmu_idx == MMU_USER_IDX || mmu_idx == MMU_USER_SECONDARY_IDX); if ((env->lsu & DMMU_E) == 0) { /* DMMU disabled */ *physical = ultrasparc_truncate_physical(address); *prot = PAGE_READ | PAGE_WRITE; return 0; } switch(mmu_idx) { case MMU_USER_IDX: case MMU_KERNEL_IDX: context = env->dmmu.mmu_primary_context & 0x1fff; break; case MMU_USER_SECONDARY_IDX: case MMU_KERNEL_SECONDARY_IDX: context = env->dmmu.mmu_secondary_context & 0x1fff; break; case MMU_NUCLEUS_IDX: context = 0; break; } for (i = 0; i < 64; i++) { // ctx match, vaddr match, valid? if (ultrasparc_tag_match(&env->dtlb[i], address, context, physical)) { // access ok? if (((env->dtlb[i].tte & 0x4) && is_user) || (!(env->dtlb[i].tte & 0x2) && (rw == 1))) { uint8_t fault_type = 0; if ((env->dtlb[i].tte & 0x4) && is_user) { fault_type |= 1; /* privilege violation */ } if (env->dmmu.sfsr & 1) /* Fault status register */ env->dmmu.sfsr = 2; /* overflow (not read before another fault) */ env->dmmu.sfsr |= (is_user << 3) | ((rw == 1) << 2) | 1; env->dmmu.sfsr |= (fault_type << 7); env->dmmu.sfar = address; /* Fault address register */ env->exception_index = TT_DFAULT; #ifdef DEBUG_MMU printf("DFAULT at 0x%" PRIx64 "\n", address); #endif return 1; } *prot = PAGE_READ; if (env->dtlb[i].tte & 0x2) *prot |= PAGE_WRITE; TTE_SET_USED(env->dtlb[i].tte); return 0; } } #ifdef DEBUG_MMU printf("DMISS at 0x%" PRIx64 "\n", address); #endif env->dmmu.tag_access = (address & ~0x1fffULL) | context; env->exception_index = TT_DMISS; return 1; }


get_cookies (SoupCookieJar *jar, SoupURI *uri, gboolean for_http, gboolean copy_cookies)
{
	SoupCookieJarPrivate *priv;
	GSList *cookies, *domain_cookies;
	char *domain, *cur, *next_domain;
	GSList *new_head, *cookies_to_remove = NULL, *p;

	priv = soup_cookie_jar_get_instance_private (jar);

	if (!uri->host)
		return NULL;

	/* The logic here is a little weird, but the plan is that if
	 * uri->host is "www.foo.com", we will end up looking up
	 * cookies for ".www.foo.com", "www.foo.com", ".foo.com", and
	 * ".com", in that order. (Logic stolen from Mozilla.)
	 */
	cookies = NULL;
	domain = cur = g_strdup_printf (".%s", uri->host);
	next_domain = domain + 1;
	do {
		new_head = domain_cookies = g_hash_table_lookup (priv->domains, cur);
		while (domain_cookies) {
			GSList *next = domain_cookies->next;
			SoupCookie *cookie = domain_cookies->data;

			if (cookie->expires && soup_date_is_past (cookie->expires)) {
				cookies_to_remove = g_slist_append (cookies_to_remove,
								    cookie);
				new_head = g_slist_delete_link (new_head, domain_cookies);
				g_hash_table_insert (priv->domains,
						     g_strdup (cur),
						     new_head);
			} else if (soup_cookie_applies_to_uri (cookie, uri) &&
				   (for_http || !cookie->http_only))
				cookies = g_slist_append (cookies, copy_cookies ? soup_cookie_copy (cookie) : cookie);

			domain_cookies = next;
		}
		cur = next_domain;
		if (cur)
			next_domain = strchr (cur + 1, '.');
	} while (cur);
	g_free (domain);

	for (p = cookies_to_remove; p; p = p->next) {
		SoupCookie *cookie = p->data;

		soup_cookie_jar_changed (jar, cookie, NULL);
		soup_cookie_free (cookie);
	}
	g_slist_free (cookies_to_remove);

	return g_slist_sort_with_data (cookies, compare_cookies, jar);
}


int git_delta_apply(
	void **out,
	size_t *out_len,
	const unsigned char *base,
	size_t base_len,
	const unsigned char *delta,
	size_t delta_len)
{
	const unsigned char *delta_end = delta + delta_len;
	size_t base_sz, res_sz, alloc_sz;
	unsigned char *res_dp;

	*out = NULL;
	*out_len = 0;

	/*
	 * Check that the base size matches the data we were given;
	 * if not we would underflow while accessing data from the
	 * base object, resulting in data corruption or segfault.
	 */
	if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
		giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
		return -1;
	}

	if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
		giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
		return -1;
	}

	GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
	res_dp = git__malloc(alloc_sz);
	GITERR_CHECK_ALLOC(res_dp);

	res_dp[res_sz] = '\0';
	*out = res_dp;
	*out_len = res_sz;

	while (delta < delta_end) {
		unsigned char cmd = *delta++;
		if (cmd & 0x80) {
			/* cmd is a copy instruction; copy from the base. */
			size_t off = 0, len = 0;

			if (cmd & 0x01) off = *delta++;
			if (cmd & 0x02) off |= *delta++ << 8UL;
			if (cmd & 0x04) off |= *delta++ << 16UL;
			if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL);

			if (cmd & 0x10) len = *delta++;
			if (cmd & 0x20) len |= *delta++ << 8UL;
			if (cmd & 0x40) len |= *delta++ << 16UL;
			if (!len)       len = 0x10000;

			if (base_len < off + len || res_sz < len)
				goto fail;
			memcpy(res_dp, base + off, len);
			res_dp += len;
			res_sz -= len;

		} else if (cmd) {
			/*
			 * cmd is a literal insert instruction; copy from
			 * the delta stream itself.
			 */
			if (delta_end - delta < cmd || res_sz < cmd)
				goto fail;
			memcpy(res_dp, delta, cmd);
			delta += cmd;
			res_dp += cmd;
			res_sz -= cmd;

		} else {
			/* cmd == 0 is reserved for future encodings. */
			goto fail;
		}
	}

	if (delta != delta_end || res_sz)
		goto fail;
	return 0;

fail:
	git__free(*out);

	*out = NULL;
	*out_len = 0;

	giterr_set(GITERR_INVALID, "failed to apply delta");
	return -1;
}


static void init_proc_POWER9(CPUPPCState *env) { /* Common Registers */ init_proc_book3s_common(env); gen_spr_book3s_207_dbg(env); /* POWER8 Specific Registers */ gen_spr_book3s_ids(env); gen_spr_amr(env); gen_spr_iamr(env); gen_spr_book3s_purr(env); gen_spr_power5p_common(env); gen_spr_power5p_lpar(env); gen_spr_power5p_ear(env); gen_spr_power6_common(env); gen_spr_power6_dbg(env); gen_spr_power8_tce_address_control(env); gen_spr_power8_ids(env); gen_spr_power8_ebb(env); gen_spr_power8_fscr(env); gen_spr_power8_pmu_sup(env); gen_spr_power8_pmu_user(env); gen_spr_power8_tm(env); gen_spr_power8_pspb(env); gen_spr_vtb(env); gen_spr_power8_ic(env); gen_spr_power8_book4(env); gen_spr_power8_rpr(env); /* POWER9 Specific registers */ spr_register_kvm(env, SPR_TIDR, "TIDR", NULL, NULL, KVM_REG_PPC_TIDR, 0); /* env variables */ #if !defined(CONFIG_USER_ONLY) env->slb_nr = 32; #endif env->ci_large_pages = true; env->dcache_line_size = 128; env->icache_line_size = 128; /* Allocate hardware IRQ controller */ init_excp_POWER8(env); ppcPOWER7_irq_init(ppc_env_get_cpu(env)); }


static void DecoderGetCc ( decoder_t * p_dec , decoder_t * p_dec_cc ) {
 decoder_owner_sys_t * p_owner = p_dec -> p_owner ;
 block_t * p_cc ;
 bool pb_present [ 4 ] ;
 bool b_processed = false ;
 int i ;
 int i_cc_decoder ;
 assert ( p_dec_cc -> pf_get_cc != NULL ) ;
 if ( ! p_owner -> cc . b_supported ) return ;
 p_cc = p_dec_cc -> pf_get_cc ( p_dec_cc , pb_present ) ;
 if ( ! p_cc ) return ;
 vlc_mutex_lock ( & p_owner -> lock ) ;
 for ( i = 0 , i_cc_decoder = 0 ;
 i < 4 ;
 i ++ ) {
 p_owner -> cc . pb_present [ i ] |= pb_present [ i ] ;
 if ( p_owner -> cc . pp_decoder [ i ] ) i_cc_decoder ++ ;
 }
 for ( i = 0 ;
 i < 4 ;
 i ++ ) {
 if ( ! p_owner -> cc . pp_decoder [ i ] ) continue ;
 block_FifoPut ( p_owner -> cc . pp_decoder [ i ] -> p_owner -> p_fifo , ( i_cc_decoder > 1 ) ? block_Duplicate ( p_cc ) : p_cc ) ;
 i_cc_decoder -- ;
 b_processed = true ;
 }
 vlc_mutex_unlock ( & p_owner -> lock ) ;
 if ( ! b_processed ) block_Release ( p_cc ) ;
 }


static void setup_test_dir(char *tmp_dir, const char *files, ...) {
        va_list ap;

        assert_se(mkdtemp(tmp_dir) != NULL);

        va_start(ap, files);
        while (files != NULL) {
                _cleanup_free_ char *path = strappend(tmp_dir, files);
                assert_se(touch_file(path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID) == 0);
                files = va_arg(ap, const char *);
        }
        va_end(ap);
}


static int apng_read_packet(AVFormatContext *s, AVPacket *pkt) { APNGDemuxContext *ctx = s->priv_data; int64_t ret; int64_t size; AVIOContext *pb = s->pb; uint32_t len, tag; /* * fcTL chunk length, in bytes: * 4 (length) * 4 (tag) * 26 (actual chunk) * 4 (crc) bytes * and needed next: * 4 (length) * 4 (tag (must be fdAT or IDAT)) */ /* if num_play is not 1, then the seekback is already guaranteed */ if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 46)) < 0) return ret; len = avio_rb32(pb); tag = avio_rl32(pb); switch (tag) { case MKTAG('f', 'c', 'T', 'L'): if (len != 26) return AVERROR_INVALIDDATA; if ((ret = decode_fctl_chunk(s, ctx, pkt)) < 0) return ret; /* fcTL must precede fdAT or IDAT */ len = avio_rb32(pb); tag = avio_rl32(pb); if (len > 0x7fffffff || tag != MKTAG('f', 'd', 'A', 'T') && tag != MKTAG('I', 'D', 'A', 'T')) return AVERROR_INVALIDDATA; size = 38 /* fcTL */ + 8 /* len, tag */ + len + 4 /* crc */; if (size > INT_MAX) return AVERROR(EINVAL); if ((ret = avio_seek(pb, -46, SEEK_CUR)) < 0 || (ret = av_append_packet(pb, pkt, size)) < 0) return ret; if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0) return ret; len = avio_rb32(pb); tag = avio_rl32(pb); while (tag && tag != MKTAG('f', 'c', 'T', 'L') && tag != MKTAG('I', 'E', 'N', 'D')) { if (len > 0x7fffffff) return AVERROR_INVALIDDATA; if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0 || (ret = av_append_packet(pb, pkt, len + 12)) < 0) return ret; if (ctx->num_play == 1 && (ret = ffio_ensure_seekback(pb, 8)) < 0) return ret; len = avio_rb32(pb); tag = avio_rl32(pb); } if ((ret = avio_seek(pb, -8, SEEK_CUR)) < 0) return ret; if (ctx->is_key_frame) pkt->flags |= AV_PKT_FLAG_KEY; pkt->pts = ctx->pkt_pts; pkt->duration = ctx->pkt_duration; ctx->pkt_pts += ctx->pkt_duration; return send_extradata(ctx, pkt); case MKTAG('I', 'E', 'N', 'D'): ctx->cur_loop++; if (ctx->ignore_loop || ctx->num_play >= 1 && ctx->cur_loop == ctx->num_play) { avio_seek(pb, -8, SEEK_CUR); return AVERROR_EOF; } if ((ret = avio_seek(pb, ctx->extra_data_size + 8, SEEK_SET)) < 0) return ret; return send_extradata(ctx, pkt); default: { char tag_buf[32]; av_get_codec_tag_string(tag_buf, sizeof(tag_buf), tag); avpriv_request_sample(s, "In-stream tag=%s (0x%08X) len=%"PRIu32, tag_buf, tag, len); avio_skip(pb, len + 4); } } /* Handle the unsupported yet cases */ return AVERROR_PATCHWELCOME; }


static __always_inline __le64 __cpu_to_le64p ( const __u64 * p ) {
 return ( __le64 ) * p ;
 }


static void set_local_port_range ( int range [ 2 ] ) {
 write_seqlock ( & sysctl_local_ports . lock ) ;
 sysctl_local_ports . range [ 0 ] = range [ 0 ] ;
 sysctl_local_ports . range [ 1 ] = range [ 1 ] ;
 write_sequnlock ( & sysctl_local_ports . lock ) ;
 }


static TCGReg tcg_out_tlb_read(TCGContext *s, TCGMemOp s_bits, TCGReg addrlo, TCGReg addrhi, int mem_index, bool is_read) { int cmp_off = (is_read ? offsetof(CPUArchState, tlb_table[mem_index][0].addr_read) : offsetof(CPUArchState, tlb_table[mem_index][0].addr_write)); int add_off = offsetof(CPUArchState, tlb_table[mem_index][0].addend); TCGReg base = TCG_AREG0; /* Extract the page index, shifted into place for tlb index. */ if (TCG_TARGET_REG_BITS == 64) { if (TARGET_LONG_BITS == 32) { /* Zero-extend the address into a place helpful for further use. */ tcg_out_ext32u(s, TCG_REG_R4, addrlo); addrlo = TCG_REG_R4; } else { tcg_out_rld(s, RLDICL, TCG_REG_R3, addrlo, 64 - TARGET_PAGE_BITS, 64 - CPU_TLB_BITS); } } /* Compensate for very large offsets. */ if (add_off >= 0x8000) { /* Most target env are smaller than 32k; none are larger than 64k. Simplify the logic here merely to offset by 0x7ff0, giving us a range just shy of 64k. Check this assumption. */ QEMU_BUILD_BUG_ON(offsetof(CPUArchState, tlb_table[NB_MMU_MODES - 1][1]) > 0x7ff0 + 0x7fff); tcg_out32(s, ADDI | TAI(TCG_REG_TMP1, base, 0x7ff0)); base = TCG_REG_TMP1; cmp_off -= 0x7ff0; add_off -= 0x7ff0; } /* Extraction and shifting, part 2. */ if (TCG_TARGET_REG_BITS == 32 || TARGET_LONG_BITS == 32) { tcg_out_rlw(s, RLWINM, TCG_REG_R3, addrlo, 32 - (TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS), 32 - (CPU_TLB_BITS + CPU_TLB_ENTRY_BITS), 31 - CPU_TLB_ENTRY_BITS); } else { tcg_out_shli64(s, TCG_REG_R3, TCG_REG_R3, CPU_TLB_ENTRY_BITS); } tcg_out32(s, ADD | TAB(TCG_REG_R3, TCG_REG_R3, base)); /* Load the tlb comparator. */ if (TCG_TARGET_REG_BITS < TARGET_LONG_BITS) { tcg_out_ld(s, TCG_TYPE_I32, TCG_REG_R4, TCG_REG_R3, cmp_off); tcg_out_ld(s, TCG_TYPE_I32, TCG_REG_TMP1, TCG_REG_R3, cmp_off + 4); } else { tcg_out_ld(s, TCG_TYPE_TL, TCG_REG_TMP1, TCG_REG_R3, cmp_off); } /* Load the TLB addend for use on the fast path. Do this asap to minimize any load use delay. */ tcg_out_ld(s, TCG_TYPE_PTR, TCG_REG_R3, TCG_REG_R3, add_off); /* Clear the non-page, non-alignment bits from the address. */ if (TCG_TARGET_REG_BITS == 32 || TARGET_LONG_BITS == 32) { tcg_out_rlw(s, RLWINM, TCG_REG_R0, addrlo, 0, (32 - s_bits) & 31, 31 - TARGET_PAGE_BITS); } else if (!s_bits) { tcg_out_rld(s, RLDICR, TCG_REG_R0, addrlo, 0, 63 - TARGET_PAGE_BITS); } else { tcg_out_rld(s, RLDICL, TCG_REG_R0, addrlo, 64 - TARGET_PAGE_BITS, TARGET_PAGE_BITS - s_bits); tcg_out_rld(s, RLDICL, TCG_REG_R0, TCG_REG_R0, TARGET_PAGE_BITS, 0); } if (TCG_TARGET_REG_BITS < TARGET_LONG_BITS) { tcg_out_cmp(s, TCG_COND_EQ, TCG_REG_R0, TCG_REG_TMP1, 0, 7, TCG_TYPE_I32); tcg_out_cmp(s, TCG_COND_EQ, addrhi, TCG_REG_R4, 0, 6, TCG_TYPE_I32); tcg_out32(s, CRAND | BT(7, CR_EQ) | BA(6, CR_EQ) | BB(7, CR_EQ)); } else { tcg_out_cmp(s, TCG_COND_EQ, TCG_REG_R0, TCG_REG_TMP1, 0, 7, TCG_TYPE_TL); } return addrlo; }


void qemu_tcg_configure(QemuOpts *opts, Error **errp) { const char *t = qemu_opt_get(opts, "thread"); if (t) { if (strcmp(t, "multi") == 0) { if (TCG_OVERSIZED_GUEST) { error_setg(errp, "No MTTCG when guest word size > hosts"); } else if (use_icount) { error_setg(errp, "No MTTCG when icount is enabled"); } else { if (!check_tcg_memory_orders_compatible()) { error_report("Guest expects a stronger memory ordering " "than the host provides"); error_printf("This may cause strange/hard to debug errors"); } mttcg_enabled = true; } } else if (strcmp(t, "single") == 0) { mttcg_enabled = false; } else { error_setg(errp, "Invalid 'thread' setting %s", t); } } else { mttcg_enabled = default_mttcg_enabled(); } }


static int dpcm_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame_ptr , AVPacket * avpkt ) {
 int buf_size = avpkt -> size ;
 DPCMContext * s = avctx -> priv_data ;
 AVFrame * frame = data ;
 int out = 0 , ret ;
 int predictor [ 2 ] ;
 int ch = 0 ;
 int stereo = avctx -> channels - 1 ;
 int16_t * output_samples , * samples_end ;
 GetByteContext gb ;
 if ( stereo && ( buf_size & 1 ) ) buf_size -- ;
 bytestream2_init ( & gb , avpkt -> data , buf_size ) ;
 switch ( avctx -> codec -> id ) {
 case AV_CODEC_ID_ROQ_DPCM : out = buf_size - 8 ;
 break ;
 case AV_CODEC_ID_INTERPLAY_DPCM : out = buf_size - 6 - avctx -> channels ;
 break ;
 case AV_CODEC_ID_XAN_DPCM : out = buf_size - 2 * avctx -> channels ;
 break ;
 case AV_CODEC_ID_SOL_DPCM : if ( avctx -> codec_tag != 3 ) out = buf_size * 2 ;
 else out = buf_size ;
 break ;
 }
 if ( out <= 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "packet is too small\n" ) ;
 return AVERROR ( EINVAL ) ;
 }
 frame -> nb_samples = out / avctx -> channels ;
 if ( ( ret = ff_get_buffer ( avctx , frame ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "get_buffer() failed\n" ) ;
 return ret ;
 }
 output_samples = ( int16_t * ) frame -> data [ 0 ] ;
 samples_end = output_samples + out ;
 switch ( avctx -> codec -> id ) {
 case AV_CODEC_ID_ROQ_DPCM : bytestream2_skipu ( & gb , 6 ) ;
 if ( stereo ) {
 predictor [ 1 ] = sign_extend ( bytestream2_get_byteu ( & gb ) << 8 , 16 ) ;
 predictor [ 0 ] = sign_extend ( bytestream2_get_byteu ( & gb ) << 8 , 16 ) ;
 }
 else {
 predictor [ 0 ] = sign_extend ( bytestream2_get_le16u ( & gb ) , 16 ) ;
 }
 while ( output_samples < samples_end ) {
 predictor [ ch ] += s -> roq_square_array [ bytestream2_get_byteu ( & gb ) ] ;
 predictor [ ch ] = av_clip_int16 ( predictor [ ch ] ) ;
 * output_samples ++ = predictor [ ch ] ;
 ch ^= stereo ;
 }
 break ;
 case AV_CODEC_ID_INTERPLAY_DPCM : bytestream2_skipu ( & gb , 6 ) ;
 for ( ch = 0 ;
 ch < avctx -> channels ;
 ch ++ ) {
 predictor [ ch ] = sign_extend ( bytestream2_get_le16u ( & gb ) , 16 ) ;
 * output_samples ++ = predictor [ ch ] ;
 }
 ch = 0 ;
 while ( output_samples < samples_end ) {
 predictor [ ch ] += interplay_delta_table [ bytestream2_get_byteu ( & gb ) ] ;
 predictor [ ch ] = av_clip_int16 ( predictor [ ch ] ) ;
 * output_samples ++ = predictor [ ch ] ;
 ch ^= stereo ;
 }
 break ;
 case AV_CODEC_ID_XAN_DPCM : {
 int shift [ 2 ] = {
 4 , 4 }
 ;
 for ( ch = 0 ;
 ch < avctx -> channels ;
 ch ++ ) predictor [ ch ] = sign_extend ( bytestream2_get_le16u ( & gb ) , 16 ) ;
 ch = 0 ;
 while ( output_samples < samples_end ) {
 int diff = bytestream2_get_byteu ( & gb ) ;
 int n = diff & 3 ;
 if ( n == 3 ) shift [ ch ] ++ ;
 else shift [ ch ] -= ( 2 * n ) ;
 diff = sign_extend ( ( diff & ~ 3 ) << 8 , 16 ) ;
 if ( shift [ ch ] < 0 ) shift [ ch ] = 0 ;
 diff >>= shift [ ch ] ;
 predictor [ ch ] += diff ;
 predictor [ ch ] = av_clip_int16 ( predictor [ ch ] ) ;
 * output_samples ++ = predictor [ ch ] ;
 ch ^= stereo ;
 }
 break ;
 }
 case AV_CODEC_ID_SOL_DPCM : if ( avctx -> codec_tag != 3 ) {
 uint8_t * output_samples_u8 = frame -> data [ 0 ] , * samples_end_u8 = output_samples_u8 + out ;
 while ( output_samples_u8 < samples_end_u8 ) {
 int n = bytestream2_get_byteu ( & gb ) ;
 s -> sample [ 0 ] += s -> sol_table [ n >> 4 ] ;
 s -> sample [ 0 ] = av_clip_uint8 ( s -> sample [ 0 ] ) ;
 * output_samples_u8 ++ = s -> sample [ 0 ] ;
 s -> sample [ stereo ] += s -> sol_table [ n & 0x0F ] ;
 s -> sample [ stereo ] = av_clip_uint8 ( s -> sample [ stereo ] ) ;
 * output_samples_u8 ++ = s -> sample [ stereo ] ;
 }
 }
 else {
 while ( output_samples < samples_end ) {
 int n = bytestream2_get_byteu ( & gb ) ;
 if ( n & 0x80 ) s -> sample [ ch ] -= sol_table_16 [ n & 0x7F ] ;
 else s -> sample [ ch ] += sol_table_16 [ n & 0x7F ] ;
 s -> sample [ ch ] = av_clip_int16 ( s -> sample [ ch ] ) ;
 * output_samples ++ = s -> sample [ ch ] ;
 ch ^= stereo ;
 }
 }
 break ;
 }
 * got_frame_ptr = 1 ;
 return avpkt -> size ;
 }


int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt) { int i, ret = 0; if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n"); return AVERROR(EINVAL); } *got_sub_ptr = 0; avcodec_get_subtitle_defaults(sub); if (avpkt->size) { AVPacket pkt_recoded; AVPacket tmp = *avpkt; int did_split = av_packet_split_side_data(&tmp); //apply_param_change(avctx, &tmp); pkt_recoded = tmp; ret = recode_subtitle(avctx, &pkt_recoded, &tmp); if (ret < 0) { *got_sub_ptr = 0; } else { avctx->pkt = &pkt_recoded; if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE) sub->pts = av_rescale_q(avpkt->pts, avctx->pkt_timebase, AV_TIME_BASE_Q); ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded); av_assert1((ret >= 0) >= !!*got_sub_ptr && !!*got_sub_ptr >= !!sub->num_rects); if (sub->num_rects && !sub->end_display_time && avpkt->duration && avctx->pkt_timebase.num) { AVRational ms = { 1, 1000 }; sub->end_display_time = av_rescale_q(avpkt->duration, avctx->pkt_timebase, ms); } for (i = 0; i < sub->num_rects; i++) { if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) { av_log(avctx, AV_LOG_ERROR, "Invalid UTF-8 in decoded subtitles text; " "maybe missing -sub_charenc option\n"); avsubtitle_free(sub); return AVERROR_INVALIDDATA; } } if (tmp.data != pkt_recoded.data) { // did we recode? /* prevent from destroying side data from original packet */ pkt_recoded.side_data = NULL; pkt_recoded.side_data_elems = 0; av_free_packet(&pkt_recoded); } sub->format = !(avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB); avctx->pkt = NULL; } if (did_split) { ff_packet_free_side_data(&tmp); if(ret == tmp.size) ret = avpkt->size; } if (*got_sub_ptr) avctx->frame_number++; } return ret; }


static uint get_table_structure(char *table, char *db, char *table_type,
                                char *ignore_flag)
{
  my_bool    init=0, delayed, write_data, complete_insert;
  my_ulonglong num_fields;
  char       *result_table, *opt_quoted_table;
  const char *insert_option;
  char	     name_buff[NAME_LEN+3],table_buff[NAME_LEN*2+3];
  char       table_buff2[NAME_LEN*2+3], query_buff[QUERY_LENGTH];
  const char *show_fields_stmt= "SELECT `COLUMN_NAME` AS `Field`, "
                                "`COLUMN_TYPE` AS `Type`, "
                                "`IS_NULLABLE` AS `Null`, "
                                "`COLUMN_KEY` AS `Key`, "
                                "`COLUMN_DEFAULT` AS `Default`, "
                                "`EXTRA` AS `Extra`, "
                                "`COLUMN_COMMENT` AS `Comment` "
                                "FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE "
                                "TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'";
  FILE       *sql_file= md_result_file;
  int        len;
  my_bool    is_log_table;
  MYSQL_RES  *result;
  MYSQL_ROW  row;
  DBUG_ENTER("get_table_structure");
  DBUG_PRINT("enter", ("db: %s  table: %s", db, table));

  *ignore_flag= check_if_ignore_table(table, table_type);

  delayed= opt_delayed;
  if (delayed && (*ignore_flag & IGNORE_INSERT_DELAYED))
  {
    delayed= 0;
    verbose_msg("-- Warning: Unable to use delayed inserts for table '%s' "
                "because it's of type %s\n", table, table_type);
  }

  complete_insert= 0;
  if ((write_data= !(*ignore_flag & IGNORE_DATA)))
  {
    complete_insert= opt_complete_insert;
    if (!insert_pat_inited)
    {
      insert_pat_inited= 1;
      init_dynamic_string_checked(&insert_pat, "", 1024, 1024);
    }
    else
      dynstr_set_checked(&insert_pat, "");
  }

  insert_option= ((delayed && opt_ignore) ? " DELAYED IGNORE " :
                  delayed ? " DELAYED " : opt_ignore ? " IGNORE " : "");

  verbose_msg("-- Retrieving table structure for table %s...\n", table);

  len= my_snprintf(query_buff, sizeof(query_buff),
                   "SET SQL_QUOTE_SHOW_CREATE=%d",
                   (opt_quoted || opt_keywords));
  if (!create_options)
    strmov(query_buff+len,
           "/*!40102 ,SQL_MODE=concat(@@sql_mode, _utf8 ',NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS') */");

  result_table=     quote_name(table, table_buff, 1);
  opt_quoted_table= quote_name(table, table_buff2, 0);

  if (opt_order_by_primary)
    order_by= primary_key_fields(result_table);

  if (!opt_xml && !mysql_query_with_error_report(mysql, 0, query_buff))
  {
    /* using SHOW CREATE statement */
    if (!opt_no_create_info)
    {
      /* Make an sql-file, if path was given iow. option -T was given */
      char buff[20+FN_REFLEN];
      MYSQL_FIELD *field;

      my_snprintf(buff, sizeof(buff), "show create table %s", result_table);

      if (switch_character_set_results(mysql, "binary") ||
          mysql_query_with_error_report(mysql, &result, buff) ||
          switch_character_set_results(mysql, default_charset))
        DBUG_RETURN(0);

      if (path)
      {
        if (!(sql_file= open_sql_file_for_table(table, O_WRONLY)))
          DBUG_RETURN(0);

        write_header(sql_file, db);
      }

      if (strcmp (table_type, "VIEW") == 0)         /* view */
        print_comment(sql_file, 0,
                      "\n--\n-- Temporary table structure for view %s\n--\n\n",
                      fix_identifier_with_newline(result_table));
      else
        print_comment(sql_file, 0,
                      "\n--\n-- Table structure for table %s\n--\n\n",
                      fix_identifier_with_newline(result_table));

      if (opt_drop)
      {
      /*
        Even if the "table" is a view, we do a DROP TABLE here.  The
        view-specific code below fills in the DROP VIEW.
        We will skip the DROP TABLE for general_log and slow_log, since
        those stmts will fail, in case we apply dump by enabling logging.
       */
        if (!general_log_or_slow_log_tables(db, table))
          fprintf(sql_file, "DROP TABLE IF EXISTS %s;\n",
                  opt_quoted_table);
        check_io(sql_file);
      }

      field= mysql_fetch_field_direct(result, 0);
      if (strcmp(field->name, "View") == 0)
      {
        char *scv_buff= NULL;
        my_ulonglong n_cols;

        verbose_msg("-- It's a view, create dummy table for view\n");

        /* save "show create" statement for later */
        if ((row= mysql_fetch_row(result)) && (scv_buff=row[1]))
          scv_buff= my_strdup(scv_buff, MYF(0));

        mysql_free_result(result);

        /*
          Create a table with the same name as the view and with columns of
          the same name in order to satisfy views that depend on this view.
          The table will be removed when the actual view is created.

          The properties of each column, are not preserved in this temporary
          table, because they are not necessary.

          This will not be necessary once we can determine dependencies
          between views and can simply dump them in the appropriate order.
        */
        my_snprintf(query_buff, sizeof(query_buff),
                    "SHOW FIELDS FROM %s", result_table);
        if (switch_character_set_results(mysql, "binary") ||
            mysql_query_with_error_report(mysql, &result, query_buff) ||
            switch_character_set_results(mysql, default_charset))
        {
          /*
            View references invalid or privileged table/col/fun (err 1356),
            so we cannot create a stand-in table.  Be defensive and dump
            a comment with the view's 'show create' statement. (Bug #17371)
          */

          if (mysql_errno(mysql) == ER_VIEW_INVALID)
            fprintf(sql_file, "\n-- failed on view %s: %s\n\n", result_table, scv_buff ? scv_buff : "");

          my_free(scv_buff);

          DBUG_RETURN(0);
        }
        else
          my_free(scv_buff);

        n_cols= mysql_num_rows(result);
        if (0 != n_cols)
        {

          /*
            The actual formula is based on the column names and how the .FRM
            files are stored and is too volatile to be repeated here.
            Thus we simply warn the user if the columns exceed a limit we
            know works most of the time.
          */
          if (n_cols >= 1000)
            fprintf(stderr,
                    "-- Warning: Creating a stand-in table for view %s may"
                    " fail when replaying the dump file produced because "
                    "of the number of columns exceeding 1000. Exercise "
                    "caution when replaying the produced dump file.\n",
                    table);
          if (opt_drop)
          {
            /*
              We have already dropped any table of the same name above, so
              here we just drop the view.
            */

            fprintf(sql_file, "/*!50001 DROP VIEW IF EXISTS %s*/;\n",
                    opt_quoted_table);
            check_io(sql_file);
          }

          fprintf(sql_file,
                  "SET @saved_cs_client     = @@character_set_client;\n"
                  "SET character_set_client = utf8;\n"
                  "/*!50001 CREATE TABLE %s (\n",
                  result_table);

          /*
            Get first row, following loop will prepend comma - keeps from
            having to know if the row being printed is last to determine if
            there should be a _trailing_ comma.
          */

          row= mysql_fetch_row(result);

          /*
            The actual column type doesn't matter anyway, since the table will
            be dropped at run time.
            We do tinyint to avoid hitting the row size limit.
          */
          fprintf(sql_file, "  %s tinyint NOT NULL",
                  quote_name(row[0], name_buff, 0));

          while((row= mysql_fetch_row(result)))
          {
            /* col name, col type */
            fprintf(sql_file, ",\n  %s tinyint NOT NULL",
                    quote_name(row[0], name_buff, 0));
          }

          /*
            Stand-in tables are always MyISAM tables as the default
            engine might have a column-limit that's lower than the
            number of columns in the view, and MyISAM support is
            guaranteed to be in the server anyway.
          */
          fprintf(sql_file,
                  "\n) ENGINE=MyISAM */;\n"
                  "SET character_set_client = @saved_cs_client;\n");

          check_io(sql_file);
        }

        mysql_free_result(result);

        if (path)
          my_fclose(sql_file, MYF(MY_WME));

        seen_views= 1;
        DBUG_RETURN(0);
      }

      row= mysql_fetch_row(result);

      is_log_table= general_log_or_slow_log_tables(db, table);
      if (is_log_table)
        row[1]+= 13; /* strlen("CREATE TABLE ")= 13 */
      if (opt_compatible_mode & 3)
      {
        fprintf(sql_file,
                is_log_table ? "CREATE TABLE IF NOT EXISTS %s;\n" : "%s;\n",
                row[1]);
      }
      else
      {
        fprintf(sql_file,
                "/*!40101 SET @saved_cs_client     = @@character_set_client */;\n"
                "/*!40101 SET character_set_client = utf8 */;\n"
                "%s%s;\n"
                "/*!40101 SET character_set_client = @saved_cs_client */;\n",
                is_log_table ? "CREATE TABLE IF NOT EXISTS " : "",
                row[1]);
      }

      check_io(sql_file);
      mysql_free_result(result);
    }
    my_snprintf(query_buff, sizeof(query_buff), "show fields from %s",
                result_table);
    if (mysql_query_with_error_report(mysql, &result, query_buff))
    {
      if (path)
        my_fclose(sql_file, MYF(MY_WME));
      DBUG_RETURN(0);
    }

    /*
      If write_data is true, then we build up insert statements for
      the table's data. Note: in subsequent lines of code, this test
      will have to be performed each time we are appending to
      insert_pat.
    */
    if (write_data)
    {
      if (opt_replace_into)
        dynstr_append_checked(&insert_pat, "REPLACE ");
      else
        dynstr_append_checked(&insert_pat, "INSERT ");
      dynstr_append_checked(&insert_pat, insert_option);
      dynstr_append_checked(&insert_pat, "INTO ");
      dynstr_append_checked(&insert_pat, opt_quoted_table);
      if (complete_insert)
      {
        dynstr_append_checked(&insert_pat, " (");
      }
      else
      {
        dynstr_append_checked(&insert_pat, " VALUES ");
        if (!extended_insert)
          dynstr_append_checked(&insert_pat, "(");
      }
    }

    while ((row= mysql_fetch_row(result)))
    {
      if (complete_insert)
      {
        if (init)
        {
          dynstr_append_checked(&insert_pat, ", ");
        }
        init=1;
        dynstr_append_checked(&insert_pat,
                      quote_name(row[SHOW_FIELDNAME], name_buff, 0));
      }
    }
    num_fields= mysql_num_rows(result);
    mysql_free_result(result);
  }
  else
  {
    verbose_msg("%s: Warning: Can't set SQL_QUOTE_SHOW_CREATE option (%s)\n",
                my_progname, mysql_error(mysql));

    my_snprintf(query_buff, sizeof(query_buff), show_fields_stmt, db, table);

    if (mysql_query_with_error_report(mysql, &result, query_buff))
      DBUG_RETURN(0);

    /* Make an sql-file, if path was given iow. option -T was given */
    if (!opt_no_create_info)
    {
      if (path)
      {
        if (!(sql_file= open_sql_file_for_table(table, O_WRONLY)))
          DBUG_RETURN(0);
        write_header(sql_file, db);
      }

      print_comment(sql_file, 0,
                    "\n--\n-- Table structure for table %s\n--\n\n",
                    fix_identifier_with_newline(result_table));
      if (opt_drop)
        fprintf(sql_file, "DROP TABLE IF EXISTS %s;\n", result_table);
      if (!opt_xml)
        fprintf(sql_file, "CREATE TABLE %s (\n", result_table);
      else
        print_xml_tag(sql_file, "\t", "\n", "table_structure", "name=", table,
                NullS);
      check_io(sql_file);
    }

    if (write_data)
    {
      if (opt_replace_into)
        dynstr_append_checked(&insert_pat, "REPLACE ");
      else
        dynstr_append_checked(&insert_pat, "INSERT ");
      dynstr_append_checked(&insert_pat, insert_option);
      dynstr_append_checked(&insert_pat, "INTO ");
      dynstr_append_checked(&insert_pat, result_table);
      if (complete_insert)
        dynstr_append_checked(&insert_pat, " (");
      else
      {
        dynstr_append_checked(&insert_pat, " VALUES ");
        if (!extended_insert)
          dynstr_append_checked(&insert_pat, "(");
      }
    }

    while ((row= mysql_fetch_row(result)))
    {
      ulong *lengths= mysql_fetch_lengths(result);
      if (init)
      {
        if (!opt_xml && !opt_no_create_info)
        {
          fputs(",\n",sql_file);
          check_io(sql_file);
        }
        if (complete_insert)
          dynstr_append_checked(&insert_pat, ", ");
      }
      init=1;
      if (complete_insert)
        dynstr_append_checked(&insert_pat,
                      quote_name(row[SHOW_FIELDNAME], name_buff, 0));
      if (!opt_no_create_info)
      {
        if (opt_xml)
        {
          print_xml_row(sql_file, "field", result, &row, NullS);
          continue;
        }

        if (opt_keywords)
          fprintf(sql_file, "  %s.%s %s", result_table,
                  quote_name(row[SHOW_FIELDNAME],name_buff, 0),
                  row[SHOW_TYPE]);
        else
          fprintf(sql_file, "  %s %s", quote_name(row[SHOW_FIELDNAME],
                                                  name_buff, 0),
                  row[SHOW_TYPE]);
        if (row[SHOW_DEFAULT])
        {
          fputs(" DEFAULT ", sql_file);
          unescape(sql_file, row[SHOW_DEFAULT], lengths[SHOW_DEFAULT]);
        }
        if (!row[SHOW_NULL][0])
          fputs(" NOT NULL", sql_file);
        if (row[SHOW_EXTRA][0])
          fprintf(sql_file, " %s",row[SHOW_EXTRA]);
        check_io(sql_file);
      }
    }
    num_fields= mysql_num_rows(result);
    mysql_free_result(result);
    if (!opt_no_create_info)
    {
      /* Make an sql-file, if path was given iow. option -T was given */
      char buff[20+FN_REFLEN];
      uint keynr,primary_key;
      my_snprintf(buff, sizeof(buff), "show keys from %s", result_table);
      if (mysql_query_with_error_report(mysql, &result, buff))
      {
        if (mysql_errno(mysql) == ER_WRONG_OBJECT)
        {
          /* it is VIEW */
          fputs("\t\t<options Comment=\"view\" />\n", sql_file);
          goto continue_xml;
        }
        fprintf(stderr, "%s: Can't get keys for table %s (%s)\n",
                my_progname, result_table, mysql_error(mysql));
        if (path)
          my_fclose(sql_file, MYF(MY_WME));
        DBUG_RETURN(0);
      }

      /* Find first which key is primary key */
      keynr=0;
      primary_key=INT_MAX;
      while ((row= mysql_fetch_row(result)))
      {
        if (atoi(row[3]) == 1)
        {
          keynr++;
#ifdef FORCE_PRIMARY_KEY
          if (atoi(row[1]) == 0 && primary_key == INT_MAX)
            primary_key=keynr;
#endif
          if (!strcmp(row[2],"PRIMARY"))
          {
            primary_key=keynr;
            break;
          }
        }
      }
      mysql_data_seek(result,0);
      keynr=0;
      while ((row= mysql_fetch_row(result)))
      {
        if (opt_xml)
        {
          print_xml_row(sql_file, "key", result, &row, NullS);
          continue;
        }

        if (atoi(row[3]) == 1)
        {
          if (keynr++)
            putc(')', sql_file);
          if (atoi(row[1]))       /* Test if duplicate key */
            /* Duplicate allowed */
            fprintf(sql_file, ",\n  KEY %s (",quote_name(row[2],name_buff,0));
          else if (keynr == primary_key)
            fputs(",\n  PRIMARY KEY (",sql_file); /* First UNIQUE is primary */
          else
            fprintf(sql_file, ",\n  UNIQUE %s (",quote_name(row[2],name_buff,
                                                            0));
        }
        else
          putc(',', sql_file);
        fputs(quote_name(row[4], name_buff, 0), sql_file);
        if (row[7])
          fprintf(sql_file, " (%s)",row[7]);      /* Sub key */
        check_io(sql_file);
      }
      mysql_free_result(result);
      if (!opt_xml)
      {
        if (keynr)
          putc(')', sql_file);
        fputs("\n)",sql_file);
        check_io(sql_file);
      }

      /* Get MySQL specific create options */
      if (create_options)
      {
        char show_name_buff[NAME_LEN*2+2+24];

        /* Check memory for quote_for_like() */
        my_snprintf(buff, sizeof(buff), "show table status like %s",
                    quote_for_like(table, show_name_buff));

        if (mysql_query_with_error_report(mysql, &result, buff))
        {
          if (mysql_errno(mysql) != ER_PARSE_ERROR)
          {                                     /* If old MySQL version */
            verbose_msg("-- Warning: Couldn't get status information for " \
                        "table %s (%s)\n", result_table,mysql_error(mysql));
          }
        }
        else if (!(row= mysql_fetch_row(result)))
        {
          fprintf(stderr,
                  "Error: Couldn't read status information for table %s (%s)\n",
                  result_table,mysql_error(mysql));
        }
        else
        {
          if (opt_xml)
            print_xml_row(sql_file, "options", result, &row, NullS);
          else
          {
            fputs("/*!",sql_file);
            print_value(sql_file,result,row,"engine=","Engine",0);
            print_value(sql_file,result,row,"","Create_options",0);
            print_value(sql_file,result,row,"comment=","Comment",1);
            fputs(" */",sql_file);
            check_io(sql_file);
          }
        }
        mysql_free_result(result);              /* Is always safe to free */
      }
continue_xml:
      if (!opt_xml)
        fputs(";\n", sql_file);
      else
        fputs("\t</table_structure>\n", sql_file);
      check_io(sql_file);
    }
  }
  if (complete_insert)
  {
    dynstr_append_checked(&insert_pat, ") VALUES ");
    if (!extended_insert)
      dynstr_append_checked(&insert_pat, "(");
  }
  if (sql_file != md_result_file)
  {
    fputs("\n", sql_file);
    write_footer(sql_file);
    my_fclose(sql_file, MYF(MY_WME));
  }
  DBUG_RETURN((uint) num_fields);
} /* get_table_structure */


static my_bool get_view_structure(char *table, char* db)
{
  MYSQL_RES  *table_res;
  MYSQL_ROW  row;
  MYSQL_FIELD *field;
  char       *result_table, *opt_quoted_table;
  char       table_buff[NAME_LEN*2+3];
  char       table_buff2[NAME_LEN*2+3];
  char       query[QUERY_LENGTH];
  FILE       *sql_file= md_result_file;
  DBUG_ENTER("get_view_structure");

  if (opt_no_create_info) /* Don't write table creation info */
    DBUG_RETURN(0);

  verbose_msg("-- Retrieving view structure for table %s...\n", table);

#ifdef NOT_REALLY_USED_YET
  dynstr_append_checked(&insert_pat, "SET SQL_QUOTE_SHOW_CREATE=");
  dynstr_append_checked(&insert_pat, (opt_quoted || opt_keywords)? "1":"0");
#endif

  result_table=     quote_name(table, table_buff, 1);
  opt_quoted_table= quote_name(table, table_buff2, 0);

  if (switch_character_set_results(mysql, "binary"))
    DBUG_RETURN(1);

  my_snprintf(query, sizeof(query), "SHOW CREATE TABLE %s", result_table);

  if (mysql_query_with_error_report(mysql, &table_res, query))
  {
    switch_character_set_results(mysql, default_charset);
    DBUG_RETURN(0);
  }

  /* Check if this is a view */
  field= mysql_fetch_field_direct(table_res, 0);
  if (strcmp(field->name, "View") != 0)
  {
    switch_character_set_results(mysql, default_charset);
    verbose_msg("-- It's base table, skipped\n");
    DBUG_RETURN(0);
  }

  /* If requested, open separate .sql file for this view */
  if (path)
  {
    if (!(sql_file= open_sql_file_for_table(table, O_WRONLY)))
      DBUG_RETURN(1);

    write_header(sql_file, db);
  }

  print_comment(sql_file, 0,
                "\n--\n-- Final view structure for view %s\n--\n\n",
                fix_identifier_with_newline(result_table));

  /* Table might not exist if this view was dumped with --tab. */
  fprintf(sql_file, "/*!50001 DROP TABLE IF EXISTS %s*/;\n", opt_quoted_table);
  if (opt_drop)
  {
    fprintf(sql_file, "/*!50001 DROP VIEW IF EXISTS %s*/;\n",
            opt_quoted_table);
    check_io(sql_file);
  }

  my_snprintf(query, sizeof(query),
              "SELECT CHECK_OPTION, DEFINER, SECURITY_TYPE, "
              "       CHARACTER_SET_CLIENT, COLLATION_CONNECTION "
              "FROM information_schema.views "
              "WHERE table_name=\"%s\" AND table_schema=\"%s\"", table, db);

  if (mysql_query(mysql, query))
  {
    /*
      Use the raw output from SHOW CREATE TABLE if
       information_schema query fails.
     */
    row= mysql_fetch_row(table_res);
    fprintf(sql_file, "/*!50001 %s */;\n", row[1]);
    check_io(sql_file);
    mysql_free_result(table_res);
  }
  else
  {
    char *ptr;
    ulong *lengths;
    char search_buf[256], replace_buf[256];
    ulong search_len, replace_len;
    DYNAMIC_STRING ds_view;

    /* Save the result of SHOW CREATE TABLE in ds_view */
    row= mysql_fetch_row(table_res);
    lengths= mysql_fetch_lengths(table_res);
    init_dynamic_string_checked(&ds_view, row[1], lengths[1] + 1, 1024);
    mysql_free_result(table_res);

    /* Get the result from "select ... information_schema" */
    if (!(table_res= mysql_store_result(mysql)) ||
        !(row= mysql_fetch_row(table_res)))
    {
      if (table_res)
        mysql_free_result(table_res);
      dynstr_free(&ds_view);
      DB_error(mysql, "when trying to save the result of SHOW CREATE TABLE in ds_view.");
      DBUG_RETURN(1);
    }

    lengths= mysql_fetch_lengths(table_res);

    /*
      "WITH %s CHECK OPTION" is available from 5.0.2
      Surround it with !50002 comments
    */
    if (strcmp(row[0], "NONE"))
    {

      ptr= search_buf;
      search_len= (ulong)(strxmov(ptr, "WITH ", row[0],
                                  " CHECK OPTION", NullS) - ptr);
      ptr= replace_buf;
      replace_len=(ulong)(strxmov(ptr, "*/\n/*!50002 WITH ", row[0],
                                  " CHECK OPTION", NullS) - ptr);
      replace(&ds_view, search_buf, search_len, replace_buf, replace_len);
    }

    /*
      "DEFINER=%s SQL SECURITY %s" is available from 5.0.13
      Surround it with !50013 comments
    */
    {
      size_t     user_name_len;
      char       user_name_str[USERNAME_LENGTH + 1];
      char       quoted_user_name_str[USERNAME_LENGTH * 2 + 3];
      size_t     host_name_len;
      char       host_name_str[HOSTNAME_LENGTH + 1];
      char       quoted_host_name_str[HOSTNAME_LENGTH * 2 + 3];

      parse_user(row[1], lengths[1], user_name_str, &user_name_len,
                 host_name_str, &host_name_len);

      ptr= search_buf;
      search_len=
        (ulong)(strxmov(ptr, "DEFINER=",
                        quote_name(user_name_str, quoted_user_name_str, FALSE),
                        "@",
                        quote_name(host_name_str, quoted_host_name_str, FALSE),
                        " SQL SECURITY ", row[2], NullS) - ptr);
      ptr= replace_buf;
      replace_len=
        (ulong)(strxmov(ptr, "*/\n/*!50013 DEFINER=",
                        quote_name(user_name_str, quoted_user_name_str, FALSE),
                        "@",
                        quote_name(host_name_str, quoted_host_name_str, FALSE),
                        " SQL SECURITY ", row[2],
                        " */\n/*!50001", NullS) - ptr);
      replace(&ds_view, search_buf, search_len, replace_buf, replace_len);
    }

    /* Dump view structure to file */

    fprintf(sql_file,
            "/*!50001 SET @saved_cs_client          = @@character_set_client */;\n"
            "/*!50001 SET @saved_cs_results         = @@character_set_results */;\n"
            "/*!50001 SET @saved_col_connection     = @@collation_connection */;\n"
            "/*!50001 SET character_set_client      = %s */;\n"
            "/*!50001 SET character_set_results     = %s */;\n"
            "/*!50001 SET collation_connection      = %s */;\n"
            "/*!50001 %s */;\n"
            "/*!50001 SET character_set_client      = @saved_cs_client */;\n"
            "/*!50001 SET character_set_results     = @saved_cs_results */;\n"
            "/*!50001 SET collation_connection      = @saved_col_connection */;\n",
            (const char *) row[3],
            (const char *) row[3],
            (const char *) row[4],
            (const char *) ds_view.str);

    check_io(sql_file);
    mysql_free_result(table_res);
    dynstr_free(&ds_view);
  }

  if (switch_character_set_results(mysql, default_charset))
    DBUG_RETURN(1);

  /* If a separate .sql file was opened, close it now */
  if (sql_file != md_result_file)
  {
    fputs("\n", sql_file);
    write_footer(sql_file);
    my_fclose(sql_file, MYF(MY_WME));
  }
  DBUG_RETURN(0);
}


proto_item * proto_tree_add_item_ret_string ( proto_tree * tree , int hfindex , tvbuff_t * tvb , const gint start , gint length , const guint encoding , wmem_allocator_t * scope , const guint8 * * retval ) {
 return proto_tree_add_item_ret_string_and_length ( tree , hfindex , tvb , start , length , encoding , scope , retval , & length ) ;
 }


my_bool grant_reload ( THD * thd ) {
 TABLE_LIST tables [ 2 ] ;
 HASH old_column_priv_hash ;
 MEM_ROOT old_mem ;
 my_bool return_val = 1 ;
 DBUG_ENTER ( "grant_reload" ) ;
 if ( ! initialized ) DBUG_RETURN ( 0 ) ;
 bzero ( ( char * ) tables , sizeof ( tables ) ) ;
 tables [ 0 ] . alias = tables [ 0 ] . table_name = ( char * ) "tables_priv" ;
 tables [ 1 ] . alias = tables [ 1 ] . table_name = ( char * ) "columns_priv" ;
 tables [ 0 ] . db = tables [ 1 ] . db = ( char * ) "mysql" ;
 tables [ 0 ] . next_local = tables [ 0 ] . next_global = tables + 1 ;
 tables [ 0 ] . lock_type = tables [ 1 ] . lock_type = TL_READ ;
 tables [ 0 ] . skip_temporary = tables [ 1 ] . skip_temporary = TRUE ;
 if ( simple_open_n_lock_tables ( thd , tables ) ) goto end ;
 rw_wrlock ( & LOCK_grant ) ;
 old_column_priv_hash = column_priv_hash ;
 old_mem = memex ;
 init_sql_alloc ( & memex , ACL_ALLOC_BLOCK_SIZE , 0 ) ;
 if ( ( return_val = grant_load ( thd , tables ) ) ) {
 DBUG_PRINT ( "error" , ( "Reverting to old privileges" ) ) ;
 grant_free ( ) ;
 column_priv_hash = old_column_priv_hash ;
 memex = old_mem ;
 }
 else {
 hash_free ( & old_column_priv_hash ) ;
 free_root ( & old_mem , MYF ( 0 ) ) ;
 }
 rw_unlock ( & LOCK_grant ) ;
 close_thread_tables ( thd ) ;
 if ( grant_reload_procs_priv ( thd ) ) return_val = 1 ;
 rw_wrlock ( & LOCK_grant ) ;
 grant_version ++ ;
 rw_unlock ( & LOCK_grant ) ;
 end : DBUG_RETURN ( return_val ) ;
 }


MYSQL_DATA *cli_read_rows(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
			  unsigned int fields)
{
  uint	field;
  ulong pkt_len;
  ulong len;
  uchar *cp;
  char	*to, *end_to;
  MYSQL_DATA *result;
  MYSQL_ROWS **prev_ptr,*cur;
  NET *net = &mysql->net;
  DBUG_ENTER("cli_read_rows");

  if ((pkt_len= cli_safe_read(mysql)) == packet_error)
    DBUG_RETURN(0);
  if (!(result=(MYSQL_DATA*) my_malloc(sizeof(MYSQL_DATA),
				       MYF(MY_WME | MY_ZEROFILL))))
  {
    set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
    DBUG_RETURN(0);
  }
  init_alloc_root(&result->alloc,8192,0);	/* Assume rowlength < 8192 */
  result->alloc.min_malloc=sizeof(MYSQL_ROWS);
  prev_ptr= &result->data;
  result->rows=0;
  result->fields=fields;

  /*
    The last EOF packet is either a single 254 character or (in MySQL 4.1)
    254 followed by 1-7 status bytes.

    This doesn't conflict with normal usage of 254 which stands for a
    string where the length of the string is 8 bytes. (see net_field_length())
  */

  while (*(cp=net->read_pos) != 254 || pkt_len >= 8)
  {
    result->rows++;
    if (!(cur= (MYSQL_ROWS*) alloc_root(&result->alloc,
					sizeof(MYSQL_ROWS))) ||
	!(cur->data= ((MYSQL_ROW)
		      alloc_root(&result->alloc,
				 (fields+1)*sizeof(char *)+pkt_len))))
    {
      free_rows(result);
      set_mysql_error(mysql, CR_OUT_OF_MEMORY, unknown_sqlstate);
      DBUG_RETURN(0);
    }
    *prev_ptr=cur;
    prev_ptr= &cur->next;
    to= (char*) (cur->data+fields+1);
    end_to=to+pkt_len-1;
    for (field=0 ; field < fields ; field++)
    {
      if ((len=(ulong) net_field_length(&cp)) == NULL_LENGTH)
      {						/* null field */
	cur->data[field] = 0;
      }
      else
      {
	cur->data[field] = to;
        if (len > (ulong) (end_to - to))
        {
          free_rows(result);
          set_mysql_error(mysql, CR_MALFORMED_PACKET, unknown_sqlstate);
          DBUG_RETURN(0);
        }
	memcpy(to,(char*) cp,len); to[len]=0;
	to+=len+1;
	cp+=len;
	if (mysql_fields)
	{
	  if (mysql_fields[field].max_length < len)
	    mysql_fields[field].max_length=len;
	}
      }
    }
    cur->data[field]=to;			/* End of last field */
    if ((pkt_len=cli_safe_read(mysql)) == packet_error)
    {
      free_rows(result);
      DBUG_RETURN(0);
    }
  }
  *prev_ptr=0;					/* last pointer is null */
  if (pkt_len > 1)				/* MySQL 4.1 protocol */
  {
    mysql->warning_count= uint2korr(cp+1);
    mysql->server_status= uint2korr(cp+3);
    DBUG_PRINT("info",("status: %u  warning_count:  %u",
		       mysql->server_status, mysql->warning_count));
  }
  DBUG_PRINT("exit", ("Got %lu rows", (ulong) result->rows));
  DBUG_RETURN(result);


mysql_list_fields(MYSQL *mysql, const char *table, const char *wild)
{
  MYSQL_RES *result;
  MYSQL_DATA *query;
  char buff[255];
  int length= 0;

  LINT_INIT(query);

  length= snprintf(buff, 128, "%s%c%s", table, '\0', wild ? wild : "");

  if (ma_simple_command(mysql, COM_FIELD_LIST,buff,length,1,0) ||
      !(query = mysql->methods->db_read_rows(mysql,(MYSQL_FIELD*) 0,8)))
    return(NULL);

  free_old_query(mysql);
  if (!(result = (MYSQL_RES *) calloc(1, sizeof(MYSQL_RES))))
  {
    free_rows(query);
    return(NULL);
  }
  result->field_alloc=mysql->field_alloc;
  mysql->fields=0;
  result->field_count = (uint) query->rows;
  result->fields= unpack_fields(query,&result->field_alloc,
				result->field_count,1,
				(my_bool) test(mysql->server_capabilities &
					       CLIENT_LONG_FLAG));
  result->eof=1;
  return(result);
}


MYSQL_DATA *mthd_my_read_rows(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
			     uint fields)
{
  uint	field;
  ulong pkt_len;
  ulong len;
  uchar *cp;
  char	*to, *end_to;
  MYSQL_DATA *result;
  MYSQL_ROWS **prev_ptr,*cur;
  NET *net = &mysql->net;

  if ((pkt_len= ma_net_safe_read(mysql)) == packet_error)
    return(0);
  if (!(result=(MYSQL_DATA*) calloc(1, sizeof(MYSQL_DATA))))
  {
    SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);
    return(0);
  }
  ma_init_alloc_root(&result->alloc,8192,0);	/* Assume rowlength < 8192 */
  result->alloc.min_malloc=sizeof(MYSQL_ROWS);
  prev_ptr= &result->data;
  result->rows=0;
  result->fields=fields;

  while (*(cp=net->read_pos) != 254 || pkt_len >= 8)
  {
    result->rows++;
    if (!(cur= (MYSQL_ROWS*) ma_alloc_root(&result->alloc,
					    sizeof(MYSQL_ROWS))) ||
	      !(cur->data= ((MYSQL_ROW)
		      ma_alloc_root(&result->alloc,
				     (fields+1)*sizeof(char *)+fields+pkt_len))))
    {
      free_rows(result);
      SET_CLIENT_ERROR(mysql, CR_OUT_OF_MEMORY, SQLSTATE_UNKNOWN, 0);
      return(0);
    }
    *prev_ptr=cur;
    prev_ptr= &cur->next;
    to= (char*) (cur->data+fields+1);
    end_to=to+fields+pkt_len-1;
    for (field=0 ; field < fields ; field++)
    {
      if ((len=(ulong) net_field_length(&cp)) == NULL_LENGTH)
      {						/* null field */
        cur->data[field] = 0;
      }
      else
      {
        cur->data[field] = to;
        if (len > (ulong) (end_to - to))
        {
          free_rows(result);
          SET_CLIENT_ERROR(mysql, CR_UNKNOWN_ERROR, SQLSTATE_UNKNOWN, 0);
          return(0);
        }
        memcpy(to,(char*) cp,len); to[len]=0;
        to+=len+1;
        cp+=len;
        if (mysql_fields)
        {
          if (mysql_fields[field].max_length < len)
            mysql_fields[field].max_length=len;
         }
      }
    }
    cur->data[field]=to;			/* End of last field */
    if ((pkt_len=ma_net_safe_read(mysql)) == packet_error)
    {
      free_rows(result);
      return(0);
    }
  }
  *prev_ptr=0;					/* last pointer is null */
  /* save status */
  if (pkt_len > 1)
  {
    cp++;
    mysql->warning_count= uint2korr(cp);
    cp+= 2;
    mysql->server_status= uint2korr(cp);
  }
  return(result);
}


static inline void reloc_pc26(tcg_insn_unit *code_ptr, tcg_insn_unit *target) { ptrdiff_t offset = target - code_ptr; assert(offset == sextract64(offset, 0, 26)); /* read instruction, mask away previous PC_REL26 parameter contents, set the proper offset, then write back the instruction. */ *code_ptr = deposit32(*code_ptr, 0, 26, offset); }


static inline unsigned long align_sigframe(unsigned long sp) { unsigned long i; i = sp & ~3UL; return i; }


static inline void gen_405_mulladd_insn(DisasContext *ctx, int opc2, int opc3, int ra, int rb, int rt, int Rc) { TCGv t0, t1; t0 = tcg_temp_local_new(); t1 = tcg_temp_local_new(); switch (opc3 & 0x0D) { case 0x05: /* macchw - macchw. - macchwo - macchwo. */ /* macchws - macchws. - macchwso - macchwso. */ /* nmacchw - nmacchw. - nmacchwo - nmacchwo. */ /* nmacchws - nmacchws. - nmacchwso - nmacchwso. */ /* mulchw - mulchw. */ tcg_gen_ext16s_tl(t0, cpu_gpr[ra]); tcg_gen_sari_tl(t1, cpu_gpr[rb], 16); tcg_gen_ext16s_tl(t1, t1); break; case 0x04: /* macchwu - macchwu. - macchwuo - macchwuo. */ /* macchwsu - macchwsu. - macchwsuo - macchwsuo. */ /* mulchwu - mulchwu. */ tcg_gen_ext16u_tl(t0, cpu_gpr[ra]); tcg_gen_shri_tl(t1, cpu_gpr[rb], 16); tcg_gen_ext16u_tl(t1, t1); break; case 0x01: /* machhw - machhw. - machhwo - machhwo. */ /* machhws - machhws. - machhwso - machhwso. */ /* nmachhw - nmachhw. - nmachhwo - nmachhwo. */ /* nmachhws - nmachhws. - nmachhwso - nmachhwso. */ /* mulhhw - mulhhw. */ tcg_gen_sari_tl(t0, cpu_gpr[ra], 16); tcg_gen_ext16s_tl(t0, t0); tcg_gen_sari_tl(t1, cpu_gpr[rb], 16); tcg_gen_ext16s_tl(t1, t1); break; case 0x00: /* machhwu - machhwu. - machhwuo - machhwuo. */ /* machhwsu - machhwsu. - machhwsuo - machhwsuo. */ /* mulhhwu - mulhhwu. */ tcg_gen_shri_tl(t0, cpu_gpr[ra], 16); tcg_gen_ext16u_tl(t0, t0); tcg_gen_shri_tl(t1, cpu_gpr[rb], 16); tcg_gen_ext16u_tl(t1, t1); break; case 0x0D: /* maclhw - maclhw. - maclhwo - maclhwo. */ /* maclhws - maclhws. - maclhwso - maclhwso. */ /* nmaclhw - nmaclhw. - nmaclhwo - nmaclhwo. */ /* nmaclhws - nmaclhws. - nmaclhwso - nmaclhwso. */ /* mullhw - mullhw. */ tcg_gen_ext16s_tl(t0, cpu_gpr[ra]); tcg_gen_ext16s_tl(t1, cpu_gpr[rb]); break; case 0x0C: /* maclhwu - maclhwu. - maclhwuo - maclhwuo. */ /* maclhwsu - maclhwsu. - maclhwsuo - maclhwsuo. */ /* mullhwu - mullhwu. */ tcg_gen_ext16u_tl(t0, cpu_gpr[ra]); tcg_gen_ext16u_tl(t1, cpu_gpr[rb]); break; } if (opc2 & 0x04) { /* (n)multiply-and-accumulate (0x0C / 0x0E) */ tcg_gen_mul_tl(t1, t0, t1); if (opc2 & 0x02) { /* nmultiply-and-accumulate (0x0E) */ tcg_gen_sub_tl(t0, cpu_gpr[rt], t1); } else { /* multiply-and-accumulate (0x0C) */ tcg_gen_add_tl(t0, cpu_gpr[rt], t1); } if (opc3 & 0x12) { /* Check overflow and/or saturate */ int l1 = gen_new_label(); if (opc3 & 0x10) { /* Start with XER OV disabled, the most likely case */ tcg_gen_movi_tl(cpu_ov, 0); } if (opc3 & 0x01) { /* Signed */ tcg_gen_xor_tl(t1, cpu_gpr[rt], t1); tcg_gen_brcondi_tl(TCG_COND_GE, t1, 0, l1); tcg_gen_xor_tl(t1, cpu_gpr[rt], t0); tcg_gen_brcondi_tl(TCG_COND_LT, t1, 0, l1); if (opc3 & 0x02) { /* Saturate */ tcg_gen_sari_tl(t0, cpu_gpr[rt], 31); tcg_gen_xori_tl(t0, t0, 0x7fffffff); } } else { /* Unsigned */ tcg_gen_brcond_tl(TCG_COND_GEU, t0, t1, l1); if (opc3 & 0x02) { /* Saturate */ tcg_gen_movi_tl(t0, UINT32_MAX); } } if (opc3 & 0x10) { /* Check overflow */ tcg_gen_movi_tl(cpu_ov, 1); tcg_gen_movi_tl(cpu_so, 1); } gen_set_label(l1); tcg_gen_mov_tl(cpu_gpr[rt], t0); } } else { tcg_gen_mul_tl(cpu_gpr[rt], t0, t1); } tcg_temp_free(t0); tcg_temp_free(t1); if (unlikely(Rc) != 0) { /* Update Rc0 */ gen_set_Rc0(ctx, cpu_gpr[rt]); } }


void opj_get_all_encoding_parameters(   const opj_image_t *p_image,
                                        const opj_cp_t *p_cp,
                                        OPJ_UINT32 tileno,
                                        OPJ_INT32 * p_tx0,
                                        OPJ_INT32 * p_tx1,
                                        OPJ_INT32 * p_ty0,
                                        OPJ_INT32 * p_ty1,
                                        OPJ_UINT32 * p_dx_min,
                                        OPJ_UINT32 * p_dy_min,
                                        OPJ_UINT32 * p_max_prec,
                                        OPJ_UINT32 * p_max_res,
                                        OPJ_UINT32 ** p_resolutions )
{
	/* loop*/
	OPJ_UINT32 compno, resno;

	/* pointers*/
	const opj_tcp_t *tcp = 00;
	const opj_tccp_t * l_tccp = 00;
	const opj_image_comp_t * l_img_comp = 00;

	/* to store l_dx, l_dy, w and h for each resolution and component.*/
	OPJ_UINT32 * lResolutionPtr;

	/* position in x and y of tile*/
	OPJ_UINT32 p, q;

	/* preconditions in debug*/
	assert(p_cp != 00);
	assert(p_image != 00);
	assert(tileno < p_cp->tw * p_cp->th);

	/* initializations*/
	tcp = &p_cp->tcps [tileno];
	l_tccp = tcp->tccps;
	l_img_comp = p_image->comps;

	/* position in x and y of tile*/
	p = tileno % p_cp->tw;
	q = tileno / p_cp->tw;

	/* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
	*p_tx0 = (OPJ_INT32)opj_uint_max(p_cp->tx0 + p * p_cp->tdx, p_image->x0);
	*p_tx1 = (OPJ_INT32)opj_uint_min(p_cp->tx0 + (p + 1) * p_cp->tdx, p_image->x1);
	*p_ty0 = (OPJ_INT32)opj_uint_max(p_cp->ty0 + q * p_cp->tdy, p_image->y0);
	*p_ty1 = (OPJ_INT32)opj_uint_min(p_cp->ty0 + (q + 1) * p_cp->tdy, p_image->y1);

	/* max precision and resolution is 0 (can only grow)*/
	*p_max_prec = 0;
	*p_max_res = 0;

	/* take the largest value for dx_min and dy_min*/
	*p_dx_min = 0x7fffffff;
	*p_dy_min = 0x7fffffff;

	for (compno = 0; compno < p_image->numcomps; ++compno) {
		/* aritmetic variables to calculate*/
		OPJ_UINT32 l_level_no;
		OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
		OPJ_INT32 l_px0, l_py0, l_px1, py1;
		OPJ_UINT32 l_product;
		OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
		OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph;

		lResolutionPtr = p_resolutions[compno];

		l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
		l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
		l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
		l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);

		if (l_tccp->numresolutions > *p_max_res) {
			*p_max_res = l_tccp->numresolutions;
		}

		/* use custom size for precincts*/
		l_level_no = l_tccp->numresolutions - 1;
		for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
			OPJ_UINT32 l_dx, l_dy;

			/* precinct width and height*/
			l_pdx = l_tccp->prcw[resno];
			l_pdy = l_tccp->prch[resno];
			*lResolutionPtr++ = l_pdx;
			*lResolutionPtr++ = l_pdy;
			l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
			l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
			/* take the minimum size for l_dx for each comp and resolution*/
			*p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx);
			*p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy);

			/* various calculations of extents*/
			l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
			l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
			l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
			l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
			l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
			l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
			l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
			py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
			l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
			l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy);
			*lResolutionPtr++ = l_pw;
			*lResolutionPtr++ = l_ph;
			l_product = l_pw * l_ph;

            /* update precision*/
			if (l_product > *p_max_prec) {
				*p_max_prec = l_product;
			}

			--l_level_no;
		}
		++l_tccp;
		++l_img_comp;
	}
}


VirtIOS390Device * s390_virtio_bus_console ( VirtIOS390Bus * bus ) {
 return bus -> console ;
 }


const char * event_get_method ( void ) {
 return ( current_base -> evsel -> name ) ;
 }


static int md_http_challenge_pr(request_rec *r)
{
    apr_bucket_brigade *bb;
    const md_srv_conf_t *sc;
    const char *name, *data;
    md_reg_t *reg;
    int configured;
    apr_status_t rv;

    if (!strncmp(ACME_CHALLENGE_PREFIX, r->parsed_uri.path, sizeof(ACME_CHALLENGE_PREFIX)-1)) {
        sc = ap_get_module_config(r->server->module_config, &md_module);
        if (sc && sc->mc) {
            configured = (NULL != md_get_by_domain(sc->mc->mds, r->hostname));
            if (r->method_number == M_GET) {
                name = r->parsed_uri.path + sizeof(ACME_CHALLENGE_PREFIX)-1;
                reg = sc && sc->mc? sc->mc->reg : NULL;

                r->status = HTTP_NOT_FOUND;
                if (!ap_strchr_c(name, '/') && reg) {
                    md_store_t *store = md_reg_store_get(reg);
                    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                                  "Challenge for %s (%s)", r->hostname, r->uri);

                    rv = md_store_load(store, MD_SG_CHALLENGES, r->hostname,
                                       MD_FN_HTTP01, MD_SV_TEXT, (void**)&data, r->pool);
                    if (APR_SUCCESS == rv) {
                        apr_size_t len = strlen(data);

                        r->status = HTTP_OK;
                        apr_table_setn(r->headers_out, "Content-Length", apr_ltoa(r->pool, (long)len));

                        bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
                        apr_brigade_write(bb, NULL, NULL, data, len);
                        ap_pass_brigade(r->output_filters, bb);
                        apr_brigade_cleanup(bb);
                    }
                    else if (!configured) {
                        /* The request hostname is not for a configured domain. We are not
                         * the sole authority here for /.well-known/acme-challenge (see PR62189).
                         * So, we decline to handle this and let others step in.
                         */
                        return DECLINED;
                    }
                    else if (APR_STATUS_IS_ENOENT(rv)) {
                        return HTTP_NOT_FOUND;
                    }
                    else if (APR_ENOENT != rv) {
                        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(10081)
                                      "loading challenge %s from store", name);
                        return HTTP_INTERNAL_SERVER_ERROR;
                    }
                }
                return r->status;
            }
            else if (configured) {
                /* See comment above, we prevent any other access only for domains
                 * the have been configured for mod_md. */
                return HTTP_NOT_IMPLEMENTED;
            }
        }

    }
    return DECLINED;
}


int main(int argc, char **argv)
{
  test_cmp_parameters inParam;
  FILE *fbase=NULL, *ftest=NULL;
  int same = 0;
  char lbase[256];
  char strbase[256];
  char ltest[256];
  char strtest[256];

  if( parse_cmdline_cmp(argc, argv, &inParam) == 1 )
    {
    compare_dump_files_help_display();
    goto cleanup;
    }

  /* Display Parameters*/
  printf("******Parameters********* \n");
  printf(" base_filename = %s\n"
    " test_filename = %s\n",
    inParam.base_filename, inParam.test_filename);
  printf("************************* \n");

  /* open base file */
  printf("Try to open: %s for reading ... ", inParam.base_filename);
  if((fbase = fopen(inParam.base_filename, "rb"))==NULL)
    {
    goto cleanup;
    }
  printf("Ok.\n");

  /* open test file */
  printf("Try to open: %s for reading ... ", inParam.test_filename);
  if((ftest = fopen(inParam.test_filename, "rb"))==NULL)
    {
    goto cleanup;
    }
  printf("Ok.\n");

  while (fgets(lbase, sizeof(lbase), fbase) && fgets(ltest,sizeof(ltest),ftest))
    {
    int nbase = sscanf(lbase, "%255[^\r\n]", strbase);
    int ntest = sscanf(ltest, "%255[^\r\n]", strtest);
    assert( nbase != 255 && ntest != 255 );
    if( nbase != 1 || ntest != 1 )
      {
      fprintf(stderr, "could not parse line from files\n" );
      goto cleanup;
      }
    if( strcmp( strbase, strtest ) != 0 )
      {
      fprintf(stderr,"<%s> vs. <%s>\n", strbase, strtest);
      goto cleanup;
      }
    }

  same = 1;
  printf("\n***** TEST SUCCEED: Files are the same. *****\n");
cleanup:
  /*Close File*/
  if(fbase) fclose(fbase);
  if(ftest) fclose(ftest);

  /* Free memory*/
  free(inParam.base_filename);
  free(inParam.test_filename);

  return same ? EXIT_SUCCESS : EXIT_FAILURE;
}


static int decrypt_init(AVFormatContext *s, ID3v2ExtraMeta *em, uint8_t *header) { OMAContext *oc = s->priv_data; ID3v2ExtraMetaGEOB *geob = NULL; uint8_t *gdata; oc->encrypted = 1; av_log(s, AV_LOG_INFO, "File is encrypted\n"); /* find GEOB metadata */ while (em) { if (!strcmp(em->tag, "GEOB") && (geob = em->data) && (!strcmp(geob->description, "OMG_LSI") || !strcmp(geob->description, "OMG_BKLSI"))) { break; } em = em->next; } if (!em) { av_log(s, AV_LOG_ERROR, "No encryption header found\n"); return -1; } if (geob->datasize < 64) { av_log(s, AV_LOG_ERROR, "Invalid GEOB data size: %u\n", geob->datasize); return -1; } gdata = geob->data; if (AV_RB16(gdata) != 1) av_log(s, AV_LOG_WARNING, "Unknown version in encryption header\n"); oc->k_size = AV_RB16(&gdata[2]); oc->e_size = AV_RB16(&gdata[4]); oc->i_size = AV_RB16(&gdata[6]); oc->s_size = AV_RB16(&gdata[8]); if (memcmp(&gdata[OMA_ENC_HEADER_SIZE], "KEYRING ", 12)) { av_log(s, AV_LOG_ERROR, "Invalid encryption header\n"); return -1; } if (oc->k_size + oc->e_size + oc->i_size > geob->datasize) { av_log(s, AV_LOG_ERROR, "Too little GEOB data\n"); return AVERROR_INVALIDDATA; } oc->rid = AV_RB32(&gdata[OMA_ENC_HEADER_SIZE + 28]); av_log(s, AV_LOG_DEBUG, "RID: %.8x\n", oc->rid); memcpy(oc->iv, &header[0x58], 8); hex_log(s, AV_LOG_DEBUG, "IV", oc->iv, 8); hex_log(s, AV_LOG_DEBUG, "CBC-MAC", &gdata[OMA_ENC_HEADER_SIZE+oc->k_size+oc->e_size+oc->i_size], 8); if (s->keylen > 0) { kset(s, s->key, s->key, s->keylen); } if (!memcmp(oc->r_val, (const uint8_t[8]){0}, 8) || rprobe(s, gdata, oc->r_val) < 0 && nprobe(s, gdata, geob->datasize, oc->n_val) < 0) { int i; for (i = 0; i < FF_ARRAY_ELEMS(leaf_table); i += 2) { uint8_t buf[16]; AV_WL64(buf, leaf_table[i]); AV_WL64(&buf[8], leaf_table[i+1]); kset(s, buf, buf, 16); if (!rprobe(s, gdata, oc->r_val) || !nprobe(s, gdata, geob->datasize, oc->n_val)) break; } if (i >= FF_ARRAY_ELEMS(leaf_table)) { av_log(s, AV_LOG_ERROR, "Invalid key\n"); return -1; } } /* e_val */ av_des_init(&oc->av_des, oc->m_val, 64, 0); av_des_crypt(&oc->av_des, oc->e_val, &gdata[OMA_ENC_HEADER_SIZE + 40], 1, NULL, 0); hex_log(s, AV_LOG_DEBUG, "EK", oc->e_val, 8); /* init e_val */ av_des_init(&oc->av_des, oc->e_val, 64, 1); return 0; }


cupsdCreateProfile(int job_id,		/* I - Job ID or 0 for none */
                   int allow_networking)/* I - Allow networking off machine? */
{
#ifdef HAVE_SANDBOX_H
  cups_file_t		*fp;		/* File pointer */
  char			profile[1024],	/* File containing the profile */
			bin[1024],	/* Quoted ServerBin */
			cache[1024],	/* Quoted CacheDir */
			domain[1024],	/* Domain socket, if any */
			request[1024],	/* Quoted RequestRoot */
			root[1024],	/* Quoted ServerRoot */
			state[1024],	/* Quoted StateDir */
			temp[1024];	/* Quoted TempDir */
  const char		*nodebug;	/* " (with no-log)" for no debug */
  cupsd_listener_t	*lis;		/* Current listening socket */

  if (!UseSandboxing || Sandboxing == CUPSD_SANDBOXING_OFF)
  {
   /*
    * Only use sandbox profiles as root...
    */

    cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id, allow_networking);

    return (NULL);
  }

  if ((fp = cupsTempFile2(profile, sizeof(profile))) == NULL)
  {
    cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id, allow_networking);
    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create security profile: %s",
                    strerror(errno));
    return (NULL);
  }

  fchown(cupsFileNumber(fp), RunUser, Group);
  fchmod(cupsFileNumber(fp), 0640);

  cupsd_requote(bin, ServerBin, sizeof(bin));
  cupsd_requote(cache, CacheDir, sizeof(cache));
  cupsd_requote(request, RequestRoot, sizeof(request));
  cupsd_requote(root, ServerRoot, sizeof(root));
  cupsd_requote(state, StateDir, sizeof(state));
  cupsd_requote(temp, TempDir, sizeof(temp));

  nodebug = LogLevel < CUPSD_LOG_DEBUG ? " (with no-log)" : "";

  cupsFilePuts(fp, "(version 1)\n");
  if (Sandboxing == CUPSD_SANDBOXING_STRICT)
    cupsFilePuts(fp, "(deny default)\n");
  else
    cupsFilePuts(fp, "(allow default)\n");
  if (LogLevel >= CUPSD_LOG_DEBUG)
    cupsFilePuts(fp, "(debug deny)\n");
  cupsFilePuts(fp, "(import \"system.sb\")\n");
  cupsFilePuts(fp, "(import \"com.apple.corefoundation.sb\")\n");
  cupsFilePuts(fp, "(system-network)\n");
  cupsFilePuts(fp, "(allow mach-per-user-lookup)\n");
  cupsFilePuts(fp, "(allow ipc-posix-sem)\n");
  cupsFilePuts(fp, "(allow ipc-posix-shm)\n");
  cupsFilePuts(fp, "(allow ipc-sysv-shm)\n");
  cupsFilePuts(fp, "(allow mach-lookup)\n");
  if (!RunUser)
    cupsFilePrintf(fp,
		   "(deny file-write* file-read-data file-read-metadata\n"
		   "  (regex"
		   " #\"^/Users$\""
		   " #\"^/Users/\""
		   ")%s)\n", nodebug);
  cupsFilePrintf(fp,
                 "(deny file-write*\n"
                 "  (regex"
		 " #\"^%s$\""		/* ServerRoot */
		 " #\"^%s/\""		/* ServerRoot/... */
		 " #\"^/private/etc$\""
		 " #\"^/private/etc/\""
		 " #\"^/usr/local/etc$\""
		 " #\"^/usr/local/etc/\""
		 " #\"^/Library$\""
		 " #\"^/Library/\""
		 " #\"^/System$\""
		 " #\"^/System/\""
		 ")%s)\n",
		 root, root, nodebug);
  /* Specifically allow applications to stat RequestRoot and some other system folders */
  cupsFilePrintf(fp,
                 "(allow file-read-metadata\n"
                 "  (regex"
		 " #\"^/$\""		/* / */
		 " #\"^/usr$\""		/* /usr */
		 " #\"^/Library$\""	/* /Library */
		 " #\"^/Library/Printers$\""	/* /Library/Printers */
		 " #\"^%s$\""		/* RequestRoot */
		 "))\n",
		 request);
  /* Read and write TempDir, CacheDir, and other common folders */
  cupsFilePuts(fp,
	       "(allow file-write* file-read-data file-read-metadata\n"
	       "  (regex"
	       " #\"^/private/var/db/\""
	       " #\"^/private/var/folders/\""
	       " #\"^/private/var/lib/\""
	       " #\"^/private/var/log/\""
	       " #\"^/private/var/mysql/\""
	       " #\"^/private/var/run/\""
	       " #\"^/private/var/spool/\""
	       " #\"^/Library/Application Support/\""
	       " #\"^/Library/Caches/\""
	       " #\"^/Library/Logs/\""
	       " #\"^/Library/Preferences/\""
	       " #\"^/Library/WebServer/\""
	       " #\"^/Users/Shared/\""
	       "))\n");
  cupsFilePrintf(fp,
		 "(deny file-write*\n"
		 "       (regex #\"^%s$\")%s)\n",
		 request, nodebug);
  cupsFilePrintf(fp,
		 "(deny file-write* file-read-data file-read-metadata\n"
		 "       (regex #\"^%s/\")%s)\n",
		 request, nodebug);
  cupsFilePrintf(fp,
                 "(allow file-write* file-read-data file-read-metadata\n"
                 "  (regex"
		 " #\"^%s$\""		/* TempDir */
		 " #\"^%s/\""		/* TempDir/... */
		 " #\"^%s$\""		/* CacheDir */
		 " #\"^%s/\""		/* CacheDir/... */
		 " #\"^%s$\""		/* StateDir */
		 " #\"^%s/\""		/* StateDir/... */
		 "))\n",
		 temp, temp, cache, cache, state, state);
  /* Read common folders */
  cupsFilePrintf(fp,
                 "(allow file-read-data file-read-metadata\n"
                 "  (regex"
                 " #\"^/AppleInternal$\""
                 " #\"^/AppleInternal/\""
                 " #\"^/bin$\""		/* /bin */
                 " #\"^/bin/\""		/* /bin/... */
                 " #\"^/private$\""
                 " #\"^/private/etc$\""
                 " #\"^/private/etc/\""
                 " #\"^/private/tmp$\""
                 " #\"^/private/tmp/\""
                 " #\"^/private/var$\""
                 " #\"^/private/var/db$\""
                 " #\"^/private/var/folders$\""
                 " #\"^/private/var/lib$\""
                 " #\"^/private/var/log$\""
                 " #\"^/private/var/mysql$\""
                 " #\"^/private/var/run$\""
                 " #\"^/private/var/spool$\""
                 " #\"^/private/var/tmp$\""
                 " #\"^/private/var/tmp/\""
                 " #\"^/usr/bin$\""	/* /usr/bin */
                 " #\"^/usr/bin/\""	/* /usr/bin/... */
                 " #\"^/usr/libexec/cups$\""	/* /usr/libexec/cups */
                 " #\"^/usr/libexec/cups/\""	/* /usr/libexec/cups/... */
                 " #\"^/usr/libexec/fax$\""	/* /usr/libexec/fax */
                 " #\"^/usr/libexec/fax/\""	/* /usr/libexec/fax/... */
                 " #\"^/usr/sbin$\""	/* /usr/sbin */
                 " #\"^/usr/sbin/\""	/* /usr/sbin/... */
		 " #\"^/Library$\""	/* /Library */
		 " #\"^/Library/\""	/* /Library/... */
		 " #\"^/System$\""	/* /System */
		 " #\"^/System/\""	/* /System/... */
		 " #\"^%s/Library$\""	/* RequestRoot/Library */
		 " #\"^%s/Library/\""	/* RequestRoot/Library/... */
		 " #\"^%s$\""		/* ServerBin */
		 " #\"^%s/\""		/* ServerBin/... */
		 " #\"^%s$\""		/* ServerRoot */
		 " #\"^%s/\""		/* ServerRoot/... */
		 "))\n",
		 request, request, bin, bin, root, root);
  if (Sandboxing == CUPSD_SANDBOXING_RELAXED)
  {
    /* Limited write access to /Library/Printers/... */
    cupsFilePuts(fp,
		 "(allow file-write*\n"
		 "  (regex"
		 " #\"^/Library/Printers/.*/\""
		 "))\n");
    cupsFilePrintf(fp,
		   "(deny file-write*\n"
		   "  (regex"
		   " #\"^/Library/Printers/PPDs$\""
		   " #\"^/Library/Printers/PPDs/\""
		   " #\"^/Library/Printers/PPD Plugins$\""
		   " #\"^/Library/Printers/PPD Plugins/\""
		   ")%s)\n", nodebug);
  }
  /* Allow execution of child processes as long as the programs are not in a user directory */
  cupsFilePuts(fp, "(allow process*)\n");
  cupsFilePuts(fp, "(deny process-exec (regex #\"^/Users/\"))\n");
  if (RunUser && getenv("CUPS_TESTROOT"))
  {
    /* Allow source directory access in "make test" environment */
    char	testroot[1024];		/* Root directory of test files */

    cupsd_requote(testroot, getenv("CUPS_TESTROOT"), sizeof(testroot));

    cupsFilePrintf(fp,
		   "(allow file-write* file-read-data file-read-metadata\n"
		   "  (regex"
		   " #\"^%s$\""		/* CUPS_TESTROOT */
		   " #\"^%s/\""		/* CUPS_TESTROOT/... */
		   "))\n",
		   testroot, testroot);
    cupsFilePrintf(fp,
		   "(allow process-exec\n"
		   "  (regex"
		   " #\"^%s/\""		/* CUPS_TESTROOT/... */
		   "))\n",
		   testroot);
    cupsFilePrintf(fp, "(allow sysctl*)\n");
  }
  if (job_id)
  {
    /* Allow job filters to read the current job files... */
    cupsFilePrintf(fp,
                   "(allow file-read-data file-read-metadata\n"
                   "       (regex #\"^%s/([ac]%05d|d%05d-[0-9][0-9][0-9])$\"))\n",
		   request, job_id, job_id);
  }
  else
  {
    /* Allow email notifications from notifiers... */
    cupsFilePuts(fp,
		 "(allow process-exec\n"
		 "  (literal \"/usr/sbin/sendmail\")\n"
		 "  (with no-sandbox))\n");
  }
  /* Allow access to Bluetooth, USB, and notify_post. */
  cupsFilePuts(fp, "(allow iokit*)\n");
  cupsFilePuts(fp, "(allow distributed-notification-post)\n");
  /* Allow outbound networking to local services */
  cupsFilePuts(fp, "(allow network-outbound"
		   "\n       (regex #\"^/private/var/run/\" #\"^/private/tmp/\" #\"^/private/var/tmp/\")");
  for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
       lis;
       lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
  {
    if (httpAddrFamily(&(lis->address)) == AF_LOCAL)
    {
      httpAddrString(&(lis->address), domain, sizeof(domain));
      cupsFilePrintf(fp, "\n       (literal \"%s\")", domain);
    }
  }
  if (allow_networking)
  {
    /* Allow TCP and UDP networking off the machine... */
    cupsFilePuts(fp, "\n       (remote tcp))\n");
    cupsFilePuts(fp, "(allow network-bind)\n"); /* for LPD resvport */
    cupsFilePuts(fp, "(allow network*\n"
		     "       (local udp \"*:*\")\n"
		     "       (remote udp \"*:*\"))\n");

    /* Also allow access to device files... */
    cupsFilePuts(fp, "(allow file-write* file-read-data file-read-metadata file-ioctl\n"
                     "       (regex #\"^/dev/\"))\n");

    /* And allow kernel extensions to be loaded, e.g., SMB */
    cupsFilePuts(fp, "(allow system-kext-load)\n");
  }
  else
  {
    /* Only allow SNMP (UDP) and LPD (TCP) off the machine... */
    cupsFilePuts(fp, ")\n");
    cupsFilePuts(fp, "(allow network-outbound\n"
		     "       (remote udp \"*:161\")\n"
		     "       (remote tcp \"*:515\"))\n");
    cupsFilePuts(fp, "(allow network-inbound\n"
		     "       (local udp \"localhost:*\"))\n");
  }
  cupsFileClose(fp);

  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d,allow_networking=%d) = \"%s\"", job_id, allow_networking, profile);
  return ((void *)strdup(profile));

#else
  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCreateProfile(job_id=%d, allow_networking=%d) = NULL", job_id, allow_networking);

  return (NULL);
#endif /* HAVE_SANDBOX_H */
}