psutil_net_if_stats(PyObject* self, PyObject* args) {
    kstat_ctl_t *kc = NULL;
    kstat_t *ksp;
    kstat_named_t *knp;
    int ret;
    int sock = -1;
    int duplex;
    int speed;

    PyObject *py_retdict = PyDict_New();
    PyObject *py_ifc_info = NULL;
    PyObject *py_is_up = NULL;

    if (py_retdict == NULL)
        return NULL;
    kc = kstat_open();
    if (kc == NULL)
        goto error;
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) {
        if (strcmp(ksp->ks_class, "net") == 0) {
            struct lifreq ifr;

            kstat_read(kc, ksp, NULL);
            if (ksp->ks_type != KSTAT_TYPE_NAMED)
                continue;
            if (strcmp(ksp->ks_class, "net") != 0)
                continue;

            strncpy(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name));
            ret = ioctl(sock, SIOCGLIFFLAGS, &ifr);
            if (ret == -1)
                continue;  // not a network interface

            // is up?
            if ((ifr.lifr_flags & IFF_UP) != 0) {
                if ((knp = kstat_data_lookup(ksp, "link_up")) != NULL) {
                    if (knp->value.ui32 != 0u)
                        py_is_up = Py_True;
                    else
                        py_is_up = Py_False;
                }
                else {
                    py_is_up = Py_True;
                }
            }
            else {
                py_is_up = Py_False;
            }
            Py_INCREF(py_is_up);

            // duplex
            duplex = 0;  // unknown
            if ((knp = kstat_data_lookup(ksp, "link_duplex")) != NULL) {
                if (knp->value.ui32 == 1)
                    duplex = 1;  // half
                else if (knp->value.ui32 == 2)
                    duplex = 2;  // full
            }

            // speed
            if ((knp = kstat_data_lookup(ksp, "ifspeed")) != NULL)
                // expressed in bits per sec, we want mega bits per sec
                speed = (int)knp->value.ui64 / 1000000;
            else
                speed = 0;

            // mtu
            ret = ioctl(sock, SIOCGLIFMTU, &ifr);
            if (ret == -1)
                goto error;

            py_ifc_info = Py_BuildValue("(Oiii)", py_is_up, duplex, speed,
                                        ifr.lifr_mtu);
            if (!py_ifc_info)
                goto error;
            if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
                goto error;
            Py_DECREF(py_ifc_info);
        }
    }

    close(sock);
    kstat_close(kc);
    return py_retdict;

error:
    Py_XDECREF(py_is_up);
    Py_XDECREF(py_ifc_info);
    Py_DECREF(py_retdict);
    if (sock != -1)
        close(sock);
    if (kc != NULL)
        kstat_close(kc);
    PyErr_SetFromErrno(PyExc_OSError);
    return NULL;
}


static void cirrus_cursor_invalidate ( VGACommonState * s1 ) {
 CirrusVGAState * s = container_of ( s1 , CirrusVGAState , vga ) ;
 int size ;
 if ( ! ( s -> vga . sr [ 0x12 ] & CIRRUS_CURSOR_SHOW ) ) {
 size = 0 ;
 }
 else {
 if ( s -> vga . sr [ 0x12 ] & CIRRUS_CURSOR_LARGE ) size = 64 ;
 else size = 32 ;
 }
 if ( s -> last_hw_cursor_size != size || s -> last_hw_cursor_x != s -> vga . hw_cursor_x || s -> last_hw_cursor_y != s -> vga . hw_cursor_y ) {
 invalidate_cursor1 ( s ) ;
 s -> last_hw_cursor_size = size ;
 s -> last_hw_cursor_x = s -> vga . hw_cursor_x ;
 s -> last_hw_cursor_y = s -> vga . hw_cursor_y ;
 cirrus_cursor_compute_yrange ( s ) ;
 invalidate_cursor1 ( s ) ;
 }
 }


psutil_proc_connections(PyObject *self, PyObject *args) {
    long pid;
    int pidinfo_result;
    int iterations;
    int i;
    unsigned long nb;

    struct proc_fdinfo *fds_pointer = NULL;
    struct proc_fdinfo *fdp_pointer;
    struct socket_fdinfo si;

    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;
    PyObject *py_laddr = NULL;
    PyObject *py_raddr = NULL;
    PyObject *py_af_filter = NULL;
    PyObject *py_type_filter = NULL;

    if (py_retlist == NULL)
        return NULL;

    if (! PyArg_ParseTuple(args, "lOO", &pid, &py_af_filter, &py_type_filter))
        goto error;

    if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {
        PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
        goto error;
    }

    if (pid == 0)
        return py_retlist;
    pidinfo_result = psutil_proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
    if (pidinfo_result <= 0)
        goto error;

    fds_pointer = malloc(pidinfo_result);
    if (fds_pointer == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    pidinfo_result = psutil_proc_pidinfo(
        pid, PROC_PIDLISTFDS, 0, fds_pointer, pidinfo_result);
    if (pidinfo_result <= 0)
        goto error;

    iterations = (pidinfo_result / PROC_PIDLISTFD_SIZE);
    for (i = 0; i < iterations; i++) {
        py_tuple = NULL;
        py_laddr = NULL;
        py_raddr = NULL;
        fdp_pointer = &fds_pointer[i];

        if (fdp_pointer->proc_fdtype == PROX_FDTYPE_SOCKET) {
            errno = 0;
            nb = proc_pidfdinfo((pid_t)pid, fdp_pointer->proc_fd,
                                PROC_PIDFDSOCKETINFO, &si, sizeof(si));

            // --- errors checking
            if ((nb <= 0) || (nb < sizeof(si))) {
                if (errno == EBADF) {
                    // let's assume socket has been closed
                    continue;
                }
                else {
                    psutil_raise_for_pid(
                        pid, "proc_pidinfo(PROC_PIDFDSOCKETINFO)");
                    goto error;
                }
            }
            // --- /errors checking

            //
            int fd, family, type, lport, rport, state;
            char lip[200], rip[200];
            int inseq;
            PyObject *py_family;
            PyObject *py_type;

            fd = (int)fdp_pointer->proc_fd;
            family = si.psi.soi_family;
            type = si.psi.soi_type;

            // apply filters
            py_family = PyLong_FromLong((long)family);
            inseq = PySequence_Contains(py_af_filter, py_family);
            Py_DECREF(py_family);
            if (inseq == 0)
                continue;
            py_type = PyLong_FromLong((long)type);
            inseq = PySequence_Contains(py_type_filter, py_type);
            Py_DECREF(py_type);
            if (inseq == 0)
                continue;

            if (errno != 0) {
                PyErr_SetFromErrno(PyExc_OSError);
                goto error;
            }

            if ((family == AF_INET) || (family == AF_INET6)) {
                if (family == AF_INET) {
                    inet_ntop(AF_INET,
                              &si.psi.soi_proto.pri_tcp.tcpsi_ini. \
                                  insi_laddr.ina_46.i46a_addr4,
                              lip,
                              sizeof(lip));
                    inet_ntop(AF_INET,
                              &si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr. \
                                  ina_46.i46a_addr4,
                              rip,
                              sizeof(rip));
                }
                else {
                    inet_ntop(AF_INET6,
                              &si.psi.soi_proto.pri_tcp.tcpsi_ini. \
                                  insi_laddr.ina_6,
                              lip, sizeof(lip));
                    inet_ntop(AF_INET6,
                              &si.psi.soi_proto.pri_tcp.tcpsi_ini. \
                                  insi_faddr.ina_6,
                              rip, sizeof(rip));
                }

                // check for inet_ntop failures
                if (errno != 0) {
                    PyErr_SetFromOSErrnoWithSyscall("inet_ntop()");
                    goto error;
                }

                lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
                rport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport);
                if (type == SOCK_STREAM)
                    state = (int)si.psi.soi_proto.pri_tcp.tcpsi_state;
                else
                    state = PSUTIL_CONN_NONE;

                py_laddr = Py_BuildValue("(si)", lip, lport);
                if (!py_laddr)
                    goto error;
                if (rport != 0)
                    py_raddr = Py_BuildValue("(si)", rip, rport);
                else
                    py_raddr = Py_BuildValue("()");
                if (!py_raddr)
                    goto error;

                // construct the python list
                py_tuple = Py_BuildValue(
                    "(iiiNNi)", fd, family, type, py_laddr, py_raddr, state);
                if (!py_tuple)
                    goto error;
                if (PyList_Append(py_retlist, py_tuple))
                    goto error;
                Py_DECREF(py_tuple);
            }
            else if (family == AF_UNIX) {
                py_laddr = PyUnicode_DecodeFSDefault(
                    si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path);
                if (!py_laddr)
                    goto error;
                py_raddr = PyUnicode_DecodeFSDefault(
                    si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path);
                if (!py_raddr)
                    goto error;
                // construct the python list
                py_tuple = Py_BuildValue(
                    "(iiiOOi)",
                    fd, family, type,
                    py_laddr,
                    py_raddr,
                    PSUTIL_CONN_NONE);
                if (!py_tuple)
                    goto error;
                if (PyList_Append(py_retlist, py_tuple))
                    goto error;
                Py_DECREF(py_tuple);
                Py_DECREF(py_laddr);
                Py_DECREF(py_raddr);
            }
        }
    }

    free(fds_pointer);
    return py_retlist;

error:
    Py_XDECREF(py_tuple);
    Py_XDECREF(py_laddr);
    Py_XDECREF(py_raddr);
    Py_DECREF(py_retlist);
    if (fds_pointer != NULL)
        free(fds_pointer);
    return NULL;
}


cnt_recv_prep(struct req *req, const char *ci)
{
	const char *xff;

	if (req->restarts == 0) {
		/*
		 * This really should be done earlier, but we want to capture
		 * it in the VSL log.
		 */
		http_CollectHdr(req->http, H_X_Forwarded_For);
		if (http_GetHdr(req->http, H_X_Forwarded_For, &xff)) {
			http_Unset(req->http, H_X_Forwarded_For);
			http_PrintfHeader(req->http, "X-Forwarded-For: %s, %s",
			    xff, ci);
		} else {
			http_PrintfHeader(req->http, "X-Forwarded-For: %s", ci);
		}
		http_CollectHdr(req->http, H_Cache_Control);

		/* By default we use the first backend */
		req->director_hint = VCL_DefaultDirector(req->vcl);

		req->d_ttl = -1;
		req->d_grace = -1;
		req->disable_esi = 0;
		req->hash_always_miss = 0;
		req->hash_ignore_busy = 0;
		req->client_identity = NULL;
		req->storage = NULL;
	}

	req->vdc->retval = 0;
	req->is_hit = 0;
	req->is_hitmiss = 0;
	req->is_hitpass = 0;
}


static void lsi_execute_script(LSIState *s)
{
    PCIDevice *pci_dev = PCI_DEVICE(s);
    uint32_t insn;
    uint32_t addr, addr_high;
    int opcode;
    int insn_processed = 0;

    s->istat1 |= LSI_ISTAT1_SRUN;
again:
    insn_processed++;
    insn = read_dword(s, s->dsp);
    if (!insn) {
        /* If we receive an empty opcode increment the DSP by 4 bytes
           instead of 8 and execute the next opcode at that location */
        s->dsp += 4;
        goto again;
    }
    addr = read_dword(s, s->dsp + 4);
    addr_high = 0;
    trace_lsi_execute_script(s->dsp, insn, addr);
    s->dsps = addr;
    s->dcmd = insn >> 24;
    s->dsp += 8;
    switch (insn >> 30) {
    case 0: /* Block move.  */
        if (s->sist1 & LSI_SIST1_STO) {
            trace_lsi_execute_script_blockmove_delayed();
            lsi_stop_script(s);
            break;
        }
        s->dbc = insn & 0xffffff;
        s->rbc = s->dbc;
        /* ??? Set ESA.  */
        s->ia = s->dsp - 8;
        if (insn & (1 << 29)) {
            /* Indirect addressing.  */
            addr = read_dword(s, addr);
        } else if (insn & (1 << 28)) {
            uint32_t buf[2];
            int32_t offset;
            /* Table indirect addressing.  */

            /* 32-bit Table indirect */
            offset = sextract32(addr, 0, 24);
            pci_dma_read(pci_dev, s->dsa + offset, buf, 8);
            /* byte count is stored in bits 0:23 only */
            s->dbc = cpu_to_le32(buf[0]) & 0xffffff;
            s->rbc = s->dbc;
            addr = cpu_to_le32(buf[1]);

            /* 40-bit DMA, upper addr bits [39:32] stored in first DWORD of
             * table, bits [31:24] */
            if (lsi_dma_40bit(s))
                addr_high = cpu_to_le32(buf[0]) >> 24;
            else if (lsi_dma_ti64bit(s)) {
                int selector = (cpu_to_le32(buf[0]) >> 24) & 0x1f;
                switch (selector) {
                case 0 ... 0x0f:
                    /* offset index into scratch registers since
                     * TI64 mode can use registers C to R */
                    addr_high = s->scratch[2 + selector];
                    break;
                case 0x10:
                    addr_high = s->mmrs;
                    break;
                case 0x11:
                    addr_high = s->mmws;
                    break;
                case 0x12:
                    addr_high = s->sfs;
                    break;
                case 0x13:
                    addr_high = s->drs;
                    break;
                case 0x14:
                    addr_high = s->sbms;
                    break;
                case 0x15:
                    addr_high = s->dbms;
                    break;
                default:
                    qemu_log_mask(LOG_GUEST_ERROR,
                          "lsi_scsi: Illegal selector specified (0x%x > 0x15) "
                          "for 64-bit DMA block move", selector);
                    break;
                }
            }
        } else if (lsi_dma_64bit(s)) {
            /* fetch a 3rd dword if 64-bit direct move is enabled and
               only if we're not doing table indirect or indirect addressing */
            s->dbms = read_dword(s, s->dsp);
            s->dsp += 4;
            s->ia = s->dsp - 12;
        }
        if ((s->sstat1 & PHASE_MASK) != ((insn >> 24) & 7)) {
            trace_lsi_execute_script_blockmove_badphase(
                    scsi_phase_name(s->sstat1),
                    scsi_phase_name(insn >> 24));
            lsi_script_scsi_interrupt(s, LSI_SIST0_MA, 0);
            break;
        }
        s->dnad = addr;
        s->dnad64 = addr_high;
        switch (s->sstat1 & 0x7) {
        case PHASE_DO:
            s->waiting = LSI_DMA_SCRIPTS;
            lsi_do_dma(s, 1);
            if (s->waiting)
                s->waiting = LSI_DMA_IN_PROGRESS;
            break;
        case PHASE_DI:
            s->waiting = LSI_DMA_SCRIPTS;
            lsi_do_dma(s, 0);
            if (s->waiting)
                s->waiting = LSI_DMA_IN_PROGRESS;
            break;
        case PHASE_CMD:
            lsi_do_command(s);
            break;
        case PHASE_ST:
            lsi_do_status(s);
            break;
        case PHASE_MO:
            lsi_do_msgout(s);
            break;
        case PHASE_MI:
            lsi_do_msgin(s);
            break;
        default:
            qemu_log_mask(LOG_UNIMP, "lsi_scsi: Unimplemented phase %s\n",
                          scsi_phase_name(s->sstat1));
        }
        s->dfifo = s->dbc & 0xff;
        s->ctest5 = (s->ctest5 & 0xfc) | ((s->dbc >> 8) & 3);
        s->sbc = s->dbc;
        s->rbc -= s->dbc;
        s->ua = addr + s->dbc;
        break;

    case 1: /* IO or Read/Write instruction.  */
        opcode = (insn >> 27) & 7;
        if (opcode < 5) {
            uint32_t id;

            if (insn & (1 << 25)) {
                id = read_dword(s, s->dsa + sextract32(insn, 0, 24));
            } else {
                id = insn;
            }
            id = (id >> 16) & 0xf;
            if (insn & (1 << 26)) {
                addr = s->dsp + sextract32(addr, 0, 24);
            }
            s->dnad = addr;
            switch (opcode) {
            case 0: /* Select */
                s->sdid = id;
                if (s->scntl1 & LSI_SCNTL1_CON) {
                    trace_lsi_execute_script_io_alreadyreselected();
                    s->dsp = s->dnad;
                    break;
                }
                s->sstat0 |= LSI_SSTAT0_WOA;
                s->scntl1 &= ~LSI_SCNTL1_IARB;
                if (!scsi_device_find(&s->bus, 0, id, 0)) {
                    lsi_bad_selection(s, id);
                    break;
                }
                trace_lsi_execute_script_io_selected(id,
                                             insn & (1 << 3) ? " ATN" : "");
                /* ??? Linux drivers compain when this is set.  Maybe
                   it only applies in low-level mode (unimplemented).
                lsi_script_scsi_interrupt(s, LSI_SIST0_CMP, 0); */
                s->select_tag = id << 8;
                s->scntl1 |= LSI_SCNTL1_CON;
                if (insn & (1 << 3)) {
                    s->socl |= LSI_SOCL_ATN;
                    s->sbcl |= LSI_SBCL_ATN;
                }
                s->sbcl |= LSI_SBCL_BSY;
                lsi_set_phase(s, PHASE_MO);
                s->waiting = LSI_NOWAIT;
                break;
            case 1: /* Disconnect */
                trace_lsi_execute_script_io_disconnect();
                s->scntl1 &= ~LSI_SCNTL1_CON;
                /* FIXME: this is not entirely correct; the target need not ask
                 * for reselection until it has to send data, while here we force a
                 * reselection as soon as the bus is free.  The correct flow would
                 * reselect before lsi_transfer_data and disconnect as soon as
                 * DMA ends.
                 */
                if (!s->current) {
                    lsi_request *p = get_pending_req(s);
                    if (p) {
                        lsi_reselect(s, p);
                    }
                }
                break;
            case 2: /* Wait Reselect */
                if (s->istat0 & LSI_ISTAT0_SIGP) {
                    s->dsp = s->dnad;
                } else if (!lsi_irq_on_rsl(s)) {
                        lsi_wait_reselect(s);
                }
                break;
            case 3: /* Set */
                trace_lsi_execute_script_io_set(
                        insn & (1 << 3) ? " ATN" : "",
                        insn & (1 << 6) ? " ACK" : "",
                        insn & (1 << 9) ? " TM" : "",
                        insn & (1 << 10) ? " CC" : "");
                if (insn & (1 << 3)) {
                    s->socl |= LSI_SOCL_ATN;
                    s->sbcl |= LSI_SBCL_ATN;
                    lsi_set_phase(s, PHASE_MO);
                }

                if (insn & (1 << 6)) {
                    s->sbcl |= LSI_SBCL_ACK;
                }

                if (insn & (1 << 9)) {
                    qemu_log_mask(LOG_UNIMP,
                        "lsi_scsi: Target mode not implemented\n");
                }
                if (insn & (1 << 10))
                    s->carry = 1;
                break;
            case 4: /* Clear */
                trace_lsi_execute_script_io_clear(
                        insn & (1 << 3) ? " ATN" : "",
                        insn & (1 << 6) ? " ACK" : "",
                        insn & (1 << 9) ? " TM" : "",
                        insn & (1 << 10) ? " CC" : "");
                if (insn & (1 << 3)) {
                    s->socl &= ~LSI_SOCL_ATN;
                    s->sbcl &= ~LSI_SBCL_ATN;
                }

                if (insn & (1 << 6)) {
                    s->sbcl &= ~LSI_SBCL_ACK;
                }

                if (insn & (1 << 10))
                    s->carry = 0;
                break;
            }
        } else {
            uint8_t op0;
            uint8_t op1;
            uint8_t data8;
            int reg;
            int operator;

            static const char *opcode_names[3] =
                {"Write", "Read", "Read-Modify-Write"};
            static const char *operator_names[8] =
                {"MOV", "SHL", "OR", "XOR", "AND", "SHR", "ADD", "ADC"};

            reg = ((insn >> 16) & 0x7f) | (insn & 0x80);
            data8 = (insn >> 8) & 0xff;
            opcode = (insn >> 27) & 7;
            operator = (insn >> 24) & 7;
            trace_lsi_execute_script_io_opcode(
                    opcode_names[opcode - 5], reg,
                    operator_names[operator], data8, s->sfbr,
                    (insn & (1 << 23)) ? " SFBR" : "");
            op0 = op1 = 0;
            switch (opcode) {
            case 5: /* From SFBR */
                op0 = s->sfbr;
                op1 = data8;
                break;
            case 6: /* To SFBR */
                if (operator)
                    op0 = lsi_reg_readb(s, reg);
                op1 = data8;
                break;
            case 7: /* Read-modify-write */
                if (operator)
                    op0 = lsi_reg_readb(s, reg);
                if (insn & (1 << 23)) {
                    op1 = s->sfbr;
                } else {
                    op1 = data8;
                }
                break;
            }

            switch (operator) {
            case 0: /* move */
                op0 = op1;
                break;
            case 1: /* Shift left */
                op1 = op0 >> 7;
                op0 = (op0 << 1) | s->carry;
                s->carry = op1;
                break;
            case 2: /* OR */
                op0 |= op1;
                break;
            case 3: /* XOR */
                op0 ^= op1;
                break;
            case 4: /* AND */
                op0 &= op1;
                break;
            case 5: /* SHR */
                op1 = op0 & 1;
                op0 = (op0 >> 1) | (s->carry << 7);
                s->carry = op1;
                break;
            case 6: /* ADD */
                op0 += op1;
                s->carry = op0 < op1;
                break;
            case 7: /* ADC */
                op0 += op1 + s->carry;
                if (s->carry)
                    s->carry = op0 <= op1;
                else
                    s->carry = op0 < op1;
                break;
            }

            switch (opcode) {
            case 5: /* From SFBR */
            case 7: /* Read-modify-write */
                lsi_reg_writeb(s, reg, op0);
                break;
            case 6: /* To SFBR */
                s->sfbr = op0;
                break;
            }
        }
        break;

    case 2: /* Transfer Control.  */
        {
            int cond;
            int jmp;

            if ((insn & 0x002e0000) == 0) {
                trace_lsi_execute_script_tc_nop();
                break;
            }
            if (s->sist1 & LSI_SIST1_STO) {
                trace_lsi_execute_script_tc_delayedselect_timeout();
                lsi_stop_script(s);
                break;
            }
            cond = jmp = (insn & (1 << 19)) != 0;
            if (cond == jmp && (insn & (1 << 21))) {
                trace_lsi_execute_script_tc_compc(s->carry == jmp);
                cond = s->carry != 0;
            }
            if (cond == jmp && (insn & (1 << 17))) {
                trace_lsi_execute_script_tc_compp(scsi_phase_name(s->sstat1),
                        jmp ? '=' : '!', scsi_phase_name(insn >> 24));
                cond = (s->sstat1 & PHASE_MASK) == ((insn >> 24) & 7);
            }
            if (cond == jmp && (insn & (1 << 18))) {
                uint8_t mask;

                mask = (~insn >> 8) & 0xff;
                trace_lsi_execute_script_tc_compd(
                        s->sfbr, mask, jmp ? '=' : '!', insn & mask);
                cond = (s->sfbr & mask) == (insn & mask);
            }
            if (cond == jmp) {
                if (insn & (1 << 23)) {
                    /* Relative address.  */
                    addr = s->dsp + sextract32(addr, 0, 24);
                }
                switch ((insn >> 27) & 7) {
                case 0: /* Jump */
                    trace_lsi_execute_script_tc_jump(addr);
                    s->adder = addr;
                    s->dsp = addr;
                    break;
                case 1: /* Call */
                    trace_lsi_execute_script_tc_call(addr);
                    s->temp = s->dsp;
                    s->dsp = addr;
                    break;
                case 2: /* Return */
                    trace_lsi_execute_script_tc_return(s->temp);
                    s->dsp = s->temp;
                    break;
                case 3: /* Interrupt */
                    trace_lsi_execute_script_tc_interrupt(s->dsps);
                    if ((insn & (1 << 20)) != 0) {
                        s->istat0 |= LSI_ISTAT0_INTF;
                        lsi_update_irq(s);
                    } else {
                        lsi_script_dma_interrupt(s, LSI_DSTAT_SIR);
                    }
                    break;
                default:
                    trace_lsi_execute_script_tc_illegal();
                    lsi_script_dma_interrupt(s, LSI_DSTAT_IID);
                    break;
                }
            } else {
                trace_lsi_execute_script_tc_cc_failed();
            }
        }
        break;

    case 3:
        if ((insn & (1 << 29)) == 0) {
            /* Memory move.  */
            uint32_t dest;
            /* ??? The docs imply the destination address is loaded into
               the TEMP register.  However the Linux drivers rely on
               the value being presrved.  */
            dest = read_dword(s, s->dsp);
            s->dsp += 4;
            lsi_memcpy(s, dest, addr, insn & 0xffffff);
        } else {
            uint8_t data[7];
            int reg;
            int n;
            int i;

            if (insn & (1 << 28)) {
                addr = s->dsa + sextract32(addr, 0, 24);
            }
            n = (insn & 7);
            reg = (insn >> 16) & 0xff;
            if (insn & (1 << 24)) {
                pci_dma_read(pci_dev, addr, data, n);
                trace_lsi_execute_script_mm_load(reg, n, addr, *(int *)data);
                for (i = 0; i < n; i++) {
                    lsi_reg_writeb(s, reg + i, data[i]);
                }
            } else {
                trace_lsi_execute_script_mm_store(reg, n, addr);
                for (i = 0; i < n; i++) {
                    data[i] = lsi_reg_readb(s, reg + i);
                }
                pci_dma_write(pci_dev, addr, data, n);
            }
        }
    }
    if (insn_processed > 10000 && s->waiting == LSI_NOWAIT) {
        /* Some windows drivers make the device spin waiting for a memory
           location to change.  If we have been executed a lot of code then
           assume this is the case and force an unexpected device disconnect.
           This is apparently sufficient to beat the drivers into submission.
         */
        if (!(s->sien0 & LSI_SIST0_UDC)) {
            qemu_log_mask(LOG_GUEST_ERROR,
                          "lsi_scsi: inf. loop with UDC masked");
        }
        lsi_script_scsi_interrupt(s, LSI_SIST0_UDC, 0);
        lsi_disconnect(s);
    } else if (s->istat1 & LSI_ISTAT1_SRUN && s->waiting == LSI_NOWAIT) {
        if (s->dcntl & LSI_DCNTL_SSM) {
            lsi_script_dma_interrupt(s, LSI_DSTAT_SSI);
        } else {
            goto again;
        }
    }
    trace_lsi_execute_script_stop();
}


static void fts_build_parse_content_type ( struct fts_mail_build_context * ctx , const struct message_header_line * hdr ) {
 struct rfc822_parser_context parser ;
 string_t * content_type ;
 if ( ctx -> content_type != NULL ) return ;
 rfc822_parser_init ( & parser , hdr -> full_value , hdr -> full_value_len , NULL ) ;
 rfc822_skip_lwsp ( & parser ) ;
 T_BEGIN {
 content_type = t_str_new ( 64 ) ;
 ( void ) rfc822_parse_content_type ( & parser , content_type ) ;
 ctx -> content_type = str_lcase ( i_strdup ( str_c ( content_type ) ) ) ;
 }
 T_END ;
 rfc822_parser_deinit ( & parser ) ;
 }


uint64_t helper_subqv(CPUAlphaState *env, uint64_t op1, uint64_t op2) { uint64_t res; res = op1 - op2; if (unlikely((op1 ^ op2) & (res ^ op1) & (1ULL << 63))) { arith_excp(env, GETPC(), EXC_M_IOV, 0); } return res; }


void pdo_row_free_storage ( pdo_stmt_t * stmt TSRMLS_DC ) {
 if ( stmt ) {
 ZVAL_NULL ( & stmt -> lazy_object_ref ) ;
 if ( -- stmt -> refcount == 0 ) {
 free_statement ( stmt TSRMLS_CC ) ;
 }
 }
 }


char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type)
{
	M_list_str_t *parts;
	const char   *part;
	char         *out;
	size_t        len;
	size_t        i;
	size_t        count;

	if (path == NULL) {
		return NULL;
	}
	len = M_list_str_len(path);
	if (len == 0) {
		return NULL;
	}

	sys_type = M_fs_path_get_system_type(sys_type);

	/* Remove any empty parts (except for the first part which denotes an abs path on Unix
 	 * or a UNC path on Windows). */
	parts = M_list_str_duplicate(path);
	for (i=len-1; i>0; i--) {
		part = M_list_str_at(parts, i);
		if (part == NULL || *part == '\0') {
			M_list_str_remove_at(parts, i);
		}
	}

	len = M_list_str_len(parts);

	/* Join puts the sep between items. If there are no items then the sep
	 * won't be written. */
	part = M_list_str_at(parts, 0);
	if (len == 1 && (part == NULL || *part == '\0')) {
		M_list_str_destroy(parts);
		if (sys_type == M_FS_SYSTEM_WINDOWS) {
			return M_strdup("\\\\");
		}
		return M_strdup("/");
	}

	/* Handle windows abs path because they need two separators. */
	if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) {
		part  = M_list_str_at(parts, 0);
		/* If we have 1 item we need to add two empties so we get the second separator. */
		count = (len == 1) ? 2 : 1;
		/* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */
		if (part != NULL && *part == '\0') {
			for (i=0; i<count; i++) {
				M_list_str_insert_at(parts, "", 0);
			}
		} else if (M_fs_path_isabs(part, sys_type) && len == 1) {
			/* We need to add an empty so we get a separator after the drive. */
			M_list_str_insert_at(parts, "", 1);
		}
	}

	out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type));
	M_list_str_destroy(parts);
	return out;
}


static uint32_t gic_dist_readl ( void * opaque , hwaddr offset ) {
 uint32_t val ;
 val = gic_dist_readw ( opaque , offset ) ;
 val |= gic_dist_readw ( opaque , offset + 2 ) << 16 ;
 return val ;
 }


int imap_subscribe (char *path, int subscribe)
{
  IMAP_DATA *idata;
  char buf[LONG_STRING];
  char mbox[LONG_STRING];
  char errstr[STRING];
  int mblen;
  BUFFER err, token;
  IMAP_MBOX mx;

  if (!mx_is_imap (path) || imap_parse_path (path, &mx) || !mx.mbox)
  {
    mutt_error (_("Bad mailbox name"));
    return -1;
  }
  if (!(idata = imap_conn_find (&(mx.account), 0)))
    goto fail;

  imap_fix_path (idata, mx.mbox, buf, sizeof (buf));
  if (!*buf)
    strfcpy (buf, "INBOX", sizeof (buf));

  if (option (OPTIMAPCHECKSUBSCRIBED))
  {
    mutt_buffer_init (&token);
    mutt_buffer_init (&err);
    err.data = errstr;
    err.dsize = sizeof (errstr);
    mblen = snprintf (mbox, sizeof (mbox), "%smailboxes ",
                      subscribe ? "" : "un");
    imap_quote_string_and_backquotes (mbox + mblen, sizeof(mbox) - mblen,
                                      path);
    if (mutt_parse_rc_line (mbox, &token, &err))
      dprint (1, (debugfile, "Error adding subscribed mailbox: %s\n", errstr));
    FREE (&token.data);
  }

  if (subscribe)
    mutt_message (_("Subscribing to %s..."), buf);
  else
    mutt_message (_("Unsubscribing from %s..."), buf);
  imap_munge_mbox_name (idata, mbox, sizeof(mbox), buf);

  snprintf (buf, sizeof (buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox);

  if (imap_exec (idata, buf, 0) < 0)
    goto fail;

  imap_unmunge_mbox_name(idata, mx.mbox);
  if (subscribe)
    mutt_message (_("Subscribed to %s"), mx.mbox);
  else
    mutt_message (_("Unsubscribed from %s"), mx.mbox);
  FREE (&mx.mbox);
  return 0;

 fail:
  FREE (&mx.mbox);
  return -1;
}


static inline int dentry_has_perm ( const struct cred * cred , struct dentry * dentry , u32 av ) {
 struct inode * inode = d_backing_inode ( dentry ) ;
 struct common_audit_data ad ;
 ad . type = LSM_AUDIT_DATA_DENTRY ;
 ad . u . dentry = dentry ;
 __inode_security_revalidate ( inode , dentry , true ) ;
 return inode_has_perm ( cred , inode , av , & ad ) ;
 }


void imap_quote_string_and_backquotes (char *dest, size_t dlen, const char *src)
{
  _imap_quote_string (dest, dlen, src, "\"\\`");
}


static int vc1_decode_frame ( AVCodecContext * avctx , void * data , int * got_frame , AVPacket * avpkt ) {
 const uint8_t * buf = avpkt -> data ;
 int buf_size = avpkt -> size , n_slices = 0 , i , ret ;
 VC1Context * v = avctx -> priv_data ;
 MpegEncContext * s = & v -> s ;
 AVFrame * pict = data ;
 uint8_t * buf2 = NULL ;
 const uint8_t * buf_start = buf ;
 int mb_height , n_slices1 ;
 struct {
 uint8_t * buf ;
 GetBitContext gb ;
 int mby_start ;
 }
 * slices = NULL , * tmp ;
 if ( buf_size == 0 || ( buf_size == 4 && AV_RB32 ( buf ) == VC1_CODE_ENDOFSEQ ) ) {
 if ( s -> low_delay == 0 && s -> next_picture_ptr ) {
 if ( ( ret = av_frame_ref ( pict , & s -> next_picture_ptr -> f ) ) < 0 ) return ret ;
 s -> next_picture_ptr = NULL ;
 * got_frame = 1 ;
 }
 return 0 ;
 }
 if ( s -> avctx -> codec -> capabilities & CODEC_CAP_HWACCEL_VDPAU ) {
 if ( v -> profile < PROFILE_ADVANCED ) avctx -> pix_fmt = AV_PIX_FMT_VDPAU_WMV3 ;
 else avctx -> pix_fmt = AV_PIX_FMT_VDPAU_VC1 ;
 }
 if ( avctx -> codec_id == AV_CODEC_ID_VC1 || avctx -> codec_id == AV_CODEC_ID_VC1IMAGE ) {
 int buf_size2 = 0 ;
 buf2 = av_mallocz ( buf_size + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( IS_MARKER ( AV_RB32 ( buf ) ) ) {
 const uint8_t * start , * end , * next ;
 int size ;
 next = buf ;
 for ( start = buf , end = buf + buf_size ;
 next < end ;
 start = next ) {
 next = find_next_marker ( start + 4 , end ) ;
 size = next - start - 4 ;
 if ( size <= 0 ) continue ;
 switch ( AV_RB32 ( start ) ) {
 case VC1_CODE_FRAME : if ( avctx -> hwaccel || s -> avctx -> codec -> capabilities & CODEC_CAP_HWACCEL_VDPAU ) buf_start = start ;
 buf_size2 = vc1_unescape_buffer ( start + 4 , size , buf2 ) ;
 break ;
 case VC1_CODE_FIELD : {
 int buf_size3 ;
 tmp = av_realloc ( slices , sizeof ( * slices ) * ( n_slices + 1 ) ) ;
 if ( ! tmp ) goto err ;
 slices = tmp ;
 slices [ n_slices ] . buf = av_mallocz ( buf_size + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( ! slices [ n_slices ] . buf ) goto err ;
 buf_size3 = vc1_unescape_buffer ( start + 4 , size , slices [ n_slices ] . buf ) ;
 init_get_bits ( & slices [ n_slices ] . gb , slices [ n_slices ] . buf , buf_size3 << 3 ) ;
 slices [ n_slices ] . mby_start = s -> mb_height >> 1 ;
 n_slices1 = n_slices - 1 ;
 n_slices ++ ;
 break ;
 }
 case VC1_CODE_ENTRYPOINT : buf_size2 = vc1_unescape_buffer ( start + 4 , size , buf2 ) ;
 init_get_bits ( & s -> gb , buf2 , buf_size2 * 8 ) ;
 ff_vc1_decode_entry_point ( avctx , v , & s -> gb ) ;
 break ;
 case VC1_CODE_SLICE : {
 int buf_size3 ;
 tmp = av_realloc ( slices , sizeof ( * slices ) * ( n_slices + 1 ) ) ;
 if ( ! tmp ) goto err ;
 slices = tmp ;
 slices [ n_slices ] . buf = av_mallocz ( buf_size + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( ! slices [ n_slices ] . buf ) goto err ;
 buf_size3 = vc1_unescape_buffer ( start + 4 , size , slices [ n_slices ] . buf ) ;
 init_get_bits ( & slices [ n_slices ] . gb , slices [ n_slices ] . buf , buf_size3 << 3 ) ;
 slices [ n_slices ] . mby_start = get_bits ( & slices [ n_slices ] . gb , 9 ) ;
 n_slices ++ ;
 break ;
 }
 }
 }
 }
 else if ( v -> interlace && ( ( buf [ 0 ] & 0xC0 ) == 0xC0 ) ) {
 const uint8_t * divider ;
 int buf_size3 ;
 divider = find_next_marker ( buf , buf + buf_size ) ;
 if ( ( divider == ( buf + buf_size ) ) || AV_RB32 ( divider ) != VC1_CODE_FIELD ) {
 av_log ( avctx , AV_LOG_ERROR , "Error in WVC1 interlaced frame\n" ) ;
 goto err ;
 }
 else {
 tmp = av_realloc ( slices , sizeof ( * slices ) * ( n_slices + 1 ) ) ;
 if ( ! tmp ) goto err ;
 slices = tmp ;
 slices [ n_slices ] . buf = av_mallocz ( buf_size + FF_INPUT_BUFFER_PADDING_SIZE ) ;
 if ( ! slices [ n_slices ] . buf ) goto err ;
 buf_size3 = vc1_unescape_buffer ( divider + 4 , buf + buf_size - divider - 4 , slices [ n_slices ] . buf ) ;
 init_get_bits ( & slices [ n_slices ] . gb , slices [ n_slices ] . buf , buf_size3 << 3 ) ;
 slices [ n_slices ] . mby_start = s -> mb_height >> 1 ;
 n_slices1 = n_slices - 1 ;
 n_slices ++ ;
 }
 buf_size2 = vc1_unescape_buffer ( buf , divider - buf , buf2 ) ;
 }
 else {
 buf_size2 = vc1_unescape_buffer ( buf , buf_size , buf2 ) ;
 }
 init_get_bits ( & s -> gb , buf2 , buf_size2 * 8 ) ;
 }
 else init_get_bits ( & s -> gb , buf , buf_size * 8 ) ;
 if ( v -> res_sprite ) {
 v -> new_sprite = ! get_bits1 ( & s -> gb ) ;
 v -> two_sprites = get_bits1 ( & s -> gb ) ;
 if ( avctx -> codec_id == AV_CODEC_ID_WMV3IMAGE || avctx -> codec_id == AV_CODEC_ID_VC1IMAGE ) {
 if ( v -> new_sprite ) {
 avctx -> width = avctx -> coded_width = v -> sprite_width ;
 avctx -> height = avctx -> coded_height = v -> sprite_height ;
 }
 else {
 goto image ;
 }
 }
 }
 if ( s -> context_initialized && ( s -> width != avctx -> coded_width || s -> height != avctx -> coded_height ) ) {
 ff_vc1_decode_end ( avctx ) ;
 }
 if ( ! s -> context_initialized ) {
 if ( ff_msmpeg4_decode_init ( avctx ) < 0 || ff_vc1_decode_init_alloc_tables ( v ) < 0 ) goto err ;
 s -> low_delay = ! avctx -> has_b_frames || v -> res_sprite ;
 if ( v -> profile == PROFILE_ADVANCED ) {
 s -> h_edge_pos = avctx -> coded_width ;
 s -> v_edge_pos = avctx -> coded_height ;
 }
 }
 if ( s -> current_picture_ptr == NULL || s -> current_picture_ptr -> f . data [ 0 ] ) {
 int i = ff_find_unused_picture ( s , 0 ) ;
 if ( i < 0 ) goto err ;
 s -> current_picture_ptr = & s -> picture [ i ] ;
 }
 v -> pic_header_flag = 0 ;
 if ( v -> profile < PROFILE_ADVANCED ) {
 if ( ff_vc1_parse_frame_header ( v , & s -> gb ) == - 1 ) {
 goto err ;
 }
 }
 else {
 if ( ff_vc1_parse_frame_header_adv ( v , & s -> gb ) == - 1 ) {
 goto err ;
 }
 }
 if ( ( avctx -> codec_id == AV_CODEC_ID_WMV3IMAGE || avctx -> codec_id == AV_CODEC_ID_VC1IMAGE ) && s -> pict_type != AV_PICTURE_TYPE_I ) {
 av_log ( v -> s . avctx , AV_LOG_ERROR , "Sprite decoder: expected I-frame\n" ) ;
 goto err ;
 }
 s -> current_picture_ptr -> f . repeat_pict = 0 ;
 if ( v -> rff ) {
 s -> current_picture_ptr -> f . repeat_pict = 1 ;
 }
 else if ( v -> rptfrm ) {
 s -> current_picture_ptr -> f . repeat_pict = v -> rptfrm * 2 ;
 }
 s -> current_picture . f . pict_type = s -> pict_type ;
 s -> current_picture . f . key_frame = s -> pict_type == AV_PICTURE_TYPE_I ;
 if ( s -> last_picture_ptr == NULL && ( s -> pict_type == AV_PICTURE_TYPE_B || s -> droppable ) ) {
 goto err ;
 }
 if ( ( avctx -> skip_frame >= AVDISCARD_NONREF && s -> pict_type == AV_PICTURE_TYPE_B ) || ( avctx -> skip_frame >= AVDISCARD_NONKEY && s -> pict_type != AV_PICTURE_TYPE_I ) || avctx -> skip_frame >= AVDISCARD_ALL ) {
 goto end ;
 }
 if ( s -> next_p_frame_damaged ) {
 if ( s -> pict_type == AV_PICTURE_TYPE_B ) goto end ;
 else s -> next_p_frame_damaged = 0 ;
 }
 if ( ff_MPV_frame_start ( s , avctx ) < 0 ) {
 goto err ;
 }
 s -> me . qpel_put = s -> dsp . put_qpel_pixels_tab ;
 s -> me . qpel_avg = s -> dsp . avg_qpel_pixels_tab ;
 if ( ( CONFIG_VC1_VDPAU_DECODER ) && s -> avctx -> codec -> capabilities & CODEC_CAP_HWACCEL_VDPAU ) ff_vdpau_vc1_decode_picture ( s , buf_start , ( buf + buf_size ) - buf_start ) ;
 else if ( avctx -> hwaccel ) {
 if ( avctx -> hwaccel -> start_frame ( avctx , buf , buf_size ) < 0 ) goto err ;
 if ( avctx -> hwaccel -> decode_slice ( avctx , buf_start , ( buf + buf_size ) - buf_start ) < 0 ) goto err ;
 if ( avctx -> hwaccel -> end_frame ( avctx ) < 0 ) goto err ;
 }
 else {
 ff_mpeg_er_frame_start ( s ) ;
 v -> bits = buf_size * 8 ;
 v -> end_mb_x = s -> mb_width ;
 if ( v -> field_mode ) {
 uint8_t * tmp [ 2 ] ;
 s -> current_picture . f . linesize [ 0 ] <<= 1 ;
 s -> current_picture . f . linesize [ 1 ] <<= 1 ;
 s -> current_picture . f . linesize [ 2 ] <<= 1 ;
 s -> linesize <<= 1 ;
 s -> uvlinesize <<= 1 ;
 tmp [ 0 ] = v -> mv_f_last [ 0 ] ;
 tmp [ 1 ] = v -> mv_f_last [ 1 ] ;
 v -> mv_f_last [ 0 ] = v -> mv_f_next [ 0 ] ;
 v -> mv_f_last [ 1 ] = v -> mv_f_next [ 1 ] ;
 v -> mv_f_next [ 0 ] = v -> mv_f [ 0 ] ;
 v -> mv_f_next [ 1 ] = v -> mv_f [ 1 ] ;
 v -> mv_f [ 0 ] = tmp [ 0 ] ;
 v -> mv_f [ 1 ] = tmp [ 1 ] ;
 }
 mb_height = s -> mb_height >> v -> field_mode ;
 for ( i = 0 ;
 i <= n_slices ;
 i ++ ) {
 if ( i > 0 && slices [ i - 1 ] . mby_start >= mb_height ) {
 if ( v -> field_mode <= 0 ) {
 av_log ( v -> s . avctx , AV_LOG_ERROR , "Slice %d starts beyond " "picture boundary (%d >= %d)\n" , i , slices [ i - 1 ] . mby_start , mb_height ) ;
 continue ;
 }
 v -> second_field = 1 ;
 v -> blocks_off = s -> mb_width * s -> mb_height << 1 ;
 v -> mb_off = s -> mb_stride * s -> mb_height >> 1 ;
 }
 else {
 v -> second_field = 0 ;
 v -> blocks_off = 0 ;
 v -> mb_off = 0 ;
 }
 if ( i ) {
 v -> pic_header_flag = 0 ;
 if ( v -> field_mode && i == n_slices1 + 2 ) {
 if ( ff_vc1_parse_frame_header_adv ( v , & s -> gb ) < 0 ) {
 av_log ( v -> s . avctx , AV_LOG_ERROR , "Field header damaged\n" ) ;
 continue ;
 }
 }
 else if ( get_bits1 ( & s -> gb ) ) {
 v -> pic_header_flag = 1 ;
 if ( ff_vc1_parse_frame_header_adv ( v , & s -> gb ) < 0 ) {
 av_log ( v -> s . avctx , AV_LOG_ERROR , "Slice header damaged\n" ) ;
 continue ;
 }
 }
 }
 s -> start_mb_y = ( i == 0 ) ? 0 : FFMAX ( 0 , slices [ i - 1 ] . mby_start % mb_height ) ;
 if ( ! v -> field_mode || v -> second_field ) s -> end_mb_y = ( i == n_slices ) ? mb_height : FFMIN ( mb_height , slices [ i ] . mby_start % mb_height ) ;
 else s -> end_mb_y = ( i <= n_slices1 + 1 ) ? mb_height : FFMIN ( mb_height , slices [ i ] . mby_start % mb_height ) ;
 ff_vc1_decode_blocks ( v ) ;
 if ( i != n_slices ) s -> gb = slices [ i ] . gb ;
 }
 if ( v -> field_mode ) {
 v -> second_field = 0 ;
 if ( s -> pict_type == AV_PICTURE_TYPE_B ) {
 memcpy ( v -> mv_f_base , v -> mv_f_next_base , 2 * ( s -> b8_stride * ( s -> mb_height * 2 + 1 ) + s -> mb_stride * ( s -> mb_height + 1 ) * 2 ) ) ;
 }
 s -> current_picture . f . linesize [ 0 ] >>= 1 ;
 s -> current_picture . f . linesize [ 1 ] >>= 1 ;
 s -> current_picture . f . linesize [ 2 ] >>= 1 ;
 s -> linesize >>= 1 ;
 s -> uvlinesize >>= 1 ;
 }
 av_dlog ( s -> avctx , "Consumed %i/%i bits\n" , get_bits_count ( & s -> gb ) , s -> gb . size_in_bits ) ;
 ff_er_frame_end ( & s -> er ) ;
 }
 ff_MPV_frame_end ( s ) ;
 if ( avctx -> codec_id == AV_CODEC_ID_WMV3IMAGE || avctx -> codec_id == AV_CODEC_ID_VC1IMAGE ) {
 image : avctx -> width = avctx -> coded_width = v -> output_width ;
 avctx -> height = avctx -> coded_height = v -> output_height ;
 if ( avctx -> skip_frame >= AVDISCARD_NONREF ) goto end ;
 # if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER if ( vc1_decode_sprites ( v , & s -> gb ) ) goto err ;
 # endif if ( ( ret = av_frame_ref ( pict , & v -> sprite_output_frame ) ) < 0 ) goto err ;
 * got_frame = 1 ;
 }
 else {
 if ( s -> pict_type == AV_PICTURE_TYPE_B || s -> low_delay ) {
 if ( ( ret = av_frame_ref ( pict , & s -> current_picture_ptr -> f ) ) < 0 ) goto err ;
 ff_print_debug_info ( s , s -> current_picture_ptr ) ;
 }
 else if ( s -> last_picture_ptr != NULL ) {
 if ( ( ret = av_frame_ref ( pict , & s -> last_picture_ptr -> f ) ) < 0 ) goto err ;
 ff_print_debug_info ( s , s -> last_picture_ptr ) ;
 }
 if ( s -> last_picture_ptr || s -> low_delay ) {
 * got_frame = 1 ;
 }
 }
 end : av_free ( buf2 ) ;
 for ( i = 0 ;
 i < n_slices ;
 i ++ ) av_free ( slices [ i ] . buf ) ;
 av_free ( slices ) ;
 return buf_size ;
 err : av_free ( buf2 ) ;
 for ( i = 0 ;
 i < n_slices ;
 i ++ ) av_free ( slices [ i ] . buf ) ;
 av_free ( slices ) ;
 return - 1 ;
 }


static int dissect_h245_T_h223AnnexADoubleFlag ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_choice ( tvb , offset , actx , tree , hf_index , ett_h245_T_h223AnnexADoubleFlag , T_h223AnnexADoubleFlag_choice , NULL ) ;
 return offset ;
 }


imap_auth_res_t imap_auth_cram_md5 (IMAP_DATA* idata, const char* method)
{
  char ibuf[LONG_STRING*2], obuf[LONG_STRING];
  unsigned char hmac_response[MD5_DIGEST_LEN];
  int len;
  int rc;

  if (!mutt_bit_isset (idata->capabilities, ACRAM_MD5))
    return IMAP_AUTH_UNAVAIL;

  mutt_message _("Authenticating (CRAM-MD5)...");

  /* get auth info */
  if (mutt_account_getlogin (&idata->conn->account))
    return IMAP_AUTH_FAILURE;
  if (mutt_account_getpass (&idata->conn->account))
    return IMAP_AUTH_FAILURE;

  imap_cmd_start (idata, "AUTHENTICATE CRAM-MD5");

  /* From RFC 2195:
   * The data encoded in the first ready response contains a presumptively
   * arbitrary string of random digits, a timestamp, and the fully-qualified
   * primary host name of the server. The syntax of the unencoded form must
   * correspond to that of an RFC 822 'msg-id' [RFC822] as described in [POP3].
   */
  do
    rc = imap_cmd_step (idata);
  while (rc == IMAP_CMD_CONTINUE);

  if (rc != IMAP_CMD_RESPOND)
  {
    dprint (1, (debugfile, "Invalid response from server: %s\n", ibuf));
    goto bail;
  }

  if ((len = mutt_from_base64 (obuf, idata->buf + 2)) == -1)
  {
    dprint (1, (debugfile, "Error decoding base64 response.\n"));
    goto bail;
  }

  obuf[len] = '\0';
  dprint (2, (debugfile, "CRAM challenge: %s\n", obuf));

  /* The client makes note of the data and then responds with a string
   * consisting of the user name, a space, and a 'digest'. The latter is
   * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the
   * key is a shared secret and the digested text is the timestamp (including
   * angle-brackets).
   *
   * Note: The user name shouldn't be quoted. Since the digest can't contain
   *   spaces, there is no ambiguity. Some servers get this wrong, we'll work
   *   around them when the bug report comes in. Until then, we'll remain
   *   blissfully RFC-compliant.
   */
  hmac_md5 (idata->conn->account.pass, obuf, hmac_response);
  /* dubious optimisation I saw elsewhere: make the whole string in one call */
  snprintf (obuf, sizeof (obuf),
    "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
    idata->conn->account.user,
    hmac_response[0], hmac_response[1], hmac_response[2], hmac_response[3],
    hmac_response[4], hmac_response[5], hmac_response[6], hmac_response[7],
    hmac_response[8], hmac_response[9], hmac_response[10], hmac_response[11],
    hmac_response[12], hmac_response[13], hmac_response[14], hmac_response[15]);
  dprint(2, (debugfile, "CRAM response: %s\n", obuf));

  /* XXX - ibuf must be long enough to store the base64 encoding of obuf,
   * plus the additional debris
   */

  mutt_to_base64 ((unsigned char*) ibuf, (unsigned char*) obuf, strlen (obuf),
		  sizeof (ibuf) - 2);
  safe_strcat (ibuf, sizeof (ibuf), "\r\n");
  mutt_socket_write (idata->conn, ibuf);

  do
    rc = imap_cmd_step (idata);
  while (rc == IMAP_CMD_CONTINUE);

  if (rc != IMAP_CMD_OK)
  {
    dprint (1, (debugfile, "Error receiving server response.\n"));
    goto bail;
  }

  if (imap_code (idata->buf))
    return IMAP_AUTH_SUCCESS;

 bail:
  mutt_error _("CRAM-MD5 authentication failed.");
  mutt_sleep (2);
  return IMAP_AUTH_FAILURE;
}


static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, int16_t *block, int n) { int level, dc, diff, j, run; int component; RLTable *rl; uint8_t * scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; const int qscale = s->qscale; /* DC coefficient */ if (n < 4) { quant_matrix = s->intra_matrix; component = 0; } else { quant_matrix = s->chroma_intra_matrix; component = (n & 1) + 1; } diff = decode_dc(&s->gb, component); if (diff >= 0xffff) return -1; dc = s->last_dc[component]; dc += diff; s->last_dc[component] = dc; block[0] = dc << (3 - s->intra_dc_precision); if (s->intra_vlc_format) rl = &ff_rl_mpeg2; else rl = &ff_rl_mpeg1; { OPEN_READER(re, &s->gb); /* now quantify & encode AC coefficients */ for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0); if (level == 127) { break; } else if (level != 0) { scantable += run; j = *scantable; level = (level * qscale * quant_matrix[j]) >> 4; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } else { /* escape */ run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6); UPDATE_CACHE(re, &s->gb); level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12); scantable += run; j = *scantable; if (level < 0) { level = (-level * qscale * quant_matrix[j]) >> 4; level = -level; } else { level = (level * qscale * quant_matrix[j]) >> 4; } } block[j] = level; } CLOSE_READER(re, &s->gb); } s->block_last_index[n] = scantable - s->intra_scantable.permutated; return 0; }


static int archive_read_format_ar_cleanup ( struct archive_read * a ) {
 struct ar * ar ;
 ar = ( struct ar * ) ( a -> format -> data ) ;
 if ( ar -> strtab ) free ( ar -> strtab ) ;
 free ( ar ) ;
 ( a -> format -> data ) = NULL ;
 return ( ARCHIVE_OK ) ;
 }


static void dca_downmix(float **samples, int srcfmt, int lfe_present, float coef[DCA_PRIM_CHANNELS_MAX + 1][2], const int8_t *channel_mapping) { int c, l, r, sl, sr, s; int i; float t, u, v; switch (srcfmt) { case DCA_MONO: case DCA_CHANNEL: case DCA_STEREO_TOTAL: case DCA_STEREO_SUMDIFF: case DCA_4F2R: av_log(NULL, 0, "Not implemented!\n"); break; case DCA_STEREO: break; case DCA_3F: c = channel_mapping[0]; l = channel_mapping[1]; r = channel_mapping[2]; DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), ); break; case DCA_2F1R: s = channel_mapping[2]; DOWNMIX_TO_STEREO(MIX_REAR1(samples, s, 2, coef), ); break; case DCA_3F1R: c = channel_mapping[0]; l = channel_mapping[1]; r = channel_mapping[2]; s = channel_mapping[3]; DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), MIX_REAR1(samples, s, 3, coef)); break; case DCA_2F2R: sl = channel_mapping[2]; sr = channel_mapping[3]; DOWNMIX_TO_STEREO(MIX_REAR2(samples, sl, sr, 2, coef), ); break; case DCA_3F2R: c = channel_mapping[0]; l = channel_mapping[1]; r = channel_mapping[2]; sl = channel_mapping[3]; sr = channel_mapping[4]; DOWNMIX_TO_STEREO(MIX_FRONT3(samples, coef), MIX_REAR2(samples, sl, sr, 3, coef)); break; } if (lfe_present) { int lf_buf = dca_lfe_index[srcfmt]; int lf_idx = dca_channels [srcfmt]; for (i = 0; i < 256; i++) { samples[0][i] += samples[lf_buf][i] * coef[lf_idx][0]; samples[1][i] += samples[lf_buf][i] * coef[lf_idx][1]; } } }


static void sysctl_write(void *opaque, target_phys_addr_t addr, uint64_t value, unsigned size) { MilkymistSysctlState *s = opaque; trace_milkymist_sysctl_memory_write(addr, value); addr >>= 2; switch (addr) { case R_GPIO_OUT: case R_GPIO_INTEN: case R_TIMER0_COUNTER: case R_TIMER1_COUNTER: case R_DBG_SCRATCHPAD: s->regs[addr] = value; break; case R_TIMER0_COMPARE: ptimer_set_limit(s->ptimer0, value, 0); s->regs[addr] = value; break; case R_TIMER1_COMPARE: ptimer_set_limit(s->ptimer1, value, 0); s->regs[addr] = value; break; case R_TIMER0_CONTROL: s->regs[addr] = value; if (s->regs[R_TIMER0_CONTROL] & CTRL_ENABLE) { trace_milkymist_sysctl_start_timer0(); ptimer_set_count(s->ptimer0, s->regs[R_TIMER0_COMPARE] - s->regs[R_TIMER0_COUNTER]); ptimer_run(s->ptimer0, 0); } else { trace_milkymist_sysctl_stop_timer0(); ptimer_stop(s->ptimer0); } break; case R_TIMER1_CONTROL: s->regs[addr] = value; if (s->regs[R_TIMER1_CONTROL] & CTRL_ENABLE) { trace_milkymist_sysctl_start_timer1(); ptimer_set_count(s->ptimer1, s->regs[R_TIMER1_COMPARE] - s->regs[R_TIMER1_COUNTER]); ptimer_run(s->ptimer1, 0); } else { trace_milkymist_sysctl_stop_timer1(); ptimer_stop(s->ptimer1); } break; case R_ICAP: sysctl_icap_write(s, value); break; case R_DBG_WRITE_LOCK: s->regs[addr] = 1; break; case R_SYSTEM_ID: qemu_system_reset_request(); break; case R_GPIO_IN: case R_CLK_FREQUENCY: case R_CAPABILITIES: error_report("milkymist_sysctl: write to read-only register 0x" TARGET_FMT_plx, addr << 2); break; default: error_report("milkymist_sysctl: write access to unknown register 0x" TARGET_FMT_plx, addr << 2); break; } }


enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method)
{
  char q_user[SHORT_STRING], q_pass[SHORT_STRING];
  char buf[STRING];
  int rc;

  if (mutt_bit_isset(idata->capabilities, LOGINDISABLED))
  {
    mutt_message(_("LOGIN disabled on this server."));
    return IMAP_AUTH_UNAVAIL;
  }

  if (mutt_account_getuser(&idata->conn->account) < 0)
    return IMAP_AUTH_FAILURE;
  if (mutt_account_getpass(&idata->conn->account) < 0)
    return IMAP_AUTH_FAILURE;

  mutt_message(_("Logging in..."));

  imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user, false);
  imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass, false);

  /* don't print the password unless we're at the ungodly debugging level
   * of 5 or higher */

  if (DebugLevel < IMAP_LOG_PASS)
    mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user);

  snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass);
  rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS);

  if (!rc)
  {
    mutt_clear_error(); /* clear "Logging in...".  fixes #3524 */
    return IMAP_AUTH_SUCCESS;
  }

  mutt_error(_("Login failed."));
  return IMAP_AUTH_FAILURE;
}


static int img_resize(int argc, char **argv) { Error *err = NULL; int c, ret, relative; const char *filename, *fmt, *size; int64_t n, total_size; bool quiet = false; BlockBackend *blk = NULL; QemuOpts *param; static QemuOptsList resize_options = { .name = "resize_options", .head = QTAILQ_HEAD_INITIALIZER(resize_options.head), .desc = { { .name = BLOCK_OPT_SIZE, .type = QEMU_OPT_SIZE, .help = "Virtual disk size" }, { /* end of list */ } }, }; bool image_opts = false; /* Remove size from argv manually so that negative numbers are not treated * as options by getopt. */ if (argc < 3) { error_exit("Not enough arguments"); return 1; } size = argv[--argc]; /* Parse getopt arguments */ fmt = NULL; for(;;) { static const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"object", required_argument, 0, OPTION_OBJECT}, {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "f:hq", long_options, NULL); if (c == -1) { break; } switch(c) { case '?': case 'h': help(); break; case 'f': fmt = optarg; break; case 'q': quiet = true; break; case OPTION_OBJECT: { QemuOpts *opts; opts = qemu_opts_parse_noisily(&qemu_object_opts, optarg, true); if (!opts) { return 1; } } break; case OPTION_IMAGE_OPTS: image_opts = true; break; } } if (optind != argc - 1) { error_exit("Expecting one image file name"); } filename = argv[optind++]; if (qemu_opts_foreach(&qemu_object_opts, user_creatable_add_opts_foreach, NULL, NULL)) { return 1; } /* Choose grow, shrink, or absolute resize mode */ switch (size[0]) { case '+': relative = 1; size++; break; case '-': relative = -1; size++; break; default: relative = 0; break; } /* Parse size */ param = qemu_opts_create(&resize_options, NULL, 0, &error_abort); qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err); if (err) { error_report_err(err); ret = -1; qemu_opts_del(param); goto out; } n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0); qemu_opts_del(param); blk = img_open(image_opts, filename, fmt, BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet); if (!blk) { ret = -1; goto out; } if (relative) { total_size = blk_getlength(blk) + n * relative; } else { total_size = n; } if (total_size <= 0) { error_report("New image size must be positive"); ret = -1; goto out; } ret = blk_truncate(blk, total_size); switch (ret) { case 0: qprintf(quiet, "Image resized.\n"); break; case -ENOTSUP: error_report("This image does not support resize"); break; case -EACCES: error_report("Image is read-only"); break; default: error_report("Error resizing image: %s", strerror(-ret)); break; } out: blk_unref(blk); if (ret) { return 1; } return 0; }


void cache_fini(PageCache *cache) { int64_t i; g_assert(cache); g_assert(cache->page_cache); for (i = 0; i < cache->max_num_items; i++) { g_free(cache->page_cache[i].it_data); } g_free(cache->page_cache); cache->page_cache = NULL; }


const char * proto_get_protocol_filter_name ( const int proto_id ) {
 protocol_t * protocol ;
 protocol = find_protocol_by_id ( proto_id ) ;
 if ( protocol == NULL ) return "(none)" ;
 return protocol -> filter_name ;
 }


static int check_directory_consistency(BDRVVVFATState *s, int cluster_num, const char* path) { int ret = 0; unsigned char* cluster = qemu_malloc(s->cluster_size); direntry_t* direntries = (direntry_t*)cluster; mapping_t* mapping = find_mapping_for_cluster(s, cluster_num); long_file_name lfn; int path_len = strlen(path); char path2[PATH_MAX]; assert(path_len < PATH_MAX); /* len was tested before! */ pstrcpy(path2, sizeof(path2), path); path2[path_len] = '/'; path2[path_len + 1] = '\0'; if (mapping) { const char* basename = get_basename(mapping->path); const char* basename2 = get_basename(path); assert(mapping->mode & MODE_DIRECTORY); assert(mapping->mode & MODE_DELETED); mapping->mode &= ~MODE_DELETED; if (strcmp(basename, basename2)) schedule_rename(s, cluster_num, strdup(path)); } else /* new directory */ schedule_mkdir(s, cluster_num, strdup(path)); lfn_init(&lfn); do { int i; int subret = 0; ret++; if (s->used_clusters[cluster_num] & USED_ANY) { fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num); return 0; } s->used_clusters[cluster_num] = USED_DIRECTORY; DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num))); subret = vvfat_read(s->bs, cluster2sector(s, cluster_num), cluster, s->sectors_per_cluster); if (subret) { fprintf(stderr, "Error fetching direntries\n"); fail: free(cluster); return 0; } for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) { int cluster_count = 0; DLOG(fprintf(stderr, "check direntry %d: \n", i); print_direntry(direntries + i)); if (is_volume_label(direntries + i) || is_dot(direntries + i) || is_free(direntries + i)) continue; subret = parse_long_name(&lfn, direntries + i); if (subret < 0) { fprintf(stderr, "Error in long name\n"); goto fail; } if (subret == 0 || is_free(direntries + i)) continue; if (fat_chksum(direntries+i) != lfn.checksum) { subret = parse_short_name(s, &lfn, direntries + i); if (subret < 0) { fprintf(stderr, "Error in short name (%d)\n", subret); goto fail; } if (subret > 0 || !strcmp((char*)lfn.name, ".") || !strcmp((char*)lfn.name, "..")) continue; } lfn.checksum = 0x100; /* cannot use long name twice */ if (path_len + 1 + lfn.len >= PATH_MAX) { fprintf(stderr, "Name too long: %s/%s\n", path, lfn.name); goto fail; } pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1, (char*)lfn.name); if (is_directory(direntries + i)) { if (begin_of_direntry(direntries + i) == 0) { DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i)); goto fail; } cluster_count = check_directory_consistency(s, begin_of_direntry(direntries + i), path2); if (cluster_count == 0) { DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i)); goto fail; } } else if (is_file(direntries + i)) { /* check file size with FAT */ cluster_count = get_cluster_count_for_direntry(s, direntries + i, path2); if (cluster_count != (le32_to_cpu(direntries[i].size) + s->cluster_size - 1) / s->cluster_size) { DLOG(fprintf(stderr, "Cluster count mismatch\n")); goto fail; } } else assert(0); /* cluster_count = 0; */ ret += cluster_count; } cluster_num = modified_fat_get(s, cluster_num); } while(!fat_eof(s, cluster_num)); free(cluster); return ret; }


lyp_parse_value(struct lys_type *type, const char **value_, struct lyxml_elem *xml,
                struct lyd_node_leaf_list *leaf, struct lyd_attr *attr, struct lys_module *local_mod,
                int store, int dflt, int trusted)
{
    struct lys_type *ret = NULL, *t;
    struct lys_tpdf *tpdf;
    enum int_log_opts prev_ilo;
    int c, len, found = 0;
    unsigned int i, j;
    int64_t num;
    uint64_t unum, uind, u = 0;
    const char *ptr, *value = *value_, *itemname, *old_val_str = NULL;
    struct lys_type_bit **bits = NULL;
    struct lys_ident *ident;
    lyd_val *val, old_val;
    LY_DATA_TYPE *val_type, old_val_type;
    uint8_t *val_flags, old_val_flags;
    struct lyd_node *contextnode;
    struct ly_ctx *ctx = type->parent->module->ctx;

    assert(leaf || attr);

    if (leaf) {
        assert(!attr);
        if (!local_mod) {
            local_mod = leaf->schema->module;
        }
        val = &leaf->value;
        val_type = &leaf->value_type;
        val_flags = &leaf->value_flags;
        contextnode = (struct lyd_node *)leaf;
        itemname = leaf->schema->name;
    } else {
        assert(!leaf);
        if (!local_mod) {
            local_mod = attr->annotation->module;
        }
        val = &attr->value;
        val_type = &attr->value_type;
        val_flags = &attr->value_flags;
        contextnode = attr->parent;
        itemname = attr->name;
    }

    /* fully clear the value */
    if (store) {
        old_val_str = lydict_insert(ctx, *value_, 0);
        lyd_free_value(*val, *val_type, *val_flags, type, old_val_str, &old_val, &old_val_type, &old_val_flags);
        *val_flags &= ~LY_VALUE_UNRES;
    }

    switch (type->base) {
    case LY_TYPE_BINARY:
        /* get number of octets for length validation */
        unum = 0;
        ptr = NULL;
        if (value) {
            /* silently skip leading/trailing whitespaces */
            for (uind = 0; isspace(value[uind]); ++uind);
            ptr = &value[uind];
            u = strlen(ptr);
            while (u && isspace(ptr[u - 1])) {
                --u;
            }
            unum = u;
            for (uind = 0; uind < u; ++uind) {
                if (ptr[uind] == '\n') {
                    unum--;
                } else if ((ptr[uind] < '/' && ptr[uind] != '+') ||
                    (ptr[uind] > '9' && ptr[uind] < 'A') ||
                    (ptr[uind] > 'Z' && ptr[uind] < 'a') || ptr[uind] > 'z') {
                    if (ptr[uind] == '=') {
                        /* padding */
                        if (uind == u - 2 && ptr[uind + 1] == '=') {
                            found = 2;
                            uind++;
                        } else if (uind == u - 1) {
                            found = 1;
                        }
                    }
                    if (!found) {
                        /* error */
                        LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, contextnode, ptr[uind], &ptr[uind]);
                        LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid Base64 character.");
                        goto error;
                    }
                }
            }
        }

        if (unum & 3) {
            /* base64 length must be multiple of 4 chars */
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
            }
            LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Base64 encoded value length must be divisible by 4.");
            goto error;
        }

        /* length of the encoded string */
        len = ((unum / 4) * 3) - found;
        if (!trusted && validate_length_range(0, len, 0, 0, 0, type, value, contextnode)) {
            goto error;
        }

        if (value && (ptr != value || ptr[u] != '\0')) {
            /* update the changed value */
            ptr = lydict_insert(ctx, ptr, u);
            lydict_remove(ctx, *value_);
            *value_ = ptr;
        }

        if (store) {
            /* store the result */
            val->binary = value;
            *val_type = LY_TYPE_BINARY;
        }
        break;

    case LY_TYPE_BITS:
        /* locate bits structure with the bits definitions
         * since YANG 1.1 allows restricted bits, it is the first
         * bits type with some explicit bit specification */
        for (; !type->info.bits.count; type = &type->der->type);

        if (value || store) {
            /* allocate the array of pointers to bits definition */
            bits = calloc(type->info.bits.count, sizeof *bits);
            LY_CHECK_ERR_GOTO(!bits, LOGMEM(ctx), error);
        }

        if (!value) {
            /* no bits set */
            if (store) {
                /* store empty array */
                val->bit = bits;
                *val_type = LY_TYPE_BITS;
            }
            break;
        }

        c = 0;
        i = 0;
        while (value[c]) {
            /* skip leading whitespaces */
            while (isspace(value[c])) {
                c++;
            }
            if (!value[c]) {
                /* trailing white spaces */
                break;
            }

            /* get the length of the bit identifier */
            for (len = 0; value[c] && !isspace(value[c]); c++, len++);

            /* go back to the beginning of the identifier */
            c = c - len;

            /* find bit definition, identifiers appear ordered by their position */
            for (found = i = 0; i < type->info.bits.count; i++) {
                if (!strncmp(type->info.bits.bit[i].name, &value[c], len) && !type->info.bits.bit[i].name[len]) {
                    /* we have match, check if the value is enabled ... */
                    for (j = 0; !trusted && (j < type->info.bits.bit[i].iffeature_size); j++) {
                        if (!resolve_iffeature(&type->info.bits.bit[i].iffeature[j])) {
                            if (leaf) {
                                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
                            } else {
                                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
                            }
                            LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL,
                                   "Bit \"%s\" is disabled by its %d. if-feature condition.",
                                   type->info.bits.bit[i].name, j + 1);
                            free(bits);
                            goto error;
                        }
                    }
                    /* check that the value was not already set */
                    if (bits[i]) {
                        if (leaf) {
                            LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
                        } else {
                            LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
                        }
                        LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" used multiple times.",
                               type->info.bits.bit[i].name);
                        free(bits);
                        goto error;
                    }
                    /* ... and then store the pointer */
                    bits[i] = &type->info.bits.bit[i];

                    /* stop searching */
                    found = 1;
                    break;
                }
            }

            if (!found) {
                /* referenced bit value does not exist */
                if (leaf) {
                    LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
                } else {
                    LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
                }
                free(bits);
                goto error;
            }
            c = c + len;
        }

        make_canonical(ctx, LY_TYPE_BITS, value_, bits, &type->info.bits.count);

        if (store) {
            /* store the result */
            val->bit = bits;
            *val_type = LY_TYPE_BITS;
        } else {
            free(bits);
        }
        break;

    case LY_TYPE_BOOL:
        if (value && !strcmp(value, "true")) {
            if (store) {
                val->bln = 1;
            }
        } else if (!value || strcmp(value, "false")) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
            }
            goto error;
        } else {
            if (store) {
                val->bln = 0;
            }
        }

        if (store) {
            *val_type = LY_TYPE_BOOL;
        }
        break;

    case LY_TYPE_DEC64:
        if (!value || !value[0]) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
            }
            goto error;
        }

        ptr = value;
        if (parse_range_dec64(&ptr, type->info.dec64.dig, &num) || ptr[0]) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
            }
            goto error;
        }

        if (!trusted && validate_length_range(2, 0, 0, num, type->info.dec64.dig, type, value, contextnode)) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_DEC64, value_, &num, &type->info.dec64.dig);

        if (store) {
            /* store the result */
            val->dec64 = num;
            *val_type = LY_TYPE_DEC64;
        }
        break;

    case LY_TYPE_EMPTY:
        if (value && value[0]) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
            }
            goto error;
        }

        if (store) {
            *val_type = LY_TYPE_EMPTY;
        }
        break;

    case LY_TYPE_ENUM:
        /* locate enums structure with the enumeration definitions,
         * since YANG 1.1 allows restricted enums, it is the first
         * enum type with some explicit enum specification */
        for (; !type->info.enums.count; type = &type->der->type);

        /* find matching enumeration value */
        for (i = found = 0; i < type->info.enums.count; i++) {
            if (value && !strcmp(value, type->info.enums.enm[i].name)) {
                /* we have match, check if the value is enabled ... */
                for (j = 0; !trusted && (j < type->info.enums.enm[i].iffeature_size); j++) {
                    if (!resolve_iffeature(&type->info.enums.enm[i].iffeature[j])) {
                        if (leaf) {
                            LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname);
                        } else {
                            LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value);
                        }
                        LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Enum \"%s\" is disabled by its %d. if-feature condition.",
                               value, j + 1);
                        goto error;
                    }
                }
                /* ... and store pointer to the definition */
                if (store) {
                    val->enm = &type->info.enums.enm[i];
                    *val_type = LY_TYPE_ENUM;
                }
                found = 1;
                break;
            }
        }

        if (!found) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : "");
            }
            goto error;
        }
        break;

    case LY_TYPE_IDENT:
        if (!value) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
            }
            goto error;
        }

        if (xml) {
            ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
            /* first, convert value into the json format, silently */
            value = transform_xml2json(ctx, value, xml, 0, 0);
            ly_ilo_restore(NULL, prev_ilo, NULL, 0);
            if (!value) {
                /* invalid identityref format */
                if (leaf) {
                    LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
                } else {
                    LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
                }
                goto error;
            }

            /* the value has no prefix (default namespace), but the element's namespace has a prefix, find default namespace */
            if (!strchr(value, ':') && xml->ns->prefix) {
                value = ident_val_add_module_prefix(value, xml, ctx);
                if (!value) {
                    goto error;
                }
            }
        } else if (dflt) {
            ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
            /* the value actually uses module's prefixes instead of the module names as in JSON format,
             * we have to convert it */
            value = transform_schema2json(local_mod, value);
            ly_ilo_restore(NULL, prev_ilo, NULL, 0);
            if (!value) {
                /* invalid identityref format or it was already transformed, so ignore the error here */
                value = lydict_insert(ctx, *value_, 0);
            }
        } else {
            value = lydict_insert(ctx, *value_, 0);
        }
        /* value is now in the dictionary, whether it differs from *value_ or not */

        ident = resolve_identref(type, value, contextnode, local_mod, dflt);
        if (!ident) {
            lydict_remove(ctx, value);
            goto error;
        } else if (store) {
            /* store the result */
            val->ident = ident;
            *val_type = LY_TYPE_IDENT;
        }

        /* the value is always changed and includes prefix */
        if (dflt) {
            type->parent->flags |= LYS_DFLTJSON;
        }

        make_canonical(ctx, LY_TYPE_IDENT, &value, (void*)lys_main_module(local_mod)->name, NULL);

        /* replace the old value with the new one (even if they may be the same) */
        lydict_remove(ctx, *value_);
        *value_ = value;
        break;

    case LY_TYPE_INST:
        if (!value) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
            }
            goto error;
        }

        if (xml) {
            ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
            /* first, convert value into the json format, silently */
            value = transform_xml2json(ctx, value, xml, 1, 1);
            ly_ilo_restore(NULL, prev_ilo, NULL, 0);
            if (!value) {
                /* invalid instance-identifier format */
                if (leaf) {
                    LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
                } else {
                    LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
                }
                goto error;
            } else if (ly_strequal(value, *value_, 1)) {
                /* we have actually created the same expression (prefixes are the same as the module names)
                 * so we have just increased dictionary's refcount - fix it */
                lydict_remove(ctx, value);
            }
        } else if (dflt) {
            /* turn logging off */
            ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);

            /* the value actually uses module's prefixes instead of the module names as in JSON format,
             * we have to convert it */
            value = transform_schema2json(local_mod, value);
            if (!value) {
                /* invalid identityref format or it was already transformed, so ignore the error here */
                value = *value_;
            } else if (ly_strequal(value, *value_, 1)) {
                /* we have actually created the same expression (prefixes are the same as the module names)
                 * so we have just increased dictionary's refcount - fix it */
                lydict_remove(ctx, value);
            }
            /* turn logging back on */
            ly_ilo_restore(NULL, prev_ilo, NULL, 0);
        } else {
            if (make_canonical(ctx, LY_TYPE_INST, &value, NULL, NULL)) {
                /* if a change occurred, value was removed from the dictionary so fix the pointers */
                *value_ = value;
            }
        }

        if (store) {
            /* note that the data node is an unresolved instance-identifier */
            val->instance = NULL;
            *val_type = LY_TYPE_INST;
            *val_flags |= LY_VALUE_UNRES;
        }

        if (!ly_strequal(value, *value_, 1)) {
            /* update the changed value */
            lydict_remove(ctx, *value_);
            *value_ = value;

            /* we have to remember the conversion into JSON format to be able to print it in correct form */
            if (dflt) {
                type->parent->flags |= LYS_DFLTJSON;
            }
        }
        break;

    case LY_TYPE_LEAFREF:
        if (!value) {
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, "");
            }
            goto error;
        }

        /* it is called not only to get the final type, but mainly to update value to canonical or JSON form
         * if needed */
        t = lyp_parse_value(&type->info.lref.target->type, value_, xml, leaf, attr, NULL, store, dflt, trusted);
        value = *value_; /* refresh possibly changed value */
        if (!t) {
            /* already logged */
            goto error;
        }

        if (store) {
            /* make the note that the data node is an unresolved leafref (value union was already filled) */
            *val_flags |= LY_VALUE_UNRES;
        }

        type = t;
        break;

    case LY_TYPE_STRING:
        if (!trusted && validate_length_range(0, (value ? ly_strlen_utf8(value) : 0), 0, 0, 0, type, value, contextnode)) {
            goto error;
        }

        if (!trusted && validate_pattern(ctx, value, type, contextnode)) {
            goto error;
        }

        /* special handling of ietf-yang-types xpath1.0 */
        for (tpdf = type->der;
             tpdf->module && (strcmp(tpdf->name, "xpath1.0") || strcmp(tpdf->module->name, "ietf-yang-types"));
             tpdf = tpdf->type.der);
        if (tpdf->module && xml) {
            /* convert value into the json format */
            value = transform_xml2json(ctx, value ? value : "", xml, 1, 1);
            if (!value) {
                /* invalid instance-identifier format */
                if (leaf) {
                    LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname);
                } else {
                    LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
                }
                goto error;
            }

            if (!ly_strequal(value, *value_, 1)) {
                /* update the changed value */
                lydict_remove(ctx, *value_);
                *value_ = value;
            }
        }

        if (store) {
            /* store the result */
            val->string = value;
            *val_type = LY_TYPE_STRING;
        }
        break;

    case LY_TYPE_INT8:
        if (parse_int(value, __INT64_C(-128), __INT64_C(127), dflt ? 0 : 10, &num, contextnode)
                || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_INT8, value_, &num, NULL);

        if (store) {
            /* store the result */
            val->int8 = (int8_t)num;
            *val_type = LY_TYPE_INT8;
        }
        break;

    case LY_TYPE_INT16:
        if (parse_int(value, __INT64_C(-32768), __INT64_C(32767), dflt ? 0 : 10, &num, contextnode)
                || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_INT16, value_, &num, NULL);

        if (store) {
            /* store the result */
            val->int16 = (int16_t)num;
            *val_type = LY_TYPE_INT16;
        }
        break;

    case LY_TYPE_INT32:
        if (parse_int(value, __INT64_C(-2147483648), __INT64_C(2147483647), dflt ? 0 : 10, &num, contextnode)
                || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_INT32, value_, &num, NULL);

        if (store) {
            /* store the result */
            val->int32 = (int32_t)num;
            *val_type = LY_TYPE_INT32;
        }
        break;

    case LY_TYPE_INT64:
        if (parse_int(value, __INT64_C(-9223372036854775807) - __INT64_C(1), __INT64_C(9223372036854775807),
                      dflt ? 0 : 10, &num, contextnode)
                || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_INT64, value_, &num, NULL);

        if (store) {
            /* store the result */
            val->int64 = num;
            *val_type = LY_TYPE_INT64;
        }
        break;

    case LY_TYPE_UINT8:
        if (parse_uint(value, __UINT64_C(255), dflt ? 0 : 10, &unum, contextnode)
                || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_UINT8, value_, &unum, NULL);

        if (store) {
            /* store the result */
            val->uint8 = (uint8_t)unum;
            *val_type = LY_TYPE_UINT8;
        }
        break;

    case LY_TYPE_UINT16:
        if (parse_uint(value, __UINT64_C(65535), dflt ? 0 : 10, &unum, contextnode)
                || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_UINT16, value_, &unum, NULL);

        if (store) {
            /* store the result */
            val->uint16 = (uint16_t)unum;
            *val_type = LY_TYPE_UINT16;
        }
        break;

    case LY_TYPE_UINT32:
        if (parse_uint(value, __UINT64_C(4294967295), dflt ? 0 : 10, &unum, contextnode)
                || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_UINT32, value_, &unum, NULL);

        if (store) {
            /* store the result */
            val->uint32 = (uint32_t)unum;
            *val_type = LY_TYPE_UINT32;
        }
        break;

    case LY_TYPE_UINT64:
        if (parse_uint(value, __UINT64_C(18446744073709551615), dflt ? 0 : 10, &unum, contextnode)
                || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) {
            goto error;
        }

        make_canonical(ctx, LY_TYPE_UINT64, value_, &unum, NULL);

        if (store) {
            /* store the result */
            val->uint64 = unum;
            *val_type = LY_TYPE_UINT64;
        }
        break;

    case LY_TYPE_UNION:
        if (store) {
            /* unresolved union type */
            memset(val, 0, sizeof(lyd_val));
            *val_type = LY_TYPE_UNION;
        }

        if (type->info.uni.has_ptr_type) {
            /* we are not resolving anything here, only parsing, and in this case we cannot decide
             * the type without resolving it -> we return the union type (resolve it with resolve_union()) */
            if (xml) {
                /* in case it should resolve into a instance-identifier, we can only do the JSON conversion here */
                ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);
                val->string = transform_xml2json(ctx, value, xml, 1, 1);
                ly_ilo_restore(NULL, prev_ilo, NULL, 0);
                if (!val->string) {
                    /* invalid instance-identifier format, likely some other type */
                    val->string = lydict_insert(ctx, value, 0);
                }
            }
            break;
        }

        t = NULL;
        found = 0;

        /* turn logging off, we are going to try to validate the value with all the types in order */
        ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL);

        while ((t = lyp_get_next_union_type(type, t, &found))) {
            found = 0;
            ret = lyp_parse_value(t, value_, xml, leaf, attr, NULL, store, dflt, 0);
            if (ret) {
                /* we have the result */
                type = ret;
                break;
            }

            if (store) {
                /* erase possible present and invalid value data */
                lyd_free_value(*val, *val_type, *val_flags, t, *value_, NULL, NULL, NULL);
                memset(val, 0, sizeof(lyd_val));
            }
        }

        /* turn logging back on */
        ly_ilo_restore(NULL, prev_ilo, NULL, 0);

        if (!t) {
            /* not found */
            if (store) {
                *val_type = 0;
            }
            if (leaf) {
                LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_ ? *value_ : "", itemname);
            } else {
                LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_);
            }
            goto error;
        }
        break;

    default:
        LOGINT(ctx);
        goto error;
    }

    /* search user types in case this value is supposed to be stored in a custom way */
    if (store && type->der && type->der->module) {
        c = lytype_store(type->der->module, type->der->name, value_, val);
        if (c == -1) {
            goto error;
        } else if (!c) {
            *val_flags |= LY_VALUE_USER;
        }
    }

    /* free backup */
    if (store) {
        lyd_free_value(old_val, old_val_type, old_val_flags, type, old_val_str, NULL, NULL, NULL);
        lydict_remove(ctx, old_val_str);
    }
    return type;

error:
    /* restore the backup */
    if (store) {
        *val = old_val;
        *val_type = old_val_type;
        *val_flags = old_val_flags;
        lydict_remove(ctx, old_val_str);
    }
    return NULL;
}


static char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc)
{
  const char *it = s;
  const char *end = s + len;

  if (enc == ENCQUOTEDPRINTABLE)
  {
    struct Buffer buf = { 0 };
    for (; it < end; ++it)
    {
      if (*it == '_')
      {
        mutt_buffer_addch(&buf, ' ');
      }
      else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) &&
               (!(it[2] & ~127) && hexval(it[2]) != -1))
      {
        mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2]));
        it += 2;
      }
      else
      {
        mutt_buffer_addch(&buf, *it);
      }
    }
    mutt_buffer_addch(&buf, '\0');
    return buf.data;
  }
  else if (enc == ENCBASE64)
  {
    char *out = mutt_mem_malloc(3 * len / 4 + 1);
    int dlen = mutt_b64_decode(out, it);
    if (dlen == -1)
    {
      FREE(&out);
      return NULL;
    }
    out[dlen] = '\0';
    return out;
  }

  assert(0); /* The enc parameter has an invalid value */
  return NULL;
}


err_t verify_signed_hash(const struct RSA_public_key *k
                         , u_char *s, unsigned int s_max_octets
                         , u_char **psig
                         , size_t hash_len
                         , const u_char *sig_val, size_t sig_len)
{
    unsigned int padlen;

    /* actual exponentiation; see PKCS#1 v2.0 5.1 */
    {
	chunk_t temp_s;
	MP_INT c;

	n_to_mpz(&c, sig_val, sig_len);
	oswcrypto.mod_exp(&c, &c, &k->e, &k->n);

	temp_s = mpz_to_n(&c, sig_len);	/* back to octets */
        if(s_max_octets < sig_len) {
            return "2""exponentiation failed; too many octets";
        }
	memcpy(s, temp_s.ptr, sig_len);
	pfree(temp_s.ptr);
	mpz_clear(&c);
    }

    /* check signature contents */
    /* verify padding (not including any DER digest info! */
    padlen = sig_len - 3 - hash_len;
    /* now check padding */

    DBG(DBG_CRYPT,
	DBG_dump("verify_sh decrypted SIG1:", s, sig_len));
    DBG(DBG_CRYPT, DBG_log("pad_len calculated: %d hash_len: %d", padlen, (int)hash_len));

    /* skip padding */
    if(s[0]    != 0x00
       || s[1] != 0x01
       || s[padlen+2] != 0x00) {
	return "3""SIG padding does not check out";
    }

    s += padlen + 3;
    (*psig) = s;

    /* return SUCCESS */
    return NULL;
}


static void slice_thread_park_workers(ThreadContext *c) { pthread_cond_wait(&c->last_job_cond, &c->current_job_lock); pthread_mutex_unlock(&c->current_job_lock); }


static void multiwrite_cb(void *opaque, int ret) { MultiwriteCB *mcb = opaque; if (ret < 0) { mcb->error = ret; multiwrite_user_cb(mcb); } mcb->num_requests--; if (mcb->num_requests == 0) { if (mcb->error == 0) { multiwrite_user_cb(mcb); } qemu_free(mcb); } }


CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
    bool ok;
    XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
    enum xkb_file_type type;
    struct xkb_context *ctx = keymap->ctx;

    /* Collect section files and check for duplicates. */
    for (file = (XkbFile *) file->defs; file;
         file = (XkbFile *) file->common.next) {
        if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
            file->file_type > LAST_KEYMAP_FILE_TYPE) {
            log_err(ctx, "Cannot define %s in a keymap file\n",
                    xkb_file_type_to_string(file->file_type));
            continue;
        }

        if (files[file->file_type]) {
            log_err(ctx,
                    "More than one %s section in keymap file; "
                    "All sections after the first ignored\n",
                    xkb_file_type_to_string(file->file_type));
            continue;
        }

        files[file->file_type] = file;
    }

    /*
     * Check that all required section were provided.
     * Report everything before failing.
     */
    ok = true;
    for (type = FIRST_KEYMAP_FILE_TYPE;
         type <= LAST_KEYMAP_FILE_TYPE;
         type++) {
        if (files[type] == NULL) {
            log_err(ctx, "Required section %s missing from keymap\n",
                    xkb_file_type_to_string(type));
            ok = false;
        }
    }
    if (!ok)
        return false;

    /* Compile sections. */
    for (type = FIRST_KEYMAP_FILE_TYPE;
         type <= LAST_KEYMAP_FILE_TYPE;
         type++) {
        log_dbg(ctx, "Compiling %s \"%s\"\n",
                xkb_file_type_to_string(type), files[type]->name);

        ok = compile_file_fns[type](files[type], keymap, merge);
        if (!ok) {
            log_err(ctx, "Failed to compile %s\n",
                    xkb_file_type_to_string(type));
            return false;
        }
    }

    return UpdateDerivedKeymapFields(keymap);
}


static void inet_get_ping_group_range_table ( struct ctl_table * table , gid_t * low , gid_t * high ) {
 gid_t * data = table -> data ;
 unsigned int seq ;
 do {
 seq = read_seqbegin ( & sysctl_local_ports . lock ) ;
 * low = data [ 0 ] ;
 * high = data [ 1 ] ;
 }
 while ( read_seqretry ( & sysctl_local_ports . lock , seq ) ) ;
 }


static void pci_reg_write4(void *opaque, target_phys_addr_t addr, uint32_t value) { PPCE500PCIState *pci = opaque; unsigned long win; win = addr & 0xfe0; pci_debug("%s: value:%x -> win:%lx(addr:" TARGET_FMT_plx ")\n", __func__, value, win, addr); switch (win) { case PPCE500_PCI_OW1: case PPCE500_PCI_OW2: case PPCE500_PCI_OW3: case PPCE500_PCI_OW4: switch (addr & 0xC) { case PCI_POTAR: pci->pob[(addr >> 5) & 0x7].potar = value; break; case PCI_POTEAR: pci->pob[(addr >> 5) & 0x7].potear = value; break; case PCI_POWBAR: pci->pob[(addr >> 5) & 0x7].powbar = value; break; case PCI_POWAR: pci->pob[(addr >> 5) & 0x7].powar = value; break; default: break; }; break; case PPCE500_PCI_IW3: case PPCE500_PCI_IW2: case PPCE500_PCI_IW1: switch (addr & 0xC) { case PCI_PITAR: pci->pib[(addr >> 5) & 0x3].pitar = value; break; case PCI_PIWBAR: pci->pib[(addr >> 5) & 0x3].piwbar = value; break; case PCI_PIWBEAR: pci->pib[(addr >> 5) & 0x3].piwbear = value; break; case PCI_PIWAR: pci->pib[(addr >> 5) & 0x3].piwar = value; break; default: break; }; break; case PPCE500_PCI_GASKET_TIMR: pci->gasket_time = value; break; default: break; }; }


void trace_event_set_vcpu_state_dynamic(CPUState *vcpu, TraceEvent *ev, bool state) { TraceEventVCPUID vcpu_id; bool state_pre; assert(trace_event_get_state_static(ev)); assert(trace_event_is_vcpu(ev)); vcpu_id = trace_event_get_vcpu_id(ev); state_pre = test_bit(vcpu_id, vcpu->trace_dstate); if (state_pre != state) { if (state) { trace_events_enabled_count++; set_bit(vcpu_id, vcpu->trace_dstate); (*ev->dstate)++; } else { trace_events_enabled_count--; clear_bit(vcpu_id, vcpu->trace_dstate); (*ev->dstate)--; } } }


static int colo_packet_compare_icmp(Packet *spkt, Packet *ppkt) { int network_header_length = ppkt->ip->ip_hl * 4; trace_colo_compare_main("compare icmp"); /* * Because of ppkt and spkt are both in the same connection, * The ppkt's src ip, dst ip, src port, dst port, ip_proto all are * same with spkt. In addition, IP header's Identification is a random * field, we can handle it in IP fragmentation function later. * COLO just concern the response net packet payload from primary guest * and secondary guest are same or not, So we ignored all IP header include * other field like TOS,TTL,IP Checksum. we only need to compare * the ip payload here. */ if (colo_packet_compare_common(ppkt, spkt, network_header_length + ETH_HLEN)) { trace_colo_compare_icmp_miscompare("primary pkt size", ppkt->size); trace_colo_compare_icmp_miscompare("Secondary pkt size", spkt->size); if (trace_event_get_state(TRACE_COLO_COMPARE_MISCOMPARE)) { qemu_hexdump((char *)ppkt->data, stderr, "colo-compare pri pkt", ppkt->size); qemu_hexdump((char *)spkt->data, stderr, "colo-compare sec pkt", spkt->size); } return -1; } else { return 0; } }


static int nut_read_packet(AVFormatContext *s, AVPacket *pkt) { NUTContext *nut = s->priv_data; StreamContext *stream; ByteIOContext *bc = &s->pb; int size, frame_code, flags, size_mul, size_lsb, stream_id; int key_frame = 0; int frame_type= 0; int64_t pts = 0; const int64_t frame_start= url_ftell(bc); if (url_feof(bc)) return -1; frame_code = get_byte(bc); if(frame_code == 'N'){ uint64_t tmp= frame_code; tmp<<=8 ; tmp |= get_byte(bc); tmp<<=16; tmp |= get_be16(bc); tmp<<=32; tmp |= get_be32(bc); if (tmp == KEYFRAME_STARTCODE) { frame_code = get_byte(bc); frame_type = 2; } else av_log(s, AV_LOG_ERROR, "error in zero bit / startcode %LX\n", tmp); } flags= nut->frame_code[frame_code].flags; size_mul= nut->frame_code[frame_code].size_mul; size_lsb= nut->frame_code[frame_code].size_lsb; stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1; if(flags & FLAG_FRAME_TYPE){ reset(s); if(frame_type==2){ get_packetheader(nut, bc, 8+1, 0); }else{ get_packetheader(nut, bc, 1, 0); frame_type= 1; } } if(stream_id==-1) stream_id= get_v(bc); if(stream_id >= s->nb_streams){ av_log(s, AV_LOG_ERROR, "illegal stream_id\n"); return -1; } stream= &nut->stream[stream_id]; if(flags & FLAG_PRED_KEY_FRAME){ if(flags & FLAG_KEY_FRAME) key_frame= !stream->last_key_frame; else key_frame= stream->last_key_frame; }else{ key_frame= !!(flags & FLAG_KEY_FRAME); } if(flags & FLAG_PTS){ if(flags & FLAG_FULL_PTS){ pts= get_v(bc); }else{ int64_t mask = (1<<stream->msb_timestamp_shift)-1; int64_t delta= stream->last_pts - mask/2; pts= ((get_v(bc) - delta)&mask) + delta; } }else{ pts= stream->last_pts + stream->lru_pts_delta[(flags&12)>>2]; } if(size_mul <= size_lsb){ size= stream->lru_size[size_lsb - size_mul]; }else{ if(flags & FLAG_DATA_SIZE) size= size_mul*get_v(bc) + size_lsb; else size= size_lsb; } //av_log(s, AV_LOG_DEBUG, "fs:%lld fc:%d ft:%d kf:%d pts:%lld\n", frame_start, frame_code, frame_type, key_frame, pts); av_new_packet(pkt, size); get_buffer(bc, pkt->data, size); pkt->stream_index = stream_id; if (key_frame) pkt->flags |= PKT_FLAG_KEY; pkt->pts = pts * AV_TIME_BASE * stream->rate_den / stream->rate_num; update(nut, stream_id, frame_start, frame_type, frame_code, key_frame, size, pts); return 0; }