krb5_ldap_put_principal(krb5_context context, krb5_db_entry *entry,
                        char **db_args)
{
    int                         l=0, kerberos_principal_object_type=0;
    unsigned int                ntrees=0, tre=0;
    krb5_error_code             st=0, tempst=0;
    LDAP                        *ld=NULL;
    LDAPMessage                 *result=NULL, *ent=NULL;
    char                        **subtreelist = NULL;
    char                        *user=NULL, *subtree=NULL, *principal_dn=NULL;
    char                        **values=NULL, *strval[10]={NULL}, errbuf[1024];
    char                        *filtuser=NULL;
    struct berval               **bersecretkey=NULL;
    LDAPMod                     **mods=NULL;
    krb5_boolean                create_standalone=FALSE;
    krb5_boolean                krb_identity_exists=FALSE, establish_links=FALSE;
    char                        *standalone_principal_dn=NULL;
    krb5_tl_data                *tl_data=NULL;
    krb5_key_data               **keys=NULL;
    kdb5_dal_handle             *dal_handle=NULL;
    krb5_ldap_context           *ldap_context=NULL;
    krb5_ldap_server_handle     *ldap_server_handle=NULL;
    osa_princ_ent_rec           princ_ent = {0};
    xargs_t                     xargs = {0};
    char                        *polname = NULL;
    OPERATION optype;
    krb5_boolean                found_entry = FALSE;

    /* Clear the global error string */
    krb5_clear_error_message(context);

    SETUP_CONTEXT();
    if (ldap_context->lrparams == NULL || ldap_context->container_dn == NULL)
        return EINVAL;

    /* get ldap handle */
    GET_HANDLE();

    if (!is_principal_in_realm(ldap_context, entry->princ)) {
        st = EINVAL;
        k5_setmsg(context, st,
                  _("Principal does not belong to the default realm"));
        goto cleanup;
    }

    /* get the principal information to act on */
    if (((st=krb5_unparse_name(context, entry->princ, &user)) != 0) ||
        ((st=krb5_ldap_unparse_principal_name(user)) != 0))
        goto cleanup;
    filtuser = ldap_filter_correct(user);
    if (filtuser == NULL) {
        st = ENOMEM;
        goto cleanup;
    }

    /* Identity the type of operation, it can be
     * add principal or modify principal.
     * hack if the entry->mask has KRB_PRINCIPAL flag set
     * then it is a add operation
     */
    if (entry->mask & KADM5_PRINCIPAL)
        optype = ADD_PRINCIPAL;
    else
        optype = MODIFY_PRINCIPAL;

    if (((st=krb5_get_princ_type(context, entry, &kerberos_principal_object_type)) != 0) ||
        ((st=krb5_get_userdn(context, entry, &principal_dn)) != 0))
        goto cleanup;

    if ((st=process_db_args(context, db_args, &xargs, optype)) != 0)
        goto cleanup;

    if (entry->mask & KADM5_LOAD) {
        unsigned int     tree = 0;
        int              numlentries = 0;
        char             *filter = NULL;

        /*  A load operation is special, will do a mix-in (add krbprinc
         *  attrs to a non-krb object entry) if an object exists with a
         *  matching krbprincipalname attribute so try to find existing
         *  object and set principal_dn.  This assumes that the
         *  krbprincipalname attribute is unique (only one object entry has
         *  a particular krbprincipalname attribute).
         */
        if (asprintf(&filter, FILTER"%s))", filtuser) < 0) {
            filter = NULL;
            st = ENOMEM;
            goto cleanup;
        }

        /* get the current subtree list */
        if ((st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees)) != 0)
            goto cleanup;

        found_entry = FALSE;
        /* search for entry with matching krbprincipalname attribute */
        for (tree = 0; found_entry == FALSE && tree < ntrees; ++tree) {
            if (principal_dn == NULL) {
                LDAP_SEARCH_1(subtreelist[tree], ldap_context->lrparams->search_scope, filter, principal_attributes, IGNORE_STATUS);
            } else {
                /* just look for entry with principal_dn */
                LDAP_SEARCH_1(principal_dn, LDAP_SCOPE_BASE, filter, principal_attributes, IGNORE_STATUS);
            }
            if (st == LDAP_SUCCESS) {
                numlentries = ldap_count_entries(ld, result);
                if (numlentries > 1) {
                    free(filter);
                    st = EINVAL;
                    k5_setmsg(context, st,
                              _("operation can not continue, more than one "
                                "entry with principal name \"%s\" found"),
                              user);
                    goto cleanup;
                } else if (numlentries == 1) {
                    found_entry = TRUE;
                    if (principal_dn == NULL) {
                        ent = ldap_first_entry(ld, result);
                        if (ent != NULL) {
                            /* setting principal_dn will cause that entry to be modified further down */
                            if ((principal_dn = ldap_get_dn(ld, ent)) == NULL) {
                                ldap_get_option (ld, LDAP_OPT_RESULT_CODE, &st);
                                st = set_ldap_error (context, st, 0);
                                free(filter);
                                goto cleanup;
                            }
                        }
                    }
                }
            } else if (st != LDAP_NO_SUCH_OBJECT) {
                /* could not perform search, return with failure */
                st = set_ldap_error (context, st, 0);
                free(filter);
                goto cleanup;
            }
            ldap_msgfree(result);
            result = NULL;
            /*
             * If it isn't found then assume a standalone princ entry is to
             * be created.
             */
        } /* end for (tree = 0; principal_dn == ... */

        free(filter);

        if (found_entry == FALSE && principal_dn != NULL) {
            /*
             * if principal_dn is null then there is code further down to
             * deal with setting standalone_principal_dn.  Also note that
             * this will set create_standalone true for
             * non-mix-in entries which is okay if loading from a dump.
             */
            create_standalone = TRUE;
            standalone_principal_dn = strdup(principal_dn);
            CHECK_NULL(standalone_principal_dn);
        }
    } /* end if (entry->mask & KADM5_LOAD */

    /* time to generate the DN information with the help of
     * containerdn, principalcontainerreference or
     * realmcontainerdn information
     */
    if (principal_dn == NULL && xargs.dn == NULL) { /* creation of standalone principal */
        /* get the subtree information */
        if (entry->princ->length == 2 && entry->princ->data[0].length == strlen("krbtgt") &&
            strncmp(entry->princ->data[0].data, "krbtgt", entry->princ->data[0].length) == 0) {
            /* if the principal is a inter-realm principal, always created in the realm container */
            subtree = strdup(ldap_context->lrparams->realmdn);
        } else if (xargs.containerdn) {
            if ((st=checkattributevalue(ld, xargs.containerdn, NULL, NULL, NULL)) != 0) {
                if (st == KRB5_KDB_NOENTRY || st == KRB5_KDB_CONSTRAINT_VIOLATION) {
                    int ost = st;
                    st = EINVAL;
                    k5_wrapmsg(context, ost, st, _("'%s' not found"),
                               xargs.containerdn);
                }
                goto cleanup;
            }
            subtree = strdup(xargs.containerdn);
        } else if (ldap_context->lrparams->containerref && strlen(ldap_context->lrparams->containerref) != 0) {
            /*
             * Here the subtree should be changed with
             * principalcontainerreference attribute value
             */
            subtree = strdup(ldap_context->lrparams->containerref);
        } else {
            subtree = strdup(ldap_context->lrparams->realmdn);
        }
        CHECK_NULL(subtree);

        if (asprintf(&standalone_principal_dn, "krbprincipalname=%s,%s",
                     filtuser, subtree) < 0)
            standalone_principal_dn = NULL;
        CHECK_NULL(standalone_principal_dn);
        /*
         * free subtree when you are done using the subtree
         * set the boolean create_standalone to TRUE
         */
        create_standalone = TRUE;
        free(subtree);
        subtree = NULL;
    }

    /*
     * If the DN information is presented by the user, time to
     * validate the input to ensure that the DN falls under
     * any of the subtrees
     */
    if (xargs.dn_from_kbd == TRUE) {
        /* make sure the DN falls in the subtree */
        int              dnlen=0, subtreelen=0;
        char             *dn=NULL;
        krb5_boolean     outofsubtree=TRUE;

        if (xargs.dn != NULL) {
            dn = xargs.dn;
        } else if (xargs.linkdn != NULL) {
            dn = xargs.linkdn;
        } else if (standalone_principal_dn != NULL) {
            /*
             * Even though the standalone_principal_dn is constructed
             * within this function, there is the containerdn input
             * from the user that can become part of the it.
             */
            dn = standalone_principal_dn;
        }

        /* Get the current subtree list if we haven't already done so. */
        if (subtreelist == NULL) {
            st = krb5_get_subtree_info(ldap_context, &subtreelist, &ntrees);
            if (st)
                goto cleanup;
        }

        for (tre=0; tre<ntrees; ++tre) {
            if (subtreelist[tre] == NULL || strlen(subtreelist[tre]) == 0) {
                outofsubtree = FALSE;
                break;
            } else {
                dnlen = strlen (dn);
                subtreelen = strlen(subtreelist[tre]);
                if ((dnlen >= subtreelen) && (strcasecmp((dn + dnlen - subtreelen), subtreelist[tre]) == 0)) {
                    outofsubtree = FALSE;
                    break;
                }
            }
        }

        if (outofsubtree == TRUE) {
            st = EINVAL;
            k5_setmsg(context, st, _("DN is out of the realm subtree"));
            goto cleanup;
        }

        /*
         * dn value will be set either by dn, linkdn or the standalone_principal_dn
         * In the first 2 cases, the dn should be existing and in the last case we
         * are supposed to create the ldap object. so the below should not be
         * executed for the last case.
         */

        if (standalone_principal_dn == NULL) {
            /*
             * If the ldap object is missing, this results in an error.
             */

            /*
             * Search for krbprincipalname attribute here.
             * This is to find if a kerberos identity is already present
             * on the ldap object, in which case adding a kerberos identity
             * on the ldap object should result in an error.
             */
            char  *attributes[]={"krbticketpolicyreference", "krbprincipalname", NULL};

            ldap_msgfree(result);
            result = NULL;
            LDAP_SEARCH_1(dn, LDAP_SCOPE_BASE, 0, attributes, IGNORE_STATUS);
            if (st == LDAP_SUCCESS) {
                ent = ldap_first_entry(ld, result);
                if (ent != NULL) {
                    if ((values=ldap_get_values(ld, ent, "krbticketpolicyreference")) != NULL) {
                        ldap_value_free(values);
                    }

                    if ((values=ldap_get_values(ld, ent, "krbprincipalname")) != NULL) {
                        krb_identity_exists = TRUE;
                        ldap_value_free(values);
                    }
                }
            } else {
                st = set_ldap_error(context, st, OP_SEARCH);
                goto cleanup;
            }
        }
    }

    /*
     * If xargs.dn is set then the request is to add a
     * kerberos principal on a ldap object, but if
     * there is one already on the ldap object this
     * should result in an error.
     */

    if (xargs.dn != NULL && krb_identity_exists == TRUE) {
        st = EINVAL;
        snprintf(errbuf, sizeof(errbuf),
                 _("ldap object is already kerberized"));
        k5_setmsg(context, st, "%s", errbuf);
        goto cleanup;
    }

    if (xargs.linkdn != NULL) {
        /*
         * link information can be changed using modprinc.
         * However, link information can be changed only on the
         * standalone kerberos principal objects. A standalone
         * kerberos principal object is of type krbprincipal
         * structural objectclass.
         *
         * NOTE: kerberos principals on an ldap object can't be
         * linked to other ldap objects.
         */
        if (optype == MODIFY_PRINCIPAL &&
            kerberos_principal_object_type != KDB_STANDALONE_PRINCIPAL_OBJECT) {
            st = EINVAL;
            snprintf(errbuf, sizeof(errbuf),
                     _("link information can not be set/updated as the "
                       "kerberos principal belongs to an ldap object"));
            k5_setmsg(context, st, "%s", errbuf);
            goto cleanup;
        }
        /*
         * Check the link information. If there is already a link
         * existing then this operation is not allowed.
         */
        {
            char **linkdns=NULL;
            int  j=0;

            if ((st=krb5_get_linkdn(context, entry, &linkdns)) != 0) {
                snprintf(errbuf, sizeof(errbuf),
                         _("Failed getting object references"));
                k5_setmsg(context, st, "%s", errbuf);
                goto cleanup;
            }
            if (linkdns != NULL) {
                st = EINVAL;
                snprintf(errbuf, sizeof(errbuf),
                         _("kerberos principal is already linked to a ldap "
                           "object"));
                k5_setmsg(context, st, "%s", errbuf);
                for (j=0; linkdns[j] != NULL; ++j)
                    free (linkdns[j]);
                free (linkdns);
                goto cleanup;
            }
        }

        establish_links = TRUE;
    }

    if (entry->mask & KADM5_LAST_SUCCESS) {
        memset(strval, 0, sizeof(strval));
        if ((strval[0]=getstringtime(entry->last_success)) == NULL)
            goto cleanup;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastSuccessfulAuth", LDAP_MOD_REPLACE, strval)) != 0) {
            free (strval[0]);
            goto cleanup;
        }
        free (strval[0]);
    }

    if (entry->mask & KADM5_LAST_FAILED) {
        memset(strval, 0, sizeof(strval));
        if ((strval[0]=getstringtime(entry->last_failed)) == NULL)
            goto cleanup;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastFailedAuth", LDAP_MOD_REPLACE, strval)) != 0) {
            free (strval[0]);
            goto cleanup;
        }
        free(strval[0]);
    }

    if (entry->mask & KADM5_FAIL_AUTH_COUNT) {
        krb5_kvno fail_auth_count;

        fail_auth_count = entry->fail_auth_count;
        if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT)
            fail_auth_count++;

        st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
                                       LDAP_MOD_REPLACE,
                                       fail_auth_count);
        if (st != 0)
            goto cleanup;
    } else if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT) {
        int attr_mask = 0;
        krb5_boolean has_fail_count;

        /* Check if the krbLoginFailedCount attribute exists.  (Through
         * krb5 1.8.1, it wasn't set in new entries.) */
        st = krb5_get_attributes_mask(context, entry, &attr_mask);
        if (st != 0)
            goto cleanup;
        has_fail_count = ((attr_mask & KDB_FAIL_AUTH_COUNT_ATTR) != 0);

        /*
         * If the client library and server supports RFC 4525,
         * then use it to increment by one the value of the
         * krbLoginFailedCount attribute. Otherwise, assert the
         * (provided) old value by deleting it before adding.
         */
#ifdef LDAP_MOD_INCREMENT
        if (ldap_server_handle->server_info->modify_increment &&
            has_fail_count) {
            st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
                                           LDAP_MOD_INCREMENT, 1);
            if (st != 0)
                goto cleanup;
        } else {
#endif /* LDAP_MOD_INCREMENT */
            if (has_fail_count) {
                st = krb5_add_int_mem_ldap_mod(&mods,
                                               "krbLoginFailedCount",
                                               LDAP_MOD_DELETE,
                                               entry->fail_auth_count);
                if (st != 0)
                    goto cleanup;
            }
            st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
                                           LDAP_MOD_ADD,
                                           entry->fail_auth_count + 1);
            if (st != 0)
                goto cleanup;
#ifdef LDAP_MOD_INCREMENT
        }
#endif
    } else if (optype == ADD_PRINCIPAL) {
        /* Initialize krbLoginFailedCount in new entries to help avoid a
         * race during the first failed login. */
        st = krb5_add_int_mem_ldap_mod(&mods, "krbLoginFailedCount",
                                       LDAP_MOD_ADD, 0);
    }

    if (entry->mask & KADM5_MAX_LIFE) {
        if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxticketlife", LDAP_MOD_REPLACE, entry->max_life)) != 0)
            goto cleanup;
    }

    if (entry->mask & KADM5_MAX_RLIFE) {
        if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbmaxrenewableage", LDAP_MOD_REPLACE,
                                          entry->max_renewable_life)) != 0)
            goto cleanup;
    }

    if (entry->mask & KADM5_ATTRIBUTES) {
        if ((st=krb5_add_int_mem_ldap_mod(&mods, "krbticketflags", LDAP_MOD_REPLACE,
                                          entry->attributes)) != 0)
            goto cleanup;
    }

    if (entry->mask & KADM5_PRINCIPAL) {
        memset(strval, 0, sizeof(strval));
        strval[0] = user;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalname", LDAP_MOD_REPLACE, strval)) != 0)
            goto cleanup;
    }

    if (entry->mask & KADM5_PRINC_EXPIRE_TIME) {
        memset(strval, 0, sizeof(strval));
        if ((strval[0]=getstringtime(entry->expiration)) == NULL)
            goto cleanup;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbprincipalexpiration", LDAP_MOD_REPLACE, strval)) != 0) {
            free (strval[0]);
            goto cleanup;
        }
        free (strval[0]);
    }

    if (entry->mask & KADM5_PW_EXPIRATION) {
        memset(strval, 0, sizeof(strval));
        if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL)
            goto cleanup;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpasswordexpiration",
                                          LDAP_MOD_REPLACE,
                                          strval)) != 0) {
            free (strval[0]);
            goto cleanup;
        }
        free (strval[0]);
    }

    if (entry->mask & KADM5_POLICY || entry->mask & KADM5_KEY_HIST) {
        memset(&princ_ent, 0, sizeof(princ_ent));
        for (tl_data=entry->tl_data; tl_data; tl_data=tl_data->tl_data_next) {
            if (tl_data->tl_data_type == KRB5_TL_KADM_DATA) {
                if ((st = krb5_lookup_tl_kadm_data(tl_data, &princ_ent)) != 0) {
                    goto cleanup;
                }
                break;
            }
        }
    }

    if (entry->mask & KADM5_POLICY) {
        if (princ_ent.aux_attributes & KADM5_POLICY) {
            memset(strval, 0, sizeof(strval));
            if ((st = krb5_ldap_name_to_policydn (context, princ_ent.policy, &polname)) != 0)
                goto cleanup;
            strval[0] = polname;
            if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, strval)) != 0)
                goto cleanup;
        } else {
            st = EINVAL;
            k5_setmsg(context, st, "Password policy value null");
            goto cleanup;
        }
    } else if (entry->mask & KADM5_LOAD && found_entry == TRUE) {
        /*
         * a load is special in that existing entries must have attrs that
         * removed.
         */

        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_REPLACE, NULL)) != 0)
            goto cleanup;
    }

    if (entry->mask & KADM5_POLICY_CLR) {
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbpwdpolicyreference", LDAP_MOD_DELETE, NULL)) != 0)
            goto cleanup;
    }

    if (entry->mask & KADM5_KEY_HIST) {
        bersecretkey = krb5_encode_histkey(&princ_ent);
        if (bersecretkey == NULL) {
            st = ENOMEM;
            goto cleanup;
        }

        st = krb5_add_ber_mem_ldap_mod(&mods, "krbpwdhistory",
                                       LDAP_MOD_REPLACE | LDAP_MOD_BVALUES,
                                       bersecretkey);
        if (st != 0)
            goto cleanup;
        free_berdata(bersecretkey);
        bersecretkey = NULL;
    }

    if (entry->mask & KADM5_KEY_DATA || entry->mask & KADM5_KVNO) {
        krb5_kvno mkvno;

        if ((st=krb5_dbe_lookup_mkvno(context, entry, &mkvno)) != 0)
            goto cleanup;
        bersecretkey = krb5_encode_krbsecretkey (entry->key_data,
                                                 entry->n_key_data, mkvno);

        if (bersecretkey == NULL) {
            st = ENOMEM;
            goto cleanup;
        }
        /* An empty list of bervals is only accepted for modify operations,
         * not add operations. */
        if (bersecretkey[0] != NULL || !create_standalone) {
            st = krb5_add_ber_mem_ldap_mod(&mods, "krbprincipalkey",
                                           LDAP_MOD_REPLACE | LDAP_MOD_BVALUES,
                                           bersecretkey);
            if (st != 0)
                goto cleanup;
        }

        if (!(entry->mask & KADM5_PRINCIPAL)) {
            memset(strval, 0, sizeof(strval));
            if ((strval[0]=getstringtime(entry->pw_expiration)) == NULL)
                goto cleanup;
            if ((st=krb5_add_str_mem_ldap_mod(&mods,
                                              "krbpasswordexpiration",
                                              LDAP_MOD_REPLACE, strval)) != 0) {
                free (strval[0]);
                goto cleanup;
            }
            free (strval[0]);
        }

        /* Update last password change whenever a new key is set */
        {
            krb5_timestamp last_pw_changed;
            if ((st=krb5_dbe_lookup_last_pwd_change(context, entry,
                                                    &last_pw_changed)) != 0)
                goto cleanup;

            memset(strval, 0, sizeof(strval));
            if ((strval[0] = getstringtime(last_pw_changed)) == NULL)
                goto cleanup;

            if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastPwdChange",
                                              LDAP_MOD_REPLACE, strval)) != 0) {
                free (strval[0]);
                goto cleanup;
            }
            free (strval[0]);
        }

    } /* Modify Key data ends here */

    /* Auth indicators will also be stored in krbExtraData when processing
     * tl_data. */
    st = update_ldap_mod_auth_ind(context, entry, &mods);
    if (st != 0)
        goto cleanup;

    /* Set tl_data */
    if (entry->tl_data != NULL) {
        int count = 0;
        struct berval **ber_tl_data = NULL;
        krb5_tl_data *ptr;
        krb5_timestamp unlock_time;
        for (ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) {
            if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE
#ifdef SECURID
                || ptr->tl_data_type == KRB5_TL_DB_ARGS
#endif
                || ptr->tl_data_type == KRB5_TL_KADM_DATA
                || ptr->tl_data_type == KDB_TL_USER_INFO
                || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL
                || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK)
                continue;
            count++;
        }
        if (count != 0) {
            int j;
            ber_tl_data = (struct berval **) calloc (count + 1,
                                                     sizeof (struct berval*));
            if (ber_tl_data == NULL) {
                st = ENOMEM;
                goto cleanup;
            }
            for (j = 0, ptr = entry->tl_data; ptr != NULL; ptr = ptr->tl_data_next) {
                /* Ignore tl_data that are stored in separate directory
                 * attributes */
                if (ptr->tl_data_type == KRB5_TL_LAST_PWD_CHANGE
#ifdef SECURID
                    || ptr->tl_data_type == KRB5_TL_DB_ARGS
#endif
                    || ptr->tl_data_type == KRB5_TL_KADM_DATA
                    || ptr->tl_data_type == KDB_TL_USER_INFO
                    || ptr->tl_data_type == KRB5_TL_CONSTRAINED_DELEGATION_ACL
                    || ptr->tl_data_type == KRB5_TL_LAST_ADMIN_UNLOCK)
                    continue;
                if ((st = tl_data2berval (ptr, &ber_tl_data[j])) != 0)
                    break;
                j++;
            }
            if (st == 0) {
                ber_tl_data[count] = NULL;
                st=krb5_add_ber_mem_ldap_mod(&mods, "krbExtraData",
                                             LDAP_MOD_REPLACE |
                                             LDAP_MOD_BVALUES, ber_tl_data);
            }
            free_berdata(ber_tl_data);
            if (st != 0)
                goto cleanup;
        }
        if ((st=krb5_dbe_lookup_last_admin_unlock(context, entry,
                                                  &unlock_time)) != 0)
            goto cleanup;
        if (unlock_time != 0) {
            /* Update last admin unlock */
            memset(strval, 0, sizeof(strval));
            if ((strval[0] = getstringtime(unlock_time)) == NULL)
                goto cleanup;

            if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbLastAdminUnlock",
                                              LDAP_MOD_REPLACE, strval)) != 0) {
                free (strval[0]);
                goto cleanup;
            }
            free (strval[0]);
        }
    }

    /* Directory specific attribute */
    if (xargs.tktpolicydn != NULL) {
        int tmask=0;

        if (strlen(xargs.tktpolicydn) != 0) {
            st = checkattributevalue(ld, xargs.tktpolicydn, "objectclass", policyclass, &tmask);
            CHECK_CLASS_VALIDITY(st, tmask, _("ticket policy object value: "));

            strval[0] = xargs.tktpolicydn;
            strval[1] = NULL;
            if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_REPLACE, strval)) != 0)
                goto cleanup;

        } else {
            /* if xargs.tktpolicydn is a empty string, then delete
             * already existing krbticketpolicyreference attr */
            if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbticketpolicyreference", LDAP_MOD_DELETE, NULL)) != 0)
                goto cleanup;
        }

    }

    if (establish_links == TRUE) {
        memset(strval, 0, sizeof(strval));
        strval[0] = xargs.linkdn;
        if ((st=krb5_add_str_mem_ldap_mod(&mods, "krbObjectReferences", LDAP_MOD_REPLACE, strval)) != 0)
            goto cleanup;
    }

    /*
     * in case mods is NULL then return
     * not sure but can happen in a modprinc
     * so no need to return an error
     * addprinc will at least have the principal name
     * and the keys passed in
     */
    if (mods == NULL)
        goto cleanup;

    if (create_standalone == TRUE) {
        memset(strval, 0, sizeof(strval));
        strval[0] = "krbprincipal";
        strval[1] = "krbprincipalaux";
        strval[2] = "krbTicketPolicyAux";

        if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0)
            goto cleanup;

        st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL);
        if (st == LDAP_ALREADY_EXISTS && entry->mask & KADM5_LOAD) {
            /* a load operation must replace an existing entry */
            st = ldap_delete_ext_s(ld, standalone_principal_dn, NULL, NULL);
            if (st != LDAP_SUCCESS) {
                snprintf(errbuf, sizeof(errbuf),
                         _("Principal delete failed (trying to replace "
                           "entry): %s"), ldap_err2string(st));
                st = translate_ldap_error (st, OP_ADD);
                k5_setmsg(context, st, "%s", errbuf);
                goto cleanup;
            } else {
                st = ldap_add_ext_s(ld, standalone_principal_dn, mods, NULL, NULL);
            }
        }
        if (st != LDAP_SUCCESS) {
            snprintf(errbuf, sizeof(errbuf), _("Principal add failed: %s"),
                     ldap_err2string(st));
            st = translate_ldap_error (st, OP_ADD);
            k5_setmsg(context, st, "%s", errbuf);
            goto cleanup;
        }
    } else {
        /*
         * Here existing ldap object is modified and can be related
         * to any attribute, so always ensure that the ldap
         * object is extended with all the kerberos related
         * objectclasses so that there are no constraint
         * violations.
         */
        {
            char *attrvalues[] = {"krbprincipalaux", "krbTicketPolicyAux", NULL};
            int p, q, r=0, amask=0;

            if ((st=checkattributevalue(ld, (xargs.dn) ? xargs.dn : principal_dn,
                                        "objectclass", attrvalues, &amask)) != 0)
                goto cleanup;

            memset(strval, 0, sizeof(strval));
            for (p=1, q=0; p<=2; p<<=1, ++q) {
                if ((p & amask) == 0)
                    strval[r++] = attrvalues[q];
            }
            if (r != 0) {
                if ((st=krb5_add_str_mem_ldap_mod(&mods, "objectclass", LDAP_MOD_ADD, strval)) != 0)
                    goto cleanup;
            }
        }
        if (xargs.dn != NULL)
            st=ldap_modify_ext_s(ld, xargs.dn, mods, NULL, NULL);
        else
            st = ldap_modify_ext_s(ld, principal_dn, mods, NULL, NULL);

        if (st != LDAP_SUCCESS) {
            snprintf(errbuf, sizeof(errbuf), _("User modification failed: %s"),
                     ldap_err2string(st));
            st = translate_ldap_error (st, OP_MOD);
            k5_setmsg(context, st, "%s", errbuf);
            goto cleanup;
        }

        if (entry->mask & KADM5_FAIL_AUTH_COUNT_INCREMENT)
            entry->fail_auth_count++;
    }

cleanup:
    if (user)
        free(user);

    if (filtuser)
        free(filtuser);

    free_xargs(xargs);

    if (standalone_principal_dn)
        free(standalone_principal_dn);

    if (principal_dn)
        free (principal_dn);

    if (polname != NULL)
        free(polname);

    for (tre = 0; tre < ntrees; tre++)
        free(subtreelist[tre]);
    free(subtreelist);

    if (subtree)
        free (subtree);

    if (bersecretkey) {
        for (l=0; bersecretkey[l]; ++l) {
            if (bersecretkey[l]->bv_val)
                free (bersecretkey[l]->bv_val);
            free (bersecretkey[l]);
        }
        free (bersecretkey);
    }

    if (keys)
        free (keys);

    ldap_mods_free(mods, 1);
    ldap_osa_free_princ_ent(&princ_ent);
    ldap_msgfree(result);
    krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle);
    return(st);
}


void traverse_commit_list ( struct rev_info * revs , show_commit_fn show_commit , show_object_fn show_object , void * data ) {
 int i ;
 struct commit * commit ;
 struct strbuf base ;
 strbuf_init ( & base , PATH_MAX ) ;
 while ( ( commit = get_revision ( revs ) ) != NULL ) {
 if ( commit -> tree ) add_pending_tree ( revs , commit -> tree ) ;
 show_commit ( commit , data ) ;
 }
 for ( i = 0 ;
 i < revs -> pending . nr ;
 i ++ ) {
 struct object_array_entry * pending = revs -> pending . objects + i ;
 struct object * obj = pending -> item ;
 const char * name = pending -> name ;
 const char * path = pending -> path ;
 if ( obj -> flags & ( UNINTERESTING | SEEN ) ) continue ;
 if ( obj -> type == OBJ_TAG ) {
 obj -> flags |= SEEN ;
 show_object ( obj , NULL , name , data ) ;
 continue ;
 }
 if ( ! path ) path = "" ;
 if ( obj -> type == OBJ_TREE ) {
 process_tree ( revs , ( struct tree * ) obj , show_object , NULL , & base , path , data ) ;
 continue ;
 }
 if ( obj -> type == OBJ_BLOB ) {
 process_blob ( revs , ( struct blob * ) obj , show_object , NULL , path , data ) ;
 continue ;
 }
 die ( "unknown pending object %s (%s)" , oid_to_hex ( & obj -> oid ) , name ) ;
 }
 object_array_clear ( & revs -> pending ) ;
 strbuf_release ( & base ) ;
 }


static void rtas_int_off(sPAPREnvironment *spapr, uint32_t token, uint32_t nargs, target_ulong args, uint32_t nret, target_ulong rets) { struct ics_state *ics = spapr->icp->ics; uint32_t nr; if ((nargs != 1) || (nret != 1)) { rtas_st(rets, 0, -3); return; } nr = rtas_ld(args, 0); if (!ics_valid_irq(ics, nr)) { rtas_st(rets, 0, -3); return; } ics_write_xive(ics, nr, ics->irqs[nr - ics->offset].server, 0xff, ics->irqs[nr - ics->offset].priority); rtas_st(rets, 0, 0); /* Success */ }


s4u_identify_user(krb5_context context,
                  krb5_creds *in_creds,
                  krb5_data *subject_cert,
                  krb5_principal *canon_user)
{
    krb5_error_code code;
    krb5_preauthtype ptypes[1] = { KRB5_PADATA_S4U_X509_USER };
    krb5_creds creds;
    int use_master = 0;
    krb5_get_init_creds_opt *opts = NULL;
    krb5_principal_data client;
    krb5_s4u_userid userid;

    *canon_user = NULL;

    if (in_creds->client == NULL && subject_cert == NULL) {
        return EINVAL;
    }

    if (in_creds->client != NULL &&
        in_creds->client->type != KRB5_NT_ENTERPRISE_PRINCIPAL) {
        int anonymous;

        anonymous = krb5_principal_compare(context, in_creds->client,
                                           krb5_anonymous_principal());

        return krb5_copy_principal(context,
                                   anonymous ? in_creds->server
                                   : in_creds->client,
                                   canon_user);
    }

    memset(&creds, 0, sizeof(creds));

    memset(&userid, 0, sizeof(userid));
    if (subject_cert != NULL)
        userid.subject_cert = *subject_cert;

    code = krb5_get_init_creds_opt_alloc(context, &opts);
    if (code != 0)
        goto cleanup;
    krb5_get_init_creds_opt_set_tkt_life(opts, 15);
    krb5_get_init_creds_opt_set_renew_life(opts, 0);
    krb5_get_init_creds_opt_set_forwardable(opts, 0);
    krb5_get_init_creds_opt_set_proxiable(opts, 0);
    krb5_get_init_creds_opt_set_canonicalize(opts, 1);
    krb5_get_init_creds_opt_set_preauth_list(opts, ptypes, 1);

    if (in_creds->client != NULL) {
        client = *in_creds->client;
        client.realm = in_creds->server->realm;
    } else {
        client.magic = KV5M_PRINCIPAL;
        client.realm = in_creds->server->realm;
        /* should this be NULL, empty or a fixed string? XXX */
        client.data = NULL;
        client.length = 0;
        client.type = KRB5_NT_ENTERPRISE_PRINCIPAL;
    }

    code = k5_get_init_creds(context, &creds, &client, NULL, NULL, 0, NULL,
                             opts, krb5_get_as_key_noop, &userid, &use_master,
                             NULL);
    if (code == 0 || code == KRB5_PREAUTH_FAILED) {
        *canon_user = userid.user;
        userid.user = NULL;
        code = 0;
    }

cleanup:
    krb5_free_cred_contents(context, &creds);
    if (opts != NULL)
        krb5_get_init_creds_opt_free(context, opts);
    if (userid.user != NULL)
        krb5_free_principal(context, userid.user);

    return code;
}


static ActivationAction get_activation_action ( NautilusFile * file ) {
 ActivationAction action ;
 char * activation_uri ;
 gboolean can_extract ;
 can_extract = g_settings_get_boolean ( nautilus_preferences , NAUTILUS_PREFERENCES_AUTOMATIC_DECOMPRESSION ) ;
 if ( can_extract && nautilus_file_is_archive ( file ) ) {
 return ACTIVATION_ACTION_EXTRACT ;
 }
 if ( nautilus_file_is_nautilus_link ( file ) ) {
 return ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE ;
 }
 activation_uri = nautilus_file_get_activation_uri ( file ) ;
 if ( activation_uri == NULL ) {
 activation_uri = nautilus_file_get_uri ( file ) ;
 }
 action = ACTIVATION_ACTION_DO_NOTHING ;
 if ( nautilus_file_is_launchable ( file ) ) {
 char * executable_path ;
 action = ACTIVATION_ACTION_LAUNCH ;
 executable_path = g_filename_from_uri ( activation_uri , NULL , NULL ) ;
 if ( ! executable_path ) {
 action = ACTIVATION_ACTION_DO_NOTHING ;
 }
 else if ( nautilus_file_contains_text ( file ) ) {
 action = get_default_executable_text_file_action ( ) ;
 }
 g_free ( executable_path ) ;
 }
 if ( action == ACTIVATION_ACTION_DO_NOTHING ) {
 if ( nautilus_file_opens_in_view ( file ) ) {
 action = ACTIVATION_ACTION_OPEN_IN_VIEW ;
 }
 else {
 action = ACTIVATION_ACTION_OPEN_IN_APPLICATION ;
 }
 }
 g_free ( activation_uri ) ;
 return action ;
 }


static void trim_marked(struct audit_tree *tree)
{
	struct list_head *p, *q;
	spin_lock(&hash_lock);
	if (tree->goner) {
		spin_unlock(&hash_lock);
		return;
	}
	/* reorder */
	for (p = tree->chunks.next; p != &tree->chunks; p = q) {
		struct node *node = list_entry(p, struct node, list);
		q = p->next;
		if (node->index & (1U<<31)) {
			list_del_init(p);
			list_add(p, &tree->chunks);
		}
	}

	while (!list_empty(&tree->chunks)) {
		struct node *node;
		struct audit_chunk *chunk;

		node = list_entry(tree->chunks.next, struct node, list);

		/* have we run out of marked? */
		if (!(node->index & (1U<<31)))
			break;

		chunk = find_chunk(node);
		get_inotify_watch(&chunk->watch);
		spin_unlock(&hash_lock);

		untag_chunk(chunk, node);

		put_inotify_watch(&chunk->watch);
		spin_lock(&hash_lock);
	}
	if (!tree->root && !tree->goner) {
		tree->goner = 1;
		spin_unlock(&hash_lock);
		mutex_lock(&audit_filter_mutex);
		kill_rules(tree);
		list_del_init(&tree->list);
		mutex_unlock(&audit_filter_mutex);
		prune_one(tree);
	} else {
		spin_unlock(&hash_lock);
	}
}


static void reorder_block ( MPADecodeContext * s , GranuleDef * g ) {
 int i , j , len ;
 INTFLOAT * ptr , * dst , * ptr1 ;
 INTFLOAT tmp [ 576 ] ;
 if ( g -> block_type != 2 ) return ;
 if ( g -> switch_point ) {
 if ( s -> sample_rate_index != 8 ) ptr = g -> sb_hybrid + 36 ;
 else ptr = g -> sb_hybrid + 72 ;
 }
 else {
 ptr = g -> sb_hybrid ;
 }
 for ( i = g -> short_start ;
 i < 13 ;
 i ++ ) {
 len = band_size_short [ s -> sample_rate_index ] [ i ] ;
 ptr1 = ptr ;
 dst = tmp ;
 for ( j = len ;
 j > 0 ;
 j -- ) {
 * dst ++ = ptr [ 0 * len ] ;
 * dst ++ = ptr [ 1 * len ] ;
 * dst ++ = ptr [ 2 * len ] ;
 ptr ++ ;
 }
 ptr += 2 * len ;
 memcpy ( ptr1 , tmp , len * 3 * sizeof ( * ptr1 ) ) ;
 }
 }


static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid, char *tag, uint32_t *vid, int for_snapshot) { int ret, fd; SheepdogVdiReq hdr; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; unsigned int wlen, rlen = 0; char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN]; fd = connect_to_sdog(s->addr, s->port); if (fd < 0) { return fd; } memset(buf, 0, sizeof(buf)); strncpy(buf, filename, SD_MAX_VDI_LEN); strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN); memset(&hdr, 0, sizeof(hdr)); if (for_snapshot) { hdr.opcode = SD_OP_GET_VDI_INFO; } else { hdr.opcode = SD_OP_LOCK_VDI; } wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN; hdr.proto_ver = SD_PROTO_VER; hdr.data_length = wlen; hdr.snapid = snapid; hdr.flags = SD_FLAG_CMD_WRITE; ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen); if (ret) { goto out; } if (rsp->result != SD_RES_SUCCESS) { error_report("cannot get vdi info, %s, %s %d %s", sd_strerror(rsp->result), filename, snapid, tag); if (rsp->result == SD_RES_NO_VDI) { ret = -ENOENT; } else { ret = -EIO; } goto out; } *vid = rsp->vdi_id; ret = 0; out: closesocket(fd); return ret; }


int inotify_rm_wd(struct inotify_handle *ih, u32 wd)
{
	struct inotify_watch *watch;
	struct inode *inode;

	mutex_lock(&ih->mutex);
	watch = idr_find(&ih->idr, wd);
	if (unlikely(!watch)) {
		mutex_unlock(&ih->mutex);
		return -EINVAL;
	}
	get_inotify_watch(watch);
	inode = watch->inode;
	mutex_unlock(&ih->mutex);

	mutex_lock(&inode->inotify_mutex);
	mutex_lock(&ih->mutex);

	/* make sure that we did not race */
	if (likely(idr_find(&ih->idr, wd) == watch))
		inotify_remove_watch_locked(ih, watch);

	mutex_unlock(&ih->mutex);
	mutex_unlock(&inode->inotify_mutex);
	put_inotify_watch(watch);

	return 0;
}


split_der(asn1buf *buf, uint8_t *const *der, size_t len, taginfo *tag_out)
{
    krb5_error_code ret;
    const uint8_t *contents, *remainder;
    size_t clen, rlen;

    ret = get_tag(*der, len, tag_out, &contents, &clen, &remainder, &rlen);
    if (ret)
        return ret;
    if (rlen != 0)
        return ASN1_BAD_LENGTH;
    insert_bytes(buf, contents, clen);
    return 0;
}


void address_space_init(AddressSpace *as, MemoryRegion *root) { memory_region_transaction_begin(); as->root = root; as->current_map = g_new(FlatView, 1); flatview_init(as->current_map); QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link); as->name = NULL; memory_region_transaction_commit(); address_space_init_dispatch(as); }


static int decode_frame ( AVCodecContext * avctx , void * data , int * got_frame_ptr , AVPacket * avpkt ) {
 RALFContext * ctx = avctx -> priv_data ;
 AVFrame * frame = data ;
 int16_t * samples0 ;
 int16_t * samples1 ;
 int ret ;
 GetBitContext gb ;
 int table_size , table_bytes , i ;
 const uint8_t * src , * block_pointer ;
 int src_size ;
 int bytes_left ;
 if ( ctx -> has_pkt ) {
 ctx -> has_pkt = 0 ;
 table_bytes = ( AV_RB16 ( avpkt -> data ) + 7 ) >> 3 ;
 if ( table_bytes + 3 > avpkt -> size || avpkt -> size > RALF_MAX_PKT_SIZE ) {
 av_log ( avctx , AV_LOG_ERROR , "Wrong packet's breath smells of wrong data!\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 if ( memcmp ( ctx -> pkt , avpkt -> data , 2 + table_bytes ) ) {
 av_log ( avctx , AV_LOG_ERROR , "Wrong packet tails are wrong!\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 src = ctx -> pkt ;
 src_size = RALF_MAX_PKT_SIZE + avpkt -> size ;
 memcpy ( ctx -> pkt + RALF_MAX_PKT_SIZE , avpkt -> data + 2 + table_bytes , avpkt -> size - 2 - table_bytes ) ;
 }
 else {
 if ( avpkt -> size == RALF_MAX_PKT_SIZE ) {
 memcpy ( ctx -> pkt , avpkt -> data , avpkt -> size ) ;
 ctx -> has_pkt = 1 ;
 * got_frame_ptr = 0 ;
 return avpkt -> size ;
 }
 src = avpkt -> data ;
 src_size = avpkt -> size ;
 }
 frame -> nb_samples = ctx -> max_frame_size ;
 if ( ( ret = ff_get_buffer ( avctx , frame ) ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "Me fail get_buffer()? That's unpossible!\n" ) ;
 return ret ;
 }
 samples0 = ( int16_t * ) frame -> data [ 0 ] ;
 samples1 = ( int16_t * ) frame -> data [ 1 ] ;
 if ( src_size < 5 ) {
 av_log ( avctx , AV_LOG_ERROR , "too short packets are too short!\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 table_size = AV_RB16 ( src ) ;
 table_bytes = ( table_size + 7 ) >> 3 ;
 if ( src_size < table_bytes + 3 ) {
 av_log ( avctx , AV_LOG_ERROR , "short packets are short!\n" ) ;
 return AVERROR_INVALIDDATA ;
 }
 init_get_bits ( & gb , src + 2 , table_size ) ;
 ctx -> num_blocks = 0 ;
 while ( get_bits_left ( & gb ) > 0 ) {
 ctx -> block_size [ ctx -> num_blocks ] = get_bits ( & gb , 15 ) ;
 if ( get_bits1 ( & gb ) ) {
 ctx -> block_pts [ ctx -> num_blocks ] = get_bits ( & gb , 9 ) ;
 }
 else {
 ctx -> block_pts [ ctx -> num_blocks ] = 0 ;
 }
 ctx -> num_blocks ++ ;
 }
 block_pointer = src + table_bytes + 2 ;
 bytes_left = src_size - table_bytes - 2 ;
 ctx -> sample_offset = 0 ;
 for ( i = 0 ;
 i < ctx -> num_blocks ;
 i ++ ) {
 if ( bytes_left < ctx -> block_size [ i ] ) {
 av_log ( avctx , AV_LOG_ERROR , "I'm pedaling backwards\n" ) ;
 break ;
 }
 init_get_bits ( & gb , block_pointer , ctx -> block_size [ i ] * 8 ) ;
 if ( decode_block ( avctx , & gb , samples0 + ctx -> sample_offset , samples1 + ctx -> sample_offset ) < 0 ) {
 av_log ( avctx , AV_LOG_ERROR , "Sir, I got carsick in your office. Not decoding the rest of packet.\n" ) ;
 break ;
 }
 block_pointer += ctx -> block_size [ i ] ;
 bytes_left -= ctx -> block_size [ i ] ;
 }
 frame -> nb_samples = ctx -> sample_offset ;
 * got_frame_ptr = ctx -> sample_offset > 0 ;
 return avpkt -> size ;
 }


SECURITY_STATUS SEC_ENTRY DeleteSecurityContext(PCtxtHandle phContext)
{
	char* Name = NULL;
	SECURITY_STATUS status;
	SecurityFunctionTableA* table;

	Name = (char*) sspi_SecureHandleGetUpperPointer(phContext);

	if (!Name)
		return SEC_E_SECPKG_NOT_FOUND;

	table = sspi_GetSecurityFunctionTableAByNameA(Name);

	if (!table)
		return SEC_E_SECPKG_NOT_FOUND;

	if (table->DeleteSecurityContext == NULL)
		return SEC_E_UNSUPPORTED_FUNCTION;

	status = table->DeleteSecurityContext(phContext);

	return status;
}


static void ppc_prep_init ( QEMUMachineInitArgs * args ) {
 ram_addr_t ram_size = args -> ram_size ;
 const char * cpu_model = args -> cpu_model ;
 const char * kernel_filename = args -> kernel_filename ;
 const char * kernel_cmdline = args -> kernel_cmdline ;
 const char * initrd_filename = args -> initrd_filename ;
 const char * boot_device = args -> boot_device ;
 MemoryRegion * sysmem = get_system_memory ( ) ;
 PowerPCCPU * cpu = NULL ;
 CPUPPCState * env = NULL ;
 char * filename ;
 nvram_t nvram ;
 M48t59State * m48t59 ;
 MemoryRegion * PPC_io_memory = g_new ( MemoryRegion , 1 ) ;
 PortioList * port_list = g_new ( PortioList , 1 ) ;
 # if 0 MemoryRegion * xcsr = g_new ( MemoryRegion , 1 ) ;
 # endif int linux_boot , i , nb_nics1 , bios_size ;
 MemoryRegion * ram = g_new ( MemoryRegion , 1 ) ;
 MemoryRegion * bios = g_new ( MemoryRegion , 1 ) ;
 uint32_t kernel_base , initrd_base ;
 long kernel_size , initrd_size ;
 DeviceState * dev ;
 PCIHostState * pcihost ;
 PCIBus * pci_bus ;
 PCIDevice * pci ;
 ISABus * isa_bus ;
 ISADevice * isa ;
 qemu_irq * cpu_exit_irq ;
 int ppc_boot_device ;
 DriveInfo * hd [ MAX_IDE_BUS * MAX_IDE_DEVS ] ;
 sysctrl = g_malloc0 ( sizeof ( sysctrl_t ) ) ;
 linux_boot = ( kernel_filename != NULL ) ;
 if ( cpu_model == NULL ) cpu_model = "602" ;
 for ( i = 0 ;
 i < smp_cpus ;
 i ++ ) {
 cpu = cpu_ppc_init ( cpu_model ) ;
 if ( cpu == NULL ) {
 fprintf ( stderr , "Unable to find PowerPC CPU definition\n" ) ;
 exit ( 1 ) ;
 }
 env = & cpu -> env ;
 if ( env -> flags & POWERPC_FLAG_RTC_CLK ) {
 cpu_ppc_tb_init ( env , 7812500UL ) ;
 }
 else {
 cpu_ppc_tb_init ( env , 100UL * 1000UL * 1000UL ) ;
 }
 qemu_register_reset ( ppc_prep_reset , cpu ) ;
 }
 memory_region_init_ram ( ram , NULL , "ppc_prep.ram" , ram_size ) ;
 vmstate_register_ram_global ( ram ) ;
 memory_region_add_subregion ( sysmem , 0 , ram ) ;
 memory_region_init_ram ( bios , NULL , "ppc_prep.bios" , BIOS_SIZE ) ;
 memory_region_set_readonly ( bios , true ) ;
 memory_region_add_subregion ( sysmem , ( uint32_t ) ( - BIOS_SIZE ) , bios ) ;
 vmstate_register_ram_global ( bios ) ;
 if ( bios_name == NULL ) bios_name = BIOS_FILENAME ;
 filename = qemu_find_file ( QEMU_FILE_TYPE_BIOS , bios_name ) ;
 if ( filename ) {
 bios_size = load_elf ( filename , NULL , NULL , NULL , NULL , NULL , 1 , ELF_MACHINE , 0 ) ;
 if ( bios_size < 0 ) {
 bios_size = get_image_size ( filename ) ;
 if ( bios_size > 0 && bios_size <= BIOS_SIZE ) {
 hwaddr bios_addr ;
 bios_size = ( bios_size + 0xfff ) & ~ 0xfff ;
 bios_addr = ( uint32_t ) ( - bios_size ) ;
 bios_size = load_image_targphys ( filename , bios_addr , bios_size ) ;
 }
 if ( bios_size > BIOS_SIZE ) {
 fprintf ( stderr , "qemu: PReP bios '%s' is too large (0x%x)\n" , bios_name , bios_size ) ;
 exit ( 1 ) ;
 }
 }
 }
 else {
 bios_size = - 1 ;
 }
 if ( bios_size < 0 && ! qtest_enabled ( ) ) {
 fprintf ( stderr , "qemu: could not load PPC PReP bios '%s'\n" , bios_name ) ;
 exit ( 1 ) ;
 }
 if ( filename ) {
 g_free ( filename ) ;
 }
 if ( linux_boot ) {
 kernel_base = KERNEL_LOAD_ADDR ;
 kernel_size = load_image_targphys ( kernel_filename , kernel_base , ram_size - kernel_base ) ;
 if ( kernel_size < 0 ) {
 hw_error ( "qemu: could not load kernel '%s'\n" , kernel_filename ) ;
 exit ( 1 ) ;
 }
 if ( initrd_filename ) {
 initrd_base = INITRD_LOAD_ADDR ;
 initrd_size = load_image_targphys ( initrd_filename , initrd_base , ram_size - initrd_base ) ;
 if ( initrd_size < 0 ) {
 hw_error ( "qemu: could not load initial ram disk '%s'\n" , initrd_filename ) ;
 }
 }
 else {
 initrd_base = 0 ;
 initrd_size = 0 ;
 }
 ppc_boot_device = 'm' ;
 }
 else {
 kernel_base = 0 ;
 kernel_size = 0 ;
 initrd_base = 0 ;
 initrd_size = 0 ;
 ppc_boot_device = '\0' ;
 for ( i = 0 ;
 boot_device [ i ] != '\0' ;
 i ++ ) {
 if ( boot_device [ i ] >= 'a' && boot_device [ i ] <= 'f' ) {
 ppc_boot_device = boot_device [ i ] ;
 break ;
 }
 }
 if ( ppc_boot_device == '\0' ) {
 fprintf ( stderr , "No valid boot device for Mac99 machine\n" ) ;
 exit ( 1 ) ;
 }
 }
 if ( PPC_INPUT ( env ) != PPC_FLAGS_INPUT_6xx ) {
 hw_error ( "Only 6xx bus is supported on PREP machine\n" ) ;
 }
 dev = qdev_create ( NULL , "raven-pcihost" ) ;
 pcihost = PCI_HOST_BRIDGE ( dev ) ;
 object_property_add_child ( qdev_get_machine ( ) , "raven" , OBJECT ( dev ) , NULL ) ;
 qdev_init_nofail ( dev ) ;
 pci_bus = ( PCIBus * ) qdev_get_child_bus ( dev , "pci.0" ) ;
 if ( pci_bus == NULL ) {
 fprintf ( stderr , "Couldn't create PCI host controller.\n" ) ;
 exit ( 1 ) ;
 }
 pci = pci_create_simple ( pci_bus , PCI_DEVFN ( 1 , 0 ) , "i82378" ) ;
 cpu_exit_irq = qemu_allocate_irqs ( cpu_request_exit , NULL , 1 ) ;
 qdev_connect_gpio_out ( & pci -> qdev , 0 , first_cpu -> irq_inputs [ PPC6xx_INPUT_INT ] ) ;
 qdev_connect_gpio_out ( & pci -> qdev , 1 , * cpu_exit_irq ) ;
 sysbus_connect_irq ( & pcihost -> busdev , 0 , qdev_get_gpio_in ( & pci -> qdev , 9 ) ) ;
 sysbus_connect_irq ( & pcihost -> busdev , 1 , qdev_get_gpio_in ( & pci -> qdev , 11 ) ) ;
 sysbus_connect_irq ( & pcihost -> busdev , 2 , qdev_get_gpio_in ( & pci -> qdev , 9 ) ) ;
 sysbus_connect_irq ( & pcihost -> busdev , 3 , qdev_get_gpio_in ( & pci -> qdev , 11 ) ) ;
 isa_bus = ISA_BUS ( qdev_get_child_bus ( DEVICE ( pci ) , "isa.0" ) ) ;
 isa = isa_create ( isa_bus , TYPE_PC87312 ) ;
 dev = DEVICE ( isa ) ;
 qdev_prop_set_uint8 ( dev , "config" , 13 ) ;
 qdev_init_nofail ( dev ) ;
 memory_region_init_io ( PPC_io_memory , NULL , & PPC_prep_io_ops , sysctrl , "ppc-io" , 0x00800000 ) ;
 memory_region_add_subregion ( sysmem , 0x80000000 , PPC_io_memory ) ;
 pci_vga_init ( pci_bus ) ;
 nb_nics1 = nb_nics ;
 if ( nb_nics1 > NE2000_NB_MAX ) nb_nics1 = NE2000_NB_MAX ;
 for ( i = 0 ;
 i < nb_nics1 ;
 i ++ ) {
 if ( nd_table [ i ] . model == NULL ) {
 nd_table [ i ] . model = g_strdup ( "ne2k_isa" ) ;
 }
 if ( strcmp ( nd_table [ i ] . model , "ne2k_isa" ) == 0 ) {
 isa_ne2000_init ( isa_bus , ne2000_io [ i ] , ne2000_irq [ i ] , & nd_table [ i ] ) ;
 }
 else {
 pci_nic_init_nofail ( & nd_table [ i ] , pci_bus , "ne2k_pci" , NULL ) ;
 }
 }
 ide_drive_get ( hd , MAX_IDE_BUS ) ;
 for ( i = 0 ;
 i < MAX_IDE_BUS ;
 i ++ ) {
 isa_ide_init ( isa_bus , ide_iobase [ i ] , ide_iobase2 [ i ] , ide_irq [ i ] , hd [ 2 * i ] , hd [ 2 * i + 1 ] ) ;
 }
 isa_create_simple ( isa_bus , "i8042" ) ;
 sysctrl -> reset_irq = first_cpu -> irq_inputs [ PPC6xx_INPUT_HRESET ] ;
 portio_list_init ( port_list , NULL , prep_portio_list , sysctrl , "prep" ) ;
 portio_list_add ( port_list , get_system_io ( ) , 0x0 ) ;
 # if 0 memory_region_init_io ( xcsr , NULL , & PPC_XCSR_ops , NULL , "ppc-xcsr" , 0x1000 ) ;
 memory_region_add_subregion ( sysmem , 0xFEFF0000 , xcsr ) ;
 # endif if ( usb_enabled ( false ) ) {
 pci_create_simple ( pci_bus , - 1 , "pci-ohci" ) ;
 }
 m48t59 = m48t59_init_isa ( isa_bus , 0x0074 , NVRAM_SIZE , 59 ) ;
 if ( m48t59 == NULL ) return ;
 sysctrl -> nvram = m48t59 ;
 nvram . opaque = m48t59 ;
 nvram . read_fn = & m48t59_read ;
 nvram . write_fn = & m48t59_write ;
 PPC_NVRAM_set_params ( & nvram , NVRAM_SIZE , "PREP" , ram_size , ppc_boot_device , kernel_base , kernel_size , kernel_cmdline , initrd_base , initrd_size , 0 , graphic_width , graphic_height , graphic_depth ) ;
 }


void MPV_common_init_armv4l(MpegEncContext *s) { int i; const int idct_algo= s->avctx->idct_algo; ff_put_pixels_clamped = s->avctx->dsp.put_pixels_clamped; ff_add_pixels_clamped = s->avctx->dsp.put_pixels_clamped; if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_ARM){ s->idct_put= arm_idct_put; s->idct_add= arm_idct_add; s->idct_permutation_type= FF_NO_IDCT_PERM; } }


int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
	skb_orphan(skb);

	if (!(dev->flags & IFF_UP))
		return NET_RX_DROP;

	if (skb->len > (dev->mtu + dev->hard_header_len))
		return NET_RX_DROP;

	skb_set_dev(skb, dev);
	skb->tstamp.tv64 = 0;
	skb->pkt_type = PACKET_HOST;
	skb->protocol = eth_type_trans(skb, dev);
	return netif_rx(skb);
}


BlockJobInfoList *qmp_query_block_jobs(Error **errp) { BlockJobInfoList *head = NULL, **p_next = &head; BlockDriverState *bs; BdrvNextIterator *it = NULL; while ((it = bdrv_next(it, &bs))) { AioContext *aio_context = bdrv_get_aio_context(bs); aio_context_acquire(aio_context); if (bs->job) { BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1); elem->value = block_job_query(bs->job); *p_next = elem; p_next = &elem->next; } aio_context_release(aio_context); } return head; }


IN_PROC_BROWSER_TEST_F ( ExtensionMessageBubbleViewBrowserTest , TestClickingDismissButton ) {
 TestClickingDismissButton ( ) ;
 }


if_start(void) { struct mbuf *ifm, *ifqt; DEBUG_CALL("if_start"); if (if_queued == 0) return; /* Nothing to do */ again: /* check if we can really output */ if (!slirp_can_output()) return; /* * See which queue to get next packet from * If there's something in the fastq, select it immediately */ if (if_fastq.ifq_next != &if_fastq) { ifm = if_fastq.ifq_next; } else { /* Nothing on fastq, see if next_m is valid */ if (next_m != &if_batchq) ifm = next_m; else ifm = if_batchq.ifq_next; /* Set which packet to send on next iteration */ next_m = ifm->ifq_next; } /* Remove it from the queue */ ifqt = ifm->ifq_prev; remque(ifm); --if_queued; /* If there are more packets for this session, re-queue them */ if (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) { insque(ifm->ifs_next, ifqt); ifs_remque(ifm); } /* Update so_queued */ if (ifm->ifq_so) { if (--ifm->ifq_so->so_queued == 0) /* If there's no more queued, reset nqueued */ ifm->ifq_so->so_nqueued = 0; } /* Encapsulate the packet for sending */ if_encap(ifm->m_data, ifm->m_len); if (if_queued) goto again; }


static inline void take_option ( char * * to , char * from , int * first , int len ) {
 if ( ! * first ) {
 * * to = ',' ;
 * to += 1 ;
 }
 else * first = 0 ;
 memcpy ( * to , from , len ) ;
 * to += len ;
 }


static void arm_gic_common_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->reset = arm_gic_common_reset; dc->realize = arm_gic_common_realize; dc->props = arm_gic_common_properties; dc->vmsd = &vmstate_gic; dc->no_user = 1; }


static void cirrus_init_common ( CirrusVGAState * s , Object * owner , int device_id , int is_pci , MemoryRegion * system_memory , MemoryRegion * system_io ) {
 int i ;
 static int inited ;
 if ( ! inited ) {
 inited = 1 ;
 for ( i = 0 ;
 i < 256 ;
 i ++ ) rop_to_index [ i ] = CIRRUS_ROP_NOP_INDEX ;
 rop_to_index [ CIRRUS_ROP_0 ] = 0 ;
 rop_to_index [ CIRRUS_ROP_SRC_AND_DST ] = 1 ;
 rop_to_index [ CIRRUS_ROP_NOP ] = 2 ;
 rop_to_index [ CIRRUS_ROP_SRC_AND_NOTDST ] = 3 ;
 rop_to_index [ CIRRUS_ROP_NOTDST ] = 4 ;
 rop_to_index [ CIRRUS_ROP_SRC ] = 5 ;
 rop_to_index [ CIRRUS_ROP_1 ] = 6 ;
 rop_to_index [ CIRRUS_ROP_NOTSRC_AND_DST ] = 7 ;
 rop_to_index [ CIRRUS_ROP_SRC_XOR_DST ] = 8 ;
 rop_to_index [ CIRRUS_ROP_SRC_OR_DST ] = 9 ;
 rop_to_index [ CIRRUS_ROP_NOTSRC_OR_NOTDST ] = 10 ;
 rop_to_index [ CIRRUS_ROP_SRC_NOTXOR_DST ] = 11 ;
 rop_to_index [ CIRRUS_ROP_SRC_OR_NOTDST ] = 12 ;
 rop_to_index [ CIRRUS_ROP_NOTSRC ] = 13 ;
 rop_to_index [ CIRRUS_ROP_NOTSRC_OR_DST ] = 14 ;
 rop_to_index [ CIRRUS_ROP_NOTSRC_AND_NOTDST ] = 15 ;
 s -> device_id = device_id ;
 if ( is_pci ) s -> bustype = CIRRUS_BUSTYPE_PCI ;
 else s -> bustype = CIRRUS_BUSTYPE_ISA ;
 }
 memory_region_init_io ( & s -> cirrus_vga_io , owner , & cirrus_vga_io_ops , s , "cirrus-io" , 0x30 ) ;
 memory_region_set_flush_coalesced ( & s -> cirrus_vga_io ) ;
 memory_region_add_subregion ( system_io , 0x3b0 , & s -> cirrus_vga_io ) ;
 memory_region_init ( & s -> low_mem_container , owner , "cirrus-lowmem-container" , 0x20000 ) ;
 memory_region_init_io ( & s -> low_mem , owner , & cirrus_vga_mem_ops , s , "cirrus-low-memory" , 0x20000 ) ;
 memory_region_add_subregion ( & s -> low_mem_container , 0 , & s -> low_mem ) ;
 for ( i = 0 ;
 i < 2 ;
 ++ i ) {
 static const char * names [ ] = {
 "vga.bank0" , "vga.bank1" }
 ;
 MemoryRegion * bank = & s -> cirrus_bank [ i ] ;
 memory_region_init_alias ( bank , owner , names [ i ] , & s -> vga . vram , 0 , 0x8000 ) ;
 memory_region_set_enabled ( bank , false ) ;
 memory_region_add_subregion_overlap ( & s -> low_mem_container , i * 0x8000 , bank , 1 ) ;
 }
 memory_region_add_subregion_overlap ( system_memory , 0x000a0000 , & s -> low_mem_container , 1 ) ;
 memory_region_set_coalescing ( & s -> low_mem ) ;
 memory_region_init_io ( & s -> cirrus_linear_io , owner , & cirrus_linear_io_ops , s , "cirrus-linear-io" , s -> vga . vram_size_mb * 1024 * 1024 ) ;
 memory_region_set_flush_coalesced ( & s -> cirrus_linear_io ) ;
 memory_region_init_io ( & s -> cirrus_linear_bitblt_io , owner , & cirrus_linear_bitblt_io_ops , s , "cirrus-bitblt-mmio" , 0x400000 ) ;
 memory_region_set_flush_coalesced ( & s -> cirrus_linear_bitblt_io ) ;
 memory_region_init_io ( & s -> cirrus_mmio_io , owner , & cirrus_mmio_io_ops , s , "cirrus-mmio" , CIRRUS_PNPMMIO_SIZE ) ;
 memory_region_set_flush_coalesced ( & s -> cirrus_mmio_io ) ;
 s -> real_vram_size = ( s -> device_id == CIRRUS_ID_CLGD5446 ) ? 4096 * 1024 : 2048 * 1024 ;
 s -> cirrus_addr_mask = s -> real_vram_size - 1 ;
 s -> linear_mmio_mask = s -> real_vram_size - 256 ;
 s -> vga . get_bpp = cirrus_get_bpp ;
 s -> vga . get_offsets = cirrus_get_offsets ;
 s -> vga . get_resolution = cirrus_get_resolution ;
 s -> vga . cursor_invalidate = cirrus_cursor_invalidate ;
 s -> vga . cursor_draw_line = cirrus_cursor_draw_line ;
 qemu_register_reset ( cirrus_reset , s ) ;
 }


int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index)
{
	struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
	int i, err = 0;
	int free = -1;

	mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac);
	mutex_lock(&table->mutex);
	for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) {
		if (free < 0 && !table->refs[i]) {
			free = i;
			continue;
		}

		if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) {
			/* MAC already registered, increase refernce count */
			*index = i;
			++table->refs[i];
			goto out;
		}
	}

	if (free < 0) {
		err = -ENOMEM;
		goto out;
	}

	mlx4_dbg(dev, "Free MAC index is %d\n", free);

	if (table->total == table->max) {
		/* No free mac entries */
		err = -ENOSPC;
		goto out;
	}

	/* Register new MAC */
	table->refs[free] = 1;
	table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID);

	err = mlx4_set_port_mac_table(dev, port, table->entries);
	if (unlikely(err)) {
		mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac);
		table->refs[free] = 0;
		table->entries[free] = 0;
		goto out;
	}

	*index = free;
	++table->total;
out:
	mutex_unlock(&table->mutex);
	return err;
}


static void reschedule_dma(void *opaque) { DMAAIOCB *dbs = (DMAAIOCB *)opaque; qemu_bh_delete(dbs->bh); dbs->bh = NULL; dma_bdrv_cb(opaque, 0); }


void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
{
    if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
        return;  // server buffer

    QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg);
#ifdef HAVE_QCA2
    putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName()));
#else
    putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg);
#endif
    emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
}


static int mkv_check_tag(AVDictionary *m) { AVDictionaryEntry *t = NULL; while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) if (av_strcasecmp(t->key, "title") && av_strcasecmp(t->key, "stereo_mode")) return 1; return 0; }


static int encode_mode(CinepakEncContext *s, CinepakMode mode, int h, int v1_size, int v4_size, int v4, AVPicture *scratch_pict, strip_info *info, unsigned char *buf) { int x, y, z, flags, bits, temp_size, header_ofs, ret = 0, mb_count = s->w * h / MB_AREA; int needs_extra_bit, should_write_temp; unsigned char temp[64]; //32/2 = 16 V4 blocks at 4 B each -> 64 B mb_info *mb; AVPicture sub_scratch; //encode codebooks if(v1_size) ret += encode_codebook(s, info->v1_codebook, v1_size, 0x22, 0x26, buf + ret); if(v4_size) ret += encode_codebook(s, info->v4_codebook, v4_size, 0x20, 0x24, buf + ret); //update scratch picture for(z = y = 0; y < h; y += MB_SIZE) { for(x = 0; x < s->w; x += MB_SIZE, z++) { mb = &s->mb[z]; if(mode == MODE_MC && mb->best_encoding == ENC_SKIP) continue; get_sub_picture(s, x, y, scratch_pict, &sub_scratch); if(mode == MODE_V1_ONLY || mb->best_encoding == ENC_V1) decode_v1_vector(s, &sub_scratch, mb, info); else if(mode != MODE_V1_ONLY && mb->best_encoding == ENC_V4) decode_v4_vector(s, &sub_scratch, mb->v4_vector[v4], info); } } switch(mode) { case MODE_V1_ONLY: //av_log(s->avctx, AV_LOG_INFO, "mb_count = %i\n", mb_count); ret += write_chunk_header(buf + ret, 0x32, mb_count); for(x = 0; x < mb_count; x++) buf[ret++] = s->mb[x].v1_vector; break; case MODE_V1_V4: //remember header position header_ofs = ret; ret += CHUNK_HEADER_SIZE; for(x = 0; x < mb_count; x += 32) { flags = 0; for(y = x; y < FFMIN(x+32, mb_count); y++) if(s->mb[y].best_encoding == ENC_V4) flags |= 1 << (31 - y + x); AV_WB32(&buf[ret], flags); ret += 4; for(y = x; y < FFMIN(x+32, mb_count); y++) { mb = &s->mb[y]; if(mb->best_encoding == ENC_V1) buf[ret++] = mb->v1_vector; else for(z = 0; z < 4; z++) buf[ret++] = mb->v4_vector[v4][z]; } } write_chunk_header(buf + header_ofs, 0x30, ret - header_ofs - CHUNK_HEADER_SIZE); break; case MODE_MC: //remember header position header_ofs = ret; ret += CHUNK_HEADER_SIZE; flags = bits = temp_size = 0; for(x = 0; x < mb_count; x++) { mb = &s->mb[x]; flags |= (mb->best_encoding != ENC_SKIP) << (31 - bits++); needs_extra_bit = 0; should_write_temp = 0; if(mb->best_encoding != ENC_SKIP) { if(bits < 32) flags |= (mb->best_encoding == ENC_V4) << (31 - bits++); else needs_extra_bit = 1; } if(bits == 32) { AV_WB32(&buf[ret], flags); ret += 4; flags = bits = 0; if(mb->best_encoding == ENC_SKIP || needs_extra_bit) { memcpy(&buf[ret], temp, temp_size); ret += temp_size; temp_size = 0; } else should_write_temp = 1; } if(needs_extra_bit) { flags = (mb->best_encoding == ENC_V4) << 31; bits = 1; } if(mb->best_encoding == ENC_V1) temp[temp_size++] = mb->v1_vector; else if(mb->best_encoding == ENC_V4) for(z = 0; z < 4; z++) temp[temp_size++] = mb->v4_vector[v4][z]; if(should_write_temp) { memcpy(&buf[ret], temp, temp_size); ret += temp_size; temp_size = 0; } } if(bits > 0) { AV_WB32(&buf[ret], flags); ret += 4; memcpy(&buf[ret], temp, temp_size); ret += temp_size; } write_chunk_header(buf + header_ofs, 0x31, ret - header_ofs - CHUNK_HEADER_SIZE); break; } return ret; }


inline void update_rq_clock(struct rq *rq)
{
	if (!rq->skip_clock_update) {
		int cpu = cpu_of(rq);
		u64 irq_time;

		rq->clock = sched_clock_cpu(cpu);
		irq_time = irq_time_cpu(cpu);
		if (rq->clock - irq_time > rq->clock_task)
			rq->clock_task = rq->clock - irq_time;

		sched_irq_time_avg_update(rq, irq_time);
	}
}


static void _UTF16LEToUnicodeWithOffsets ( UConverterToUnicodeArgs * pArgs , UErrorCode * pErrorCode ) {
 UConverter * cnv ;
 const uint8_t * source ;
 UChar * target ;
 int32_t * offsets ;
 uint32_t targetCapacity , length , count , sourceIndex ;
 UChar c , trail ;
 if ( pArgs -> converter -> mode < 8 ) {
 _UTF16ToUnicodeWithOffsets ( pArgs , pErrorCode ) ;
 return ;
 }
 cnv = pArgs -> converter ;
 source = ( const uint8_t * ) pArgs -> source ;
 length = ( int32_t ) ( ( const uint8_t * ) pArgs -> sourceLimit - source ) ;
 if ( length <= 0 && cnv -> toUnicodeStatus == 0 ) {
 return ;
 }
 target = pArgs -> target ;
 if ( target >= pArgs -> targetLimit ) {
 * pErrorCode = U_BUFFER_OVERFLOW_ERROR ;
 return ;
 }
 targetCapacity = ( uint32_t ) ( pArgs -> targetLimit - pArgs -> target ) ;
 offsets = pArgs -> offsets ;
 sourceIndex = 0 ;
 c = 0 ;
 if ( cnv -> toUnicodeStatus != 0 ) {
 cnv -> toUBytes [ 0 ] = ( uint8_t ) cnv -> toUnicodeStatus ;
 cnv -> toULength = 1 ;
 cnv -> toUnicodeStatus = 0 ;
 }
 if ( ( count = cnv -> toULength ) != 0 ) {
 uint8_t * p = cnv -> toUBytes ;
 do {
 p [ count ++ ] = * source ++ ;
 ++ sourceIndex ;
 -- length ;
 if ( count == 2 ) {
 c = ( ( UChar ) p [ 1 ] << 8 ) | p [ 0 ] ;
 if ( U16_IS_SINGLE ( c ) ) {
 * target ++ = c ;
 if ( offsets != NULL ) {
 * offsets ++ = - 1 ;
 }
 -- targetCapacity ;
 count = 0 ;
 c = 0 ;
 break ;
 }
 else if ( U16_IS_SURROGATE_LEAD ( c ) ) {
 c = 0 ;
 }
 else {
 break ;
 }
 }
 else if ( count == 4 ) {
 c = ( ( UChar ) p [ 1 ] << 8 ) | p [ 0 ] ;
 trail = ( ( UChar ) p [ 3 ] << 8 ) | p [ 2 ] ;
 if ( U16_IS_TRAIL ( trail ) ) {
 * target ++ = c ;
 if ( targetCapacity >= 2 ) {
 * target ++ = trail ;
 if ( offsets != NULL ) {
 * offsets ++ = - 1 ;
 * offsets ++ = - 1 ;
 }
 targetCapacity -= 2 ;
 }
 else {
 targetCapacity = 0 ;
 cnv -> UCharErrorBuffer [ 0 ] = trail ;
 cnv -> UCharErrorBufferLength = 1 ;
 * pErrorCode = U_BUFFER_OVERFLOW_ERROR ;
 }
 count = 0 ;
 c = 0 ;
 break ;
 }
 else {
 * pErrorCode = U_ILLEGAL_CHAR_FOUND ;
 if ( ( ( const uint8_t * ) pArgs -> source - source ) >= 2 ) {
 source -= 2 ;
 }
 else {
 cnv -> toUnicodeStatus = 0x100 | p [ 2 ] ;
 -- source ;
 }
 cnv -> toULength = 2 ;
 pArgs -> source = ( const char * ) source ;
 pArgs -> target = target ;
 pArgs -> offsets = offsets ;
 return ;
 }
 }
 }
 while ( length > 0 ) ;
 cnv -> toULength = ( int8_t ) count ;
 }
 count = 2 * targetCapacity ;
 if ( count > length ) {
 count = length & ~ 1 ;
 }
 if ( c == 0 && count > 0 ) {
 length -= count ;
 count >>= 1 ;
 targetCapacity -= count ;
 if ( offsets == NULL ) {
 do {
 c = ( ( UChar ) source [ 1 ] << 8 ) | source [ 0 ] ;
 source += 2 ;
 if ( U16_IS_SINGLE ( c ) ) {
 * target ++ = c ;
 }
 else if ( U16_IS_SURROGATE_LEAD ( c ) && count >= 2 && U16_IS_TRAIL ( trail = ( ( UChar ) source [ 1 ] << 8 ) | source [ 0 ] ) ) {
 source += 2 ;
 -- count ;
 * target ++ = c ;
 * target ++ = trail ;
 }
 else {
 break ;
 }
 }
 while ( -- count > 0 ) ;
 }
 else {
 do {
 c = ( ( UChar ) source [ 1 ] << 8 ) | source [ 0 ] ;
 source += 2 ;
 if ( U16_IS_SINGLE ( c ) ) {
 * target ++ = c ;
 * offsets ++ = sourceIndex ;
 sourceIndex += 2 ;
 }
 else if ( U16_IS_SURROGATE_LEAD ( c ) && count >= 2 && U16_IS_TRAIL ( trail = ( ( UChar ) source [ 1 ] << 8 ) | source [ 0 ] ) ) {
 source += 2 ;
 -- count ;
 * target ++ = c ;
 * target ++ = trail ;
 * offsets ++ = sourceIndex ;
 * offsets ++ = sourceIndex ;
 sourceIndex += 4 ;
 }
 else {
 break ;
 }
 }
 while ( -- count > 0 ) ;
 }
 if ( count == 0 ) {
 c = 0 ;
 }
 else {
 length += 2 * ( count - 1 ) ;
 targetCapacity += count ;
 }
 }
 if ( c != 0 ) {
 cnv -> toUBytes [ 0 ] = ( uint8_t ) c ;
 cnv -> toUBytes [ 1 ] = ( uint8_t ) ( c >> 8 ) ;
 cnv -> toULength = 2 ;
 if ( U16_IS_SURROGATE_LEAD ( c ) ) {
 if ( length >= 2 ) {
 if ( U16_IS_TRAIL ( trail = ( ( UChar ) source [ 1 ] << 8 ) | source [ 0 ] ) ) {
 source += 2 ;
 length -= 2 ;
 * target ++ = c ;
 if ( offsets != NULL ) {
 * offsets ++ = sourceIndex ;
 }
 cnv -> UCharErrorBuffer [ 0 ] = trail ;
 cnv -> UCharErrorBufferLength = 1 ;
 cnv -> toULength = 0 ;
 * pErrorCode = U_BUFFER_OVERFLOW_ERROR ;
 }
 else {
 * pErrorCode = U_ILLEGAL_CHAR_FOUND ;
 }
 }
 else {
 }
 }
 else {
 * pErrorCode = U_ILLEGAL_CHAR_FOUND ;
 }
 }
 if ( U_SUCCESS ( * pErrorCode ) ) {
 if ( length > 0 ) {
 if ( targetCapacity == 0 ) {
 * pErrorCode = U_BUFFER_OVERFLOW_ERROR ;
 }
 else {
 cnv -> toUBytes [ cnv -> toULength ++ ] = * source ++ ;
 }
 }
 }
 pArgs -> source = ( const char * ) source ;
 pArgs -> target = target ;
 pArgs -> offsets = offsets ;
 }


ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry,
				 struct ecryptfs_crypt_stat *crypt_stat,
				 char *page_virt, size_t size)
{
	int rc;

	rc = ecryptfs_setxattr(ecryptfs_dentry, ECRYPTFS_XATTR_NAME, page_virt,
			       size, 0);
	return rc;
}


static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
	int r = EMULATE_DONE;

	++vcpu->stat.insn_emulation_fail;
	trace_kvm_emulate_insn_failed(vcpu);
	if (!is_guest_mode(vcpu)) {
		vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
		vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
		vcpu->run->internal.ndata = 0;
		r = EMULATE_FAIL;
	}
	kvm_queue_exception(vcpu, UD_VECTOR);

	return r;
}


void monitor_flush(Monitor *mon) { int i; if (term_outbuf_index > 0) { for (i = 0; i < MAX_MON; i++) if (monitor_hd[i] && monitor_hd[i]->focus == 0) qemu_chr_write(monitor_hd[i], term_outbuf, term_outbuf_index); term_outbuf_index = 0; } }


static void nvdimm_dsm_func_read_fit(AcpiNVDIMMState *state, NvdimmDsmIn *in, hwaddr dsm_mem_addr) { NvdimmFitBuffer *fit_buf = &state->fit_buf; NvdimmFuncReadFITIn *read_fit; NvdimmFuncReadFITOut *read_fit_out; GArray *fit; uint32_t read_len = 0, func_ret_status; int size; read_fit = (NvdimmFuncReadFITIn *)in->arg3; le32_to_cpus(&read_fit->offset); qemu_mutex_lock(&fit_buf->lock); fit = fit_buf->fit; nvdimm_debug("Read FIT: offset %#x FIT size %#x Dirty %s.\n", read_fit->offset, fit->len, fit_buf->dirty ? "Yes" : "No"); if (read_fit->offset > fit->len) { func_ret_status = 3 /* Invalid Input Parameters */; goto exit; } /* It is the first time to read FIT. */ if (!read_fit->offset) { fit_buf->dirty = false; } else if (fit_buf->dirty) { /* FIT has been changed during RFIT. */ func_ret_status = 0x100 /* fit changed */; goto exit; } func_ret_status = 0 /* Success */; read_len = MIN(fit->len - read_fit->offset, 4096 - sizeof(NvdimmFuncReadFITOut)); exit: size = sizeof(NvdimmFuncReadFITOut) + read_len; read_fit_out = g_malloc(size); read_fit_out->len = cpu_to_le32(size); read_fit_out->func_ret_status = cpu_to_le32(func_ret_status); memcpy(read_fit_out->fit, fit->data + read_fit->offset, read_len); cpu_physical_memory_write(dsm_mem_addr, read_fit_out, size); g_free(read_fit_out); qemu_mutex_unlock(&fit_buf->lock); }


static krb5_error_code build_principal_va ( krb5_context context , krb5_principal princ , unsigned int rlen , const char * realm , va_list ap ) {
 krb5_error_code retval = 0 ;
 char * r = NULL ;
 krb5_data * data = NULL ;
 krb5_int32 count = 0 ;
 krb5_int32 size = 2 ;
 char * component = NULL ;
 data = malloc ( size * sizeof ( krb5_data ) ) ;
 if ( ! data ) {
 retval = ENOMEM ;
 }
 if ( ! retval ) {
 r = strdup ( realm ) ;
 if ( ! r ) {
 retval = ENOMEM ;
 }
 }
 while ( ! retval && ( component = va_arg ( ap , char * ) ) ) {
 if ( count == size ) {
 krb5_data * new_data = NULL ;
 size *= 2 ;
 new_data = realloc ( data , size * sizeof ( krb5_data ) ) ;
 if ( new_data ) {
 data = new_data ;
 }
 else {
 retval = ENOMEM ;
 }
 }
 if ( ! retval ) {
 data [ count ] . length = strlen ( component ) ;
 data [ count ] . data = strdup ( component ) ;
 if ( ! data [ count ] . data ) {
 retval = ENOMEM ;
 }
 count ++ ;
 }
 }
 if ( ! retval ) {
 princ -> type = KRB5_NT_UNKNOWN ;
 princ -> magic = KV5M_PRINCIPAL ;
 princ -> realm = make_data ( r , rlen ) ;
 princ -> data = data ;
 princ -> length = count ;
 r = NULL ;
 data = NULL ;
 }
 if ( data ) {
 while ( -- count >= 0 ) {
 free ( data [ count ] . data ) ;
 }
 free ( data ) ;
 }
 free ( r ) ;
 return retval ;
 }


struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor)
{
	struct udev_device *udev_device;
	struct msghdr smsg;
	struct iovec iov;
	char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
	char buf[4096];
	size_t bufpos;
	int devpath_set = 0;
	int subsystem_set = 0;
	int action_set = 0;
	int maj = 0;
	int min = 0;

	if (udev_monitor == NULL)
		return NULL;
	memset(buf, 0x00, sizeof(buf));
	iov.iov_base = &buf;
	iov.iov_len = sizeof(buf);
	memset (&smsg, 0x00, sizeof(struct msghdr));
	smsg.msg_iov = &iov;
	smsg.msg_iovlen = 1;
	smsg.msg_control = cred_msg;
	smsg.msg_controllen = sizeof(cred_msg);

	if (recvmsg(udev_monitor->sock, &smsg, 0) < 0) {
		if (errno != EINTR)
			info(udev_monitor->udev, "unable to receive message");
		return NULL;
	}

	if (udev_monitor->sun.sun_family != 0) {
		struct cmsghdr *cmsg = CMSG_FIRSTHDR(&smsg);
		struct ucred *cred = (struct ucred *)CMSG_DATA (cmsg);

		if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
			info(udev_monitor->udev, "no sender credentials received, message ignored");
			return NULL;
		}

		if (cred->uid != 0) {
			info(udev_monitor->udev, "sender uid=%d, message ignored", cred->uid);
			return NULL;
		}
	}

	/* skip header */
	bufpos = strlen(buf) + 1;
	if (bufpos < sizeof("a@/d") || bufpos >= sizeof(buf)) {
		info(udev_monitor->udev, "invalid message length");
		return NULL;
	}

	/* check message header */
	if (strstr(buf, "@/") == NULL) {
		info(udev_monitor->udev, "unrecognized message header");
		return NULL;
	}

	udev_device = device_new(udev_monitor->udev);
	if (udev_device == NULL) {
		return NULL;
	}

	while (bufpos < sizeof(buf)) {
		char *key;
		size_t keylen;

		key = &buf[bufpos];
		keylen = strlen(key);
		if (keylen == 0)
			break;
		bufpos += keylen + 1;

		if (strncmp(key, "DEVPATH=", 8) == 0) {
			char path[UTIL_PATH_SIZE];

			util_strlcpy(path, udev_get_sys_path(udev_monitor->udev), sizeof(path));
			util_strlcat(path, &key[8], sizeof(path));
			udev_device_set_syspath(udev_device, path);
			devpath_set = 1;
		} else if (strncmp(key, "SUBSYSTEM=", 10) == 0) {
			udev_device_set_subsystem(udev_device, &key[10]);
			subsystem_set = 1;
		} else if (strncmp(key, "DEVTYPE=", 8) == 0) {
			udev_device_set_devtype(udev_device, &key[8]);
		} else if (strncmp(key, "DEVNAME=", 8) == 0) {
			udev_device_set_devnode(udev_device, &key[8]);
		} else if (strncmp(key, "DEVLINKS=", 9) == 0) {
			char devlinks[UTIL_PATH_SIZE];
			char *slink;
			char *next;

			util_strlcpy(devlinks, &key[9], sizeof(devlinks));
			slink = devlinks;
			next = strchr(slink, ' ');
			while (next != NULL) {
				next[0] = '\0';
				udev_device_add_devlink(udev_device, slink);
				slink = &next[1];
				next = strchr(slink, ' ');
			}
			if (slink[0] != '\0')
				udev_device_add_devlink(udev_device, slink);
		} else if (strncmp(key, "DRIVER=", 7) == 0) {
			udev_device_set_driver(udev_device, &key[7]);
		} else if (strncmp(key, "ACTION=", 7) == 0) {
			udev_device_set_action(udev_device, &key[7]);
			action_set = 1;
		} else if (strncmp(key, "MAJOR=", 6) == 0) {
			maj = strtoull(&key[6], NULL, 10);
		} else if (strncmp(key, "MINOR=", 6) == 0) {
			min = strtoull(&key[6], NULL, 10);
		} else if (strncmp(key, "DEVPATH_OLD=", 12) == 0) {
			udev_device_set_devpath_old(udev_device, &key[12]);
		} else if (strncmp(key, "PHYSDEVPATH=", 12) == 0) {
			udev_device_set_physdevpath(udev_device, &key[12]);
		} else if (strncmp(key, "SEQNUM=", 7) == 0) {
			udev_device_set_seqnum(udev_device, strtoull(&key[7], NULL, 10));
		} else if (strncmp(key, "TIMEOUT=", 8) == 0) {
			udev_device_set_timeout(udev_device, strtoull(&key[8], NULL, 10));
		} else if (strncmp(key, "PHYSDEV", 7) == 0) {
			/* skip deprecated values */
			continue;
		} else {
			udev_device_add_property_from_string(udev_device, key);
		}
	}
	if (!devpath_set || !subsystem_set || !action_set) {
		info(udev_monitor->udev, "missing values, skip\n");
		udev_device_unref(udev_device);
		return NULL;
	}
	if (maj > 0)
		udev_device_set_devnum(udev_device, makedev(maj, min));
	udev_device_set_info_loaded(udev_device);
	return udev_device;
}


void dev_load(struct net *net, const char *name)
{
	struct net_device *dev;

	rcu_read_lock();
	dev = dev_get_by_name_rcu(net, name);
	rcu_read_unlock();

	if (!dev && capable(CAP_NET_ADMIN))
		request_module("%s", name);
}


int udev_monitor_send_device(struct udev_monitor *udev_monitor, struct udev_device *udev_device)
{
	const char *buf;
	ssize_t len;
	ssize_t count;

	len = udev_device_get_properties_monitor_buf(udev_device, &buf);
	if (len < 32)
		return -1;
	if (udev_monitor->sun.sun_family != 0)
		count = sendto(udev_monitor->sock,
			       buf, len, 0,
			       (struct sockaddr *)&udev_monitor->sun,
			       udev_monitor->addrlen);
	else if (udev_monitor->snl.nl_family != 0)
		/* no destination besides the muticast group, we will always get ECONNREFUSED */
		count = sendto(udev_monitor->sock,
			       buf, len, 0,
			       (struct sockaddr *)&udev_monitor->snl_peer,
			       sizeof(struct sockaddr_nl));
	else
		return -1;

	info(udev_monitor->udev, "passed %zi bytes to monitor %p, \n", count, udev_monitor);
	return count;
}


static void exif_process_APP12(image_info_type *ImageInfo,
                               char *buffer, size_t length) {
  size_t l1, l2=0;
  if ((l1 = php_strnlen(buffer+2, length-2)) > 0) {
    exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company",
                     TAG_NONE, TAG_FMT_STRING, l1, buffer+2);
    if (length > 2+l1+1) {
      l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1);
      exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info",
                       TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1);
    }
  }
}


static void qdev_prop_set(DeviceState *dev, const char *name, void *src, enum PropertyType type) { Property *prop; prop = qdev_prop_find(dev, name); if (!prop) { fprintf(stderr, "%s: property \"%s.%s\" not found\n", __FUNCTION__, object_get_typename(OBJECT(dev)), name); abort(); } if (prop->info->type != type) { fprintf(stderr, "%s: property \"%s.%s\" type mismatch\n", __FUNCTION__, object_get_typename(OBJECT(dev)), name); abort(); } qdev_prop_cpy(dev, prop, src); }


long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
	/* This is only valid for single tasks */
	if (pid <= 0 || tgid <= 0)
		return -EINVAL;

	/* Not even root can pretend to send signals from the kernel.
	   Nor can they impersonate a kill(), which adds source info.  */
	if (info->si_code >= 0)
		return -EPERM;
	info->si_signo = sig;

	return do_send_specific(tgid, pid, sig, info);
}


static int vhost_set_vring_file(struct vhost_dev *dev, VhostUserRequest request, struct vhost_vring_file *file) { int fds[VHOST_MEMORY_MAX_NREGIONS]; size_t fd_num = 0; VhostUserMsg msg = { .request = request, .flags = VHOST_USER_VERSION, .payload.u64 = file->index & VHOST_USER_VRING_IDX_MASK, .size = sizeof(msg.payload.u64), }; if (ioeventfd_enabled() && file->fd > 0) { fds[fd_num++] = file->fd; } else { msg.payload.u64 |= VHOST_USER_VRING_NOFD_MASK; } vhost_user_write(dev, &msg, fds, fd_num); return 0; }


static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern,
                                               const String& replacement,
                                               const String& str,
                                               const String& option,
                                               OnigOptionType options) {
  const char *p;
  php_mb_regex_t *re;
  OnigSyntaxType *syntax;
  OnigRegion *regs = nullptr;
  StringBuffer out_buf;
  int i, err, eval, n;
  OnigUChar *pos;
  OnigUChar *string_lim;
  char pat_buf[2];

  const mbfl_encoding *enc;

  {
    const char *current_enc_name;
    current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype));
    if (current_enc_name == nullptr ||
      (enc = mbfl_name2encoding(current_enc_name)) == nullptr) {
      raise_warning("Unknown error");
      return false;
    }
  }
  eval = 0;
  {
    if (!option.empty()) {
      _php_mb_regex_init_options(option.data(), option.size(),
                                 &options, &syntax, &eval);
    } else {
      options |= MBSTRG(regex_default_options);
      syntax = MBSTRG(regex_default_syntax);
    }
  }

  String spattern;
  if (pattern.isString()) {
    spattern = pattern.toString();
  } else {
    /* FIXME: this code is not multibyte aware! */
    pat_buf[0] = pattern.toByte();
    pat_buf[1] = '\0';
    spattern = String(pat_buf, 1, CopyString);
  }
  /* create regex pattern buffer */
  re = php_mbregex_compile_pattern(spattern, options,
                                   MBSTRG(current_mbctype), syntax);
  if (re == nullptr) {
    return false;
  }

  if (eval) {
    throw_not_supported("ereg_replace", "dynamic coding");
  }

  /* do the actual work */
  err = 0;
  pos = (OnigUChar*)str.data();
  string_lim = (OnigUChar*)(str.data() + str.size());
  regs = onig_region_new();
  while (err >= 0) {
    err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim,
                      pos, (OnigUChar *)string_lim, regs, 0);
    if (err <= -2) {
      OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
      onig_error_code_to_str(err_str, err);
      raise_warning("mbregex search failure: %s", err_str);
      break;
    }
    if (err >= 0) {
#if moriyoshi_0
      if (regs->beg[0] == regs->end[0]) {
        raise_warning("Empty regular expression");
        break;
      }
#endif
      /* copy the part of the string before the match */
      out_buf.append((const char *)pos,
                     (OnigUChar *)(str.data() + regs->beg[0]) - pos);
      /* copy replacement and backrefs */
      i = 0;
      p = replacement.data();
      while (i < replacement.size()) {
        int fwd = (int)php_mb_mbchar_bytes_ex(p, enc);
        n = -1;
        auto const remaining = replacement.size() - i;
        if (remaining >= 2 && fwd == 1 &&
            p[0] == '\\' && p[1] >= '0' && p[1] <= '9') {
          n = p[1] - '0';
        }
        if (n >= 0 && n < regs->num_regs) {
          if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] &&
              regs->end[n] <= str.size()) {
            out_buf.append(str.data() + regs->beg[n],
                           regs->end[n] - regs->beg[n]);
          }
          p += 2;
          i += 2;
        } else if (remaining >= fwd) {
          out_buf.append(p, fwd);
          p += fwd;
          i += fwd;
        } else {
          raise_warning("Replacement ends with unterminated %s: 0x%hhx",
                        enc->name, *p);
          break;
        }
      }
      n = regs->end[0];
      if ((pos - (OnigUChar *)str.data()) < n) {
        pos = (OnigUChar *)(str.data() + n);
      } else {
        if (pos < string_lim) {
          out_buf.append((const char *)pos, 1);
        }
        pos++;
      }
    } else { /* nomatch */
      /* stick that last bit of string on our output */
      if (string_lim - pos > 0) {
        out_buf.append((const char *)pos, string_lim - pos);
      }
    }
    onig_region_free(regs, 0);
  }

  if (regs != nullptr) {
    onig_region_free(regs, 1);
  }

  if (err <= -2) {
    return false;
  }
  return out_buf.detach();
}


static void iadst4 ( const int16_t * input , int16_t * output ) {
 int s0 , s1 , s2 , s3 , s4 , s5 , s6 , s7 ;
 int x0 = input [ 0 ] ;
 int x1 = input [ 1 ] ;
 int x2 = input [ 2 ] ;
 int x3 = input [ 3 ] ;
 if ( ! ( x0 | x1 | x2 | x3 ) ) {
 output [ 0 ] = output [ 1 ] = output [ 2 ] = output [ 3 ] = 0 ;
 return ;
 }
 s0 = sinpi_1_9 * x0 ;
 s1 = sinpi_2_9 * x0 ;
 s2 = sinpi_3_9 * x1 ;
 s3 = sinpi_4_9 * x2 ;
 s4 = sinpi_1_9 * x2 ;
 s5 = sinpi_2_9 * x3 ;
 s6 = sinpi_4_9 * x3 ;
 s7 = x0 - x2 + x3 ;
 x0 = s0 + s3 + s5 ;
 x1 = s1 - s4 - s6 ;
 x2 = sinpi_3_9 * s7 ;
 x3 = s2 ;
 s0 = x0 + x3 ;
 s1 = x1 + x3 ;
 s2 = x2 ;
 s3 = x0 + x1 - x3 ;
 output [ 0 ] = dct_const_round_shift ( s0 ) ;
 output [ 1 ] = dct_const_round_shift ( s1 ) ;
 output [ 2 ] = dct_const_round_shift ( s2 ) ;
 output [ 3 ] = dct_const_round_shift ( s3 ) ;
 }


video_usercopy(struct file *file, unsigned int cmd, unsigned long arg,
		v4l2_kioctl func)
{
	char	sbuf[128];
	void    *mbuf = NULL;
	void	*parg = NULL;
	long	err  = -EINVAL;
	int     is_ext_ctrl;
	size_t  ctrls_size = 0;
	void __user *user_ptr = NULL;

	is_ext_ctrl = (cmd == VIDIOC_S_EXT_CTRLS || cmd == VIDIOC_G_EXT_CTRLS ||
		       cmd == VIDIOC_TRY_EXT_CTRLS);

	/*  Copy arguments into temp kernel buffer  */
	switch (_IOC_DIR(cmd)) {
	case _IOC_NONE:
		parg = NULL;
		break;
	case _IOC_READ:
	case _IOC_WRITE:
	case (_IOC_WRITE | _IOC_READ):
		if (_IOC_SIZE(cmd) <= sizeof(sbuf)) {
			parg = sbuf;
		} else {
			/* too big to allocate from stack */
			mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL);
			if (NULL == mbuf)
				return -ENOMEM;
			parg = mbuf;
		}

		err = -EFAULT;
		if (_IOC_DIR(cmd) & _IOC_WRITE)
			if (copy_from_user(parg, (void __user *)arg, _IOC_SIZE(cmd)))
				goto out;
		break;
	}
	if (is_ext_ctrl) {
		struct v4l2_ext_controls *p = parg;

		/* In case of an error, tell the caller that it wasn't
		   a specific control that caused it. */
		p->error_idx = p->count;
		user_ptr = (void __user *)p->controls;
		if (p->count) {
			ctrls_size = sizeof(struct v4l2_ext_control) * p->count;
			/* Note: v4l2_ext_controls fits in sbuf[] so mbuf is still NULL. */
			mbuf = kmalloc(ctrls_size, GFP_KERNEL);
			err = -ENOMEM;
			if (NULL == mbuf)
				goto out_ext_ctrl;
			err = -EFAULT;
			if (copy_from_user(mbuf, user_ptr, ctrls_size))
				goto out_ext_ctrl;
			p->controls = mbuf;
		}
	}

	/* call driver */
	err = func(file, cmd, parg);
	if (err == -ENOIOCTLCMD)
		err = -EINVAL;
	if (is_ext_ctrl) {
		struct v4l2_ext_controls *p = parg;

		p->controls = (void *)user_ptr;
		if (p->count && err == 0 && copy_to_user(user_ptr, mbuf, ctrls_size))
			err = -EFAULT;
		goto out_ext_ctrl;
	}
	if (err < 0)
		goto out;

out_ext_ctrl:
	/*  Copy results into user buffer  */
	switch (_IOC_DIR(cmd)) {
	case _IOC_READ:
	case (_IOC_WRITE | _IOC_READ):
		if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd)))
			err = -EFAULT;
		break;
	}

out:
	kfree(mbuf);
	return err;
}


static QPCIDevice *get_ahci_device(uint32_t *fingerprint) { QPCIDevice *ahci; uint32_t ahci_fingerprint; QPCIBus *pcibus; pcibus = qpci_init_pc(); /* Find the AHCI PCI device and verify it's the right one. */ ahci = qpci_device_find(pcibus, QPCI_DEVFN(0x1F, 0x02)); g_assert(ahci != NULL); ahci_fingerprint = qpci_config_readl(ahci, PCI_VENDOR_ID); switch (ahci_fingerprint) { case AHCI_INTEL_ICH9: break; default: /* Unknown device. */ g_assert_not_reached(); } if (fingerprint) { *fingerprint = ahci_fingerprint; } return ahci; }


static int nr_getname(struct socket *sock, struct sockaddr *uaddr,
	int *uaddr_len, int peer)
{
	struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr;
	struct sock *sk = sock->sk;
	struct nr_sock *nr = nr_sk(sk);

	lock_sock(sk);
	if (peer != 0) {
		if (sk->sk_state != TCP_ESTABLISHED) {
			release_sock(sk);
			return -ENOTCONN;
		}
		sax->fsa_ax25.sax25_family = AF_NETROM;
		sax->fsa_ax25.sax25_ndigis = 1;
		sax->fsa_ax25.sax25_call   = nr->user_addr;
		sax->fsa_digipeater[0]     = nr->dest_addr;
		*uaddr_len = sizeof(struct full_sockaddr_ax25);
	} else {
		sax->fsa_ax25.sax25_family = AF_NETROM;
		sax->fsa_ax25.sax25_ndigis = 0;
		sax->fsa_ax25.sax25_call   = nr->source_addr;
		*uaddr_len = sizeof(struct sockaddr_ax25);
	}
	release_sock(sk);

	return 0;
}


static int rsvp_dump(struct tcf_proto *tp, unsigned long fh,
		     struct sk_buff *skb, struct tcmsg *t)
{
	struct rsvp_filter *f = (struct rsvp_filter*)fh;
	struct rsvp_session *s;
	unsigned char	 *b = skb->tail;
	struct rtattr *rta;
	struct tc_rsvp_pinfo pinfo;

	if (f == NULL)
		return skb->len;
	s = f->sess;

	t->tcm_handle = f->handle;

	rta = (struct rtattr*)b;
	RTA_PUT(skb, TCA_OPTIONS, 0, NULL);

	RTA_PUT(skb, TCA_RSVP_DST, sizeof(s->dst), &s->dst);
	pinfo.dpi = s->dpi;
	pinfo.spi = f->spi;
	pinfo.protocol = s->protocol;
	pinfo.tunnelid = s->tunnelid;
	pinfo.tunnelhdr = f->tunnelhdr;
	RTA_PUT(skb, TCA_RSVP_PINFO, sizeof(pinfo), &pinfo);
	if (f->res.classid)
		RTA_PUT(skb, TCA_RSVP_CLASSID, 4, &f->res.classid);
	if (((f->handle>>8)&0xFF) != 16)
		RTA_PUT(skb, TCA_RSVP_SRC, sizeof(f->src), f->src);

	if (tcf_exts_dump(skb, &f->exts, &rsvp_ext_map) < 0)
		goto rtattr_failure;

	rta->rta_len = skb->tail - b;

	if (tcf_exts_dump_stats(skb, &f->exts, &rsvp_ext_map) < 0)
		goto rtattr_failure;
	return skb->len;

rtattr_failure:
	skb_trim(skb, b - skb->data);
	return -1;
}


static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac, uint8_t (*layout_map)[3], GetBitContext *gb, int byte_align_ref) { int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc; int sampling_index; int comment_len; int tags; skip_bits(gb, 2); // object_type sampling_index = get_bits(gb, 4); if (m4ac->sampling_index != sampling_index) av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not " "match the sample rate index configured by the container.\n"); num_front = get_bits(gb, 4); num_side = get_bits(gb, 4); num_back = get_bits(gb, 4); num_lfe = get_bits(gb, 2); num_assoc_data = get_bits(gb, 3); num_cc = get_bits(gb, 4); if (get_bits1(gb)) skip_bits(gb, 4); // mono_mixdown_tag if (get_bits1(gb)) skip_bits(gb, 4); // stereo_mixdown_tag if (get_bits1(gb)) skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) { av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err); return -1; } decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front); tags = num_front; decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side); tags += num_side; decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back); tags += num_back; decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe); tags += num_lfe; skip_bits_long(gb, 4 * num_assoc_data); decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc); tags += num_cc; relative_align_get_bits(gb, byte_align_ref); /* comment field, first byte is length */ comment_len = get_bits(gb, 8) * 8; if (get_bits_left(gb) < comment_len) { av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err); return AVERROR_INVALIDDATA; } skip_bits_long(gb, comment_len); return tags; }


static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
	unsigned char *pt;
	unsigned char l, lg, n = 0;
	int fac_national_digis_received = 0;

	do {
		switch (*p & 0xC0) {
		case 0x00:
			p   += 2;
			n   += 2;
			len -= 2;
			break;

		case 0x40:
			if (*p == FAC_NATIONAL_RAND)
				facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);
			p   += 3;
			n   += 3;
			len -= 3;
			break;

		case 0x80:
			p   += 4;
			n   += 4;
			len -= 4;
			break;

		case 0xC0:
			l = p[1];
			if (*p == FAC_NATIONAL_DEST_DIGI) {
				if (!fac_national_digis_received) {
					memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);
					facilities->source_ndigis = 1;
				}
			}
			else if (*p == FAC_NATIONAL_SRC_DIGI) {
				if (!fac_national_digis_received) {
					memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);
					facilities->dest_ndigis = 1;
				}
			}
			else if (*p == FAC_NATIONAL_FAIL_CALL) {
				memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);
			}
			else if (*p == FAC_NATIONAL_FAIL_ADD) {
				memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);
			}
			else if (*p == FAC_NATIONAL_DIGIS) {
				fac_national_digis_received = 1;
				facilities->source_ndigis = 0;
				facilities->dest_ndigis   = 0;
				for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {
					if (pt[6] & AX25_HBIT) {
						if (facilities->dest_ndigis >= ROSE_MAX_DIGIS)
							return -1;
						memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);
					} else {
						if (facilities->source_ndigis >= ROSE_MAX_DIGIS)
							return -1;
						memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);
					}
				}
			}
			p   += l + 2;
			n   += l + 2;
			len -= l + 2;
			break;
		}
	} while (*p != 0x00 && len > 0);

	return n;
}


int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci)
{
	struct sock *sk;
	struct sock *make;
	struct rose_sock *make_rose;
	struct rose_facilities_struct facilities;
	int n, len;

	skb->sk = NULL;		/* Initially we don't know who it's for */

	/*
	 *	skb->data points to the rose frame start
	 */
	memset(&facilities, 0x00, sizeof(struct rose_facilities_struct));

	len  = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1;
	len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1;
	if (!rose_parse_facilities(skb->data + len + 4, &facilities)) {
		rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76);
		return 0;
	}

	sk = rose_find_listener(&facilities.source_addr, &facilities.source_call);

	/*
	 * We can't accept the Call Request.
	 */
	if (sk == NULL || sk_acceptq_is_full(sk) ||
	    (make = rose_make_new(sk)) == NULL) {
		rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120);
		return 0;
	}

	skb->sk     = make;
	make->sk_state = TCP_ESTABLISHED;
	make_rose = rose_sk(make);

	make_rose->lci           = lci;
	make_rose->dest_addr     = facilities.dest_addr;
	make_rose->dest_call     = facilities.dest_call;
	make_rose->dest_ndigis   = facilities.dest_ndigis;
	for (n = 0 ; n < facilities.dest_ndigis ; n++)
		make_rose->dest_digis[n] = facilities.dest_digis[n];
	make_rose->source_addr   = facilities.source_addr;
	make_rose->source_call   = facilities.source_call;
	make_rose->source_ndigis = facilities.source_ndigis;
	for (n = 0 ; n < facilities.source_ndigis ; n++)
		make_rose->source_digis[n]= facilities.source_digis[n];
	make_rose->neighbour     = neigh;
	make_rose->device        = dev;
	make_rose->facilities    = facilities;

	make_rose->neighbour->use++;

	if (rose_sk(sk)->defer) {
		make_rose->state = ROSE_STATE_5;
	} else {
		rose_write_internal(make, ROSE_CALL_ACCEPTED);
		make_rose->state = ROSE_STATE_3;
		rose_start_idletimer(make);
	}

	make_rose->condition = 0x00;
	make_rose->vs        = 0;
	make_rose->va        = 0;
	make_rose->vr        = 0;
	make_rose->vl        = 0;
	sk->sk_ack_backlog++;

	rose_insert_socket(make);

	skb_queue_head(&sk->sk_receive_queue, skb);

	rose_start_heartbeat(make);

	if (!sock_flag(sk, SOCK_DEAD))
		sk->sk_data_ready(sk, skb->len);

	return 1;
}


inline typename V::VectorType FBUnserializer<V>::unserializeVector() {
  p_ += CODE_SIZE;

  typename V::VectorType ret = V::createVector();

  size_t code = nextCode();
  while (code != FB_SERIALIZE_STOP) {
    V::vectorAppend(ret, unserializeThing());
    code = nextCode();
  }
  p_ += CODE_SIZE;
  return ret;
}


static void rose_loopback_timer(unsigned long param)
{
	struct sk_buff *skb;
	struct net_device *dev;
	rose_address *dest;
	struct sock *sk;
	unsigned short frametype;
	unsigned int lci_i, lci_o;

	while ((skb = skb_dequeue(&loopback_queue)) != NULL) {
		lci_i     = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
		frametype = skb->data[2];
		dest      = (rose_address *)(skb->data + 4);
		lci_o     = ROSE_DEFAULT_MAXVC + 1 - lci_i;

		skb_reset_transport_header(skb);

		sk = rose_find_socket(lci_o, rose_loopback_neigh);
		if (sk) {
			if (rose_process_rx_frame(sk, skb) == 0)
				kfree_skb(skb);
			continue;
		}

		if (frametype == ROSE_CALL_REQUEST) {
			if ((dev = rose_dev_get(dest)) != NULL) {
				if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0)
					kfree_skb(skb);
			} else {
				kfree_skb(skb);
			}
		} else {
			kfree_skb(skb);
		}
	}
}


void mark_select_range_as_dependent ( THD * thd , SELECT_LEX * last_select , SELECT_LEX * current_sel , Field * found_field , Item * found_item , Item_ident * resolved_item ) {
 SELECT_LEX * previous_select = current_sel ;
 for ( ;
 previous_select -> outer_select ( ) != last_select ;
 previous_select = previous_select -> outer_select ( ) ) {
 Item_subselect * prev_subselect_item = previous_select -> master_unit ( ) -> item ;
 prev_subselect_item -> used_tables_cache |= OUTER_REF_TABLE_BIT ;
 prev_subselect_item -> const_item_cache = 0 ;
 }
 {
 Item_subselect * prev_subselect_item = previous_select -> master_unit ( ) -> item ;
 Item_ident * dependent = resolved_item ;
 if ( found_field == view_ref_found ) {
 Item : : Type type = found_item -> type ( ) ;
 prev_subselect_item -> used_tables_cache |= found_item -> used_tables ( ) ;
 dependent = ( ( type == Item : : REF_ITEM || type == Item : : FIELD_ITEM ) ? ( Item_ident * ) found_item : 0 ) ;
 }
 else prev_subselect_item -> used_tables_cache |= found_field -> table -> map ;
 prev_subselect_item -> const_item_cache = 0 ;
 mark_as_dependent ( thd , last_select , current_sel , resolved_item , dependent ) ;
 }
 }


int fts_build_mail ( struct fts_backend_update_context * update_ctx , struct mail * mail ) {
 int ret ;
 T_BEGIN {
 ret = fts_build_mail_real ( update_ctx , mail ) ;
 }
 T_END ;
 return ret ;
 }


void rose_write_internal(struct sock *sk, int frametype)
{
	struct rose_sock *rose = rose_sk(sk);
	struct sk_buff *skb;
	unsigned char  *dptr;
	unsigned char  lci1, lci2;
	char buffer[100];
	int len, faclen = 0;

	len = AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN + 1;

	switch (frametype) {
	case ROSE_CALL_REQUEST:
		len   += 1 + ROSE_ADDR_LEN + ROSE_ADDR_LEN;
		faclen = rose_create_facilities(buffer, rose);
		len   += faclen;
		break;
	case ROSE_CALL_ACCEPTED:
	case ROSE_CLEAR_REQUEST:
	case ROSE_RESET_REQUEST:
		len   += 2;
		break;
	}

	if ((skb = alloc_skb(len, GFP_ATOMIC)) == NULL)
		return;

	/*
	 *	Space for AX.25 header and PID.
	 */
	skb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + 1);

	dptr = skb_put(skb, skb_tailroom(skb));

	lci1 = (rose->lci >> 8) & 0x0F;
	lci2 = (rose->lci >> 0) & 0xFF;

	switch (frametype) {
	case ROSE_CALL_REQUEST:
		*dptr++ = ROSE_GFI | lci1;
		*dptr++ = lci2;
		*dptr++ = frametype;
		*dptr++ = 0xAA;
		memcpy(dptr, &rose->dest_addr,  ROSE_ADDR_LEN);
		dptr   += ROSE_ADDR_LEN;
		memcpy(dptr, &rose->source_addr, ROSE_ADDR_LEN);
		dptr   += ROSE_ADDR_LEN;
		memcpy(dptr, buffer, faclen);
		dptr   += faclen;
		break;

	case ROSE_CALL_ACCEPTED:
		*dptr++ = ROSE_GFI | lci1;
		*dptr++ = lci2;
		*dptr++ = frametype;
		*dptr++ = 0x00;		/* Address length */
		*dptr++ = 0;		/* Facilities length */
		break;

	case ROSE_CLEAR_REQUEST:
		*dptr++ = ROSE_GFI | lci1;
		*dptr++ = lci2;
		*dptr++ = frametype;
		*dptr++ = rose->cause;
		*dptr++ = rose->diagnostic;
		break;

	case ROSE_RESET_REQUEST:
		*dptr++ = ROSE_GFI | lci1;
		*dptr++ = lci2;
		*dptr++ = frametype;
		*dptr++ = ROSE_DTE_ORIGINATED;
		*dptr++ = 0;
		break;

	case ROSE_RR:
	case ROSE_RNR:
		*dptr++ = ROSE_GFI | lci1;
		*dptr++ = lci2;
		*dptr   = frametype;
		*dptr++ |= (rose->vr << 5) & 0xE0;
		break;

	case ROSE_CLEAR_CONFIRMATION:
	case ROSE_RESET_CONFIRMATION:
		*dptr++ = ROSE_GFI | lci1;
		*dptr++ = lci2;
		*dptr++  = frametype;
		break;

	default:
		printk(KERN_ERR "ROSE: rose_write_internal - invalid frametype %02X\n", frametype);
		kfree_skb(skb);
		return;
	}

	rose_transmit_link(skb, rose->neighbour);
}


void pcre_dump_cache(const std::string& filename) {
  s_pcreCache.dump(filename);
}