QPDF::calculateHPageOffset(
    std::map<int, QPDFXRefEntry> const& xref,
    std::map<int, qpdf_offset_t> const& lengths,
    std::map<int, int> const& obj_renumber)
{
    // Page Offset Hint Table

    // We are purposely leaving some values set to their initial zero
    // values.

    std::vector<QPDFObjectHandle> const& pages = getAllPages();
    unsigned int npages = pages.size();
    CHPageOffset& cph = this->m->c_page_offset_data;
    std::vector<CHPageOffsetEntry>& cphe = cph.entries;

    // Calculate minimum and maximum values for number of objects per
    // page and page length.

    int min_nobjects = cphe.at(0).nobjects;
    int max_nobjects = min_nobjects;
    int min_length = outputLengthNextN(
	pages.at(0).getObjectID(), min_nobjects, lengths, obj_renumber);
    int max_length = min_length;
    int max_shared = cphe.at(0).nshared_objects;

    HPageOffset& ph = this->m->page_offset_hints;
    std::vector<HPageOffsetEntry>& phe = ph.entries;
    // npages is the size of the existing pages array.
    phe = std::vector<HPageOffsetEntry>(npages);

    for (unsigned int i = 0; i < npages; ++i)
    {
	// Calculate values for each page, assigning full values to
	// the delta items.  They will be adjusted later.

	// Repeat calculations for page 0 so we can assign to phe[i]
	// without duplicating those assignments.

	int nobjects = cphe.at(i).nobjects;
	int length = outputLengthNextN(
	    pages.at(i).getObjectID(), nobjects, lengths, obj_renumber);
	int nshared = cphe.at(i).nshared_objects;

	min_nobjects = std::min(min_nobjects, nobjects);
	max_nobjects = std::max(max_nobjects, nobjects);
	min_length = std::min(min_length, length);
	max_length = std::max(max_length, length);
	max_shared = std::max(max_shared, nshared);

	phe.at(i).delta_nobjects = nobjects;
	phe.at(i).delta_page_length = length;
	phe.at(i).nshared_objects = nshared;
    }

    ph.min_nobjects = min_nobjects;
    int in_page0_id = pages.at(0).getObjectID();
    int out_page0_id = (*(obj_renumber.find(in_page0_id))).second;
    ph.first_page_offset = (*(xref.find(out_page0_id))).second.getOffset();
    ph.nbits_delta_nobjects = nbits(max_nobjects - min_nobjects);
    ph.min_page_length = min_length;
    ph.nbits_delta_page_length = nbits(max_length - min_length);
    ph.nbits_nshared_objects = nbits(max_shared);
    ph.nbits_shared_identifier =
	nbits(this->m->c_shared_object_data.nshared_total);
    ph.shared_denominator = 4;	// doesn't matter

    // It isn't clear how to compute content offset and content
    // length.  Since we are not interleaving page objects with the
    // content stream, we'll use the same values for content length as
    // page length.  We will use 0 as content offset because this is
    // what Adobe does (implementation note 127) and pdlin as well.
    ph.nbits_delta_content_length = ph.nbits_delta_page_length;
    ph.min_content_length = ph.min_page_length;

    for (unsigned int i = 0; i < npages; ++i)
    {
	// Adjust delta entries
	if ((phe.at(i).delta_nobjects < min_nobjects) ||
            (phe.at(i).delta_page_length < min_length))
        {
            stopOnError("found too small delta nobjects or delta page length"
                        " while writing linearization data");
        }
	phe.at(i).delta_nobjects -= min_nobjects;
	phe.at(i).delta_page_length -= min_length;
	phe.at(i).delta_content_length = phe.at(i).delta_page_length;

	for (int j = 0; j < cphe.at(i).nshared_objects; ++j)
	{
	    phe.at(i).shared_identifiers.push_back(
		cphe.at(i).shared_identifiers.at(j));
	    phe.at(i).shared_numerators.push_back(0);
	}
    }
}


static PHP_NAMED_FUNCTION ( zif_zip_entry_filesize ) {
 php_zip_entry_get_info ( INTERNAL_FUNCTION_PARAM_PASSTHRU , 2 ) ;
 }


static gboolean file_was_not_mounted ( NautilusFile * file ) {
 GError * error ;
 error = nautilus_file_get_file_info_error ( file ) ;
 return error != NULL && error -> domain == G_IO_ERROR && error -> code == G_IO_ERROR_NOT_MOUNTED ;
 }


void vp8cx_mb_init_quantizer ( VP8_COMP * cpi , MACROBLOCK * x , int ok_to_skip ) {
 int i ;
 int QIndex ;
 MACROBLOCKD * xd = & x -> e_mbd ;
 int zbin_extra ;
 if ( xd -> segmentation_enabled ) {
 if ( xd -> mb_segement_abs_delta == SEGMENT_ABSDATA ) QIndex = xd -> segment_feature_data [ MB_LVL_ALT_Q ] [ xd -> mode_info_context -> mbmi . segment_id ] ;
 else {
 QIndex = cpi -> common . base_qindex + xd -> segment_feature_data [ MB_LVL_ALT_Q ] [ xd -> mode_info_context -> mbmi . segment_id ] ;
 QIndex = ( QIndex >= 0 ) ? ( ( QIndex <= MAXQ ) ? QIndex : MAXQ ) : 0 ;
 }
 }
 else QIndex = cpi -> common . base_qindex ;
 if ( ! ok_to_skip || QIndex != x -> q_index ) {
 xd -> dequant_y1_dc [ 0 ] = 1 ;
 xd -> dequant_y1 [ 0 ] = cpi -> common . Y1dequant [ QIndex ] [ 0 ] ;
 xd -> dequant_y2 [ 0 ] = cpi -> common . Y2dequant [ QIndex ] [ 0 ] ;
 xd -> dequant_uv [ 0 ] = cpi -> common . UVdequant [ QIndex ] [ 0 ] ;
 for ( i = 1 ;
 i < 16 ;
 i ++ ) {
 xd -> dequant_y1_dc [ i ] = xd -> dequant_y1 [ i ] = cpi -> common . Y1dequant [ QIndex ] [ 1 ] ;
 xd -> dequant_y2 [ i ] = cpi -> common . Y2dequant [ QIndex ] [ 1 ] ;
 xd -> dequant_uv [ i ] = cpi -> common . UVdequant [ QIndex ] [ 1 ] ;
 }
 # if 1 for ( i = 0 ;
 i < 16 ;
 i ++ ) x -> e_mbd . block [ i ] . dequant = xd -> dequant_y1 ;
 for ( i = 16 ;
 i < 24 ;
 i ++ ) x -> e_mbd . block [ i ] . dequant = xd -> dequant_uv ;
 x -> e_mbd . block [ 24 ] . dequant = xd -> dequant_y2 ;
 # endif zbin_extra = ZBIN_EXTRA_Y ;
 for ( i = 0 ;
 i < 16 ;
 i ++ ) {
 x -> block [ i ] . quant = cpi -> Y1quant [ QIndex ] ;
 x -> block [ i ] . quant_fast = cpi -> Y1quant_fast [ QIndex ] ;
 x -> block [ i ] . quant_shift = cpi -> Y1quant_shift [ QIndex ] ;
 x -> block [ i ] . zbin = cpi -> Y1zbin [ QIndex ] ;
 x -> block [ i ] . round = cpi -> Y1round [ QIndex ] ;
 x -> block [ i ] . zrun_zbin_boost = cpi -> zrun_zbin_boost_y1 [ QIndex ] ;
 x -> block [ i ] . zbin_extra = ( short ) zbin_extra ;
 }
 zbin_extra = ZBIN_EXTRA_UV ;
 for ( i = 16 ;
 i < 24 ;
 i ++ ) {
 x -> block [ i ] . quant = cpi -> UVquant [ QIndex ] ;
 x -> block [ i ] . quant_fast = cpi -> UVquant_fast [ QIndex ] ;
 x -> block [ i ] . quant_shift = cpi -> UVquant_shift [ QIndex ] ;
 x -> block [ i ] . zbin = cpi -> UVzbin [ QIndex ] ;
 x -> block [ i ] . round = cpi -> UVround [ QIndex ] ;
 x -> block [ i ] . zrun_zbin_boost = cpi -> zrun_zbin_boost_uv [ QIndex ] ;
 x -> block [ i ] . zbin_extra = ( short ) zbin_extra ;
 }
 zbin_extra = ZBIN_EXTRA_Y2 ;
 x -> block [ 24 ] . quant_fast = cpi -> Y2quant_fast [ QIndex ] ;
 x -> block [ 24 ] . quant = cpi -> Y2quant [ QIndex ] ;
 x -> block [ 24 ] . quant_shift = cpi -> Y2quant_shift [ QIndex ] ;
 x -> block [ 24 ] . zbin = cpi -> Y2zbin [ QIndex ] ;
 x -> block [ 24 ] . round = cpi -> Y2round [ QIndex ] ;
 x -> block [ 24 ] . zrun_zbin_boost = cpi -> zrun_zbin_boost_y2 [ QIndex ] ;
 x -> block [ 24 ] . zbin_extra = ( short ) zbin_extra ;
 x -> q_index = QIndex ;
 x -> last_zbin_over_quant = x -> zbin_over_quant ;
 x -> last_zbin_mode_boost = x -> zbin_mode_boost ;
 x -> last_act_zbin_adj = x -> act_zbin_adj ;
 }
 else if ( x -> last_zbin_over_quant != x -> zbin_over_quant || x -> last_zbin_mode_boost != x -> zbin_mode_boost || x -> last_act_zbin_adj != x -> act_zbin_adj ) {
 zbin_extra = ZBIN_EXTRA_Y ;
 for ( i = 0 ;
 i < 16 ;
 i ++ ) x -> block [ i ] . zbin_extra = ( short ) zbin_extra ;
 zbin_extra = ZBIN_EXTRA_UV ;
 for ( i = 16 ;
 i < 24 ;
 i ++ ) x -> block [ i ] . zbin_extra = ( short ) zbin_extra ;
 zbin_extra = ZBIN_EXTRA_Y2 ;
 x -> block [ 24 ] . zbin_extra = ( short ) zbin_extra ;
 x -> last_zbin_over_quant = x -> zbin_over_quant ;
 x -> last_zbin_mode_boost = x -> zbin_mode_boost ;
 x -> last_act_zbin_adj = x -> act_zbin_adj ;
 }
 }


static vpx_codec_err_t ctrl_set_tile_rows ( vpx_codec_alg_priv_t * ctx , va_list args ) {
 struct vp9_extracfg extra_cfg = ctx -> extra_cfg ;
 extra_cfg . tile_rows = CAST ( VP9E_SET_TILE_ROWS , args ) ;
 return update_extra_cfg ( ctx , & extra_cfg ) ;
 }


QPDFWriter::writeLinearized()
{
    // Optimize file and enqueue objects in order

    discardGeneration(this->m->object_to_object_stream,
                      this->m->object_to_object_stream_no_gen);

    bool need_xref_stream = (! this->m->object_to_object_stream.empty());
    this->m->pdf.optimize(this->m->object_to_object_stream_no_gen);

    std::vector<QPDFObjectHandle> part4;
    std::vector<QPDFObjectHandle> part6;
    std::vector<QPDFObjectHandle> part7;
    std::vector<QPDFObjectHandle> part8;
    std::vector<QPDFObjectHandle> part9;
    QPDF::Writer::getLinearizedParts(
        this->m->pdf, this->m->object_to_object_stream_no_gen,
        part4, part6, part7, part8, part9);

    // Object number sequence:
    //
    //  second half
    //    second half uncompressed objects
    //    second half xref stream, if any
    //    second half compressed objects
    //  first half
    //    linearization dictionary
    //    first half xref stream, if any
    //    part 4 uncompresesd objects
    //    encryption dictionary, if any
    //    hint stream
    //    part 6 uncompressed objects
    //    first half compressed objects
    //

    // Second half objects
    int second_half_uncompressed = part7.size() + part8.size() + part9.size();
    int second_half_first_obj = 1;
    int after_second_half = 1 + second_half_uncompressed;
    this->m->next_objid = after_second_half;
    int second_half_xref = 0;
    if (need_xref_stream)
    {
	second_half_xref = this->m->next_objid++;
    }
    // Assign numbers to all compressed objects in the second half.
    std::vector<QPDFObjectHandle>* vecs2[] = {&part7, &part8, &part9};
    for (int i = 0; i < 3; ++i)
    {
	for (std::vector<QPDFObjectHandle>::iterator iter = (*vecs2[i]).begin();
	     iter != (*vecs2[i]).end(); ++iter)
	{
	    assignCompressedObjectNumbers((*iter).getObjGen());
	}
    }
    int second_half_end = this->m->next_objid - 1;
    int second_trailer_size = this->m->next_objid;

    // First half objects
    int first_half_start = this->m->next_objid;
    int lindict_id = this->m->next_objid++;
    int first_half_xref = 0;
    if (need_xref_stream)
    {
	first_half_xref = this->m->next_objid++;
    }
    int part4_first_obj = this->m->next_objid;
    this->m->next_objid += part4.size();
    int after_part4 = this->m->next_objid;
    if (this->m->encrypted)
    {
	this->m->encryption_dict_objid = this->m->next_objid++;
    }
    int hint_id = this->m->next_objid++;
    int part6_first_obj = this->m->next_objid;
    this->m->next_objid += part6.size();
    int after_part6 = this->m->next_objid;
    // Assign numbers to all compressed objects in the first half
    std::vector<QPDFObjectHandle>* vecs1[] = {&part4, &part6};
    for (int i = 0; i < 2; ++i)
    {
	for (std::vector<QPDFObjectHandle>::iterator iter = (*vecs1[i]).begin();
	     iter != (*vecs1[i]).end(); ++iter)
	{
	    assignCompressedObjectNumbers((*iter).getObjGen());
	}
    }
    int first_half_end = this->m->next_objid - 1;
    int first_trailer_size = this->m->next_objid;

    int part4_end_marker = part4.back().getObjectID();
    int part6_end_marker = part6.back().getObjectID();
    qpdf_offset_t space_before_zero = 0;
    qpdf_offset_t file_size = 0;
    qpdf_offset_t part6_end_offset = 0;
    qpdf_offset_t first_half_max_obj_offset = 0;
    qpdf_offset_t second_xref_offset = 0;
    qpdf_offset_t first_xref_end = 0;
    qpdf_offset_t second_xref_end = 0;

    this->m->next_objid = part4_first_obj;
    enqueuePart(part4);
    assert(this->m->next_objid == after_part4);
    this->m->next_objid = part6_first_obj;
    enqueuePart(part6);
    assert(this->m->next_objid == after_part6);
    this->m->next_objid = second_half_first_obj;
    enqueuePart(part7);
    enqueuePart(part8);
    enqueuePart(part9);
    assert(this->m->next_objid == after_second_half);

    qpdf_offset_t hint_length = 0;
    PointerHolder<Buffer> hint_buffer;

    // Write file in two passes.  Part numbers refer to PDF spec 1.4.

    FILE* lin_pass1_file = 0;
    for (int pass = 1; pass <= 2; ++pass)
    {
	if (pass == 1)
	{
            if (! this->m->lin_pass1_filename.empty())
            {
                lin_pass1_file =
                    QUtil::safe_fopen(
                        this->m->lin_pass1_filename.c_str(), "wb");
                pushPipeline(
                    new Pl_StdioFile("linearization pass1", lin_pass1_file));
                activatePipelineStack();
            }
            else
            {
                pushDiscardFilter();
            }
            if (this->m->deterministic_id)
            {
                pushMD5Pipeline();
            }
	}

	// Part 1: header

	writeHeader();

	// Part 2: linearization parameter dictionary.  Save enough
	// space to write real dictionary.  200 characters is enough
	// space if all numerical values in the parameter dictionary
	// that contain offsets are 20 digits long plus a few extra
	// characters for safety.  The entire linearization parameter
	// dictionary must appear within the first 1024 characters of
	// the file.

	qpdf_offset_t pos = this->m->pipeline->getCount();
	openObject(lindict_id);
	writeString("<<");
	if (pass == 2)
	{
	    std::vector<QPDFObjectHandle> const& pages =
                this->m->pdf.getAllPages();
	    int first_page_object =
                this->m->obj_renumber[pages.at(0).getObjGen()];
	    int npages = pages.size();

	    writeString(" /Linearized 1 /L ");
	    writeString(QUtil::int_to_string(file_size + hint_length));
	    // Implementation note 121 states that a space is
	    // mandatory after this open bracket.
	    writeString(" /H [ ");
	    writeString(QUtil::int_to_string(
                            this->m->xref[hint_id].getOffset()));
	    writeString(" ");
	    writeString(QUtil::int_to_string(hint_length));
	    writeString(" ] /O ");
	    writeString(QUtil::int_to_string(first_page_object));
	    writeString(" /E ");
	    writeString(QUtil::int_to_string(part6_end_offset + hint_length));
	    writeString(" /N ");
	    writeString(QUtil::int_to_string(npages));
	    writeString(" /T ");
	    writeString(QUtil::int_to_string(space_before_zero + hint_length));
	}
	writeString(" >>");
	closeObject(lindict_id);
	static int const pad = 200;
	int spaces = (pos - this->m->pipeline->getCount() + pad);
	assert(spaces >= 0);
	writePad(spaces);
	writeString("\n");

        // If the user supplied any additional header text, write it
        // here after the linearization parameter dictionary.
        writeString(this->m->extra_header_text);

	// Part 3: first page cross reference table and trailer.

	qpdf_offset_t first_xref_offset = this->m->pipeline->getCount();
	qpdf_offset_t hint_offset = 0;
	if (pass == 2)
	{
	    hint_offset = this->m->xref[hint_id].getOffset();
	}
	if (need_xref_stream)
	{
	    // Must pad here too.
	    if (pass == 1)
	    {
		// Set first_half_max_obj_offset to a value large
		// enough to force four bytes to be reserved for each
		// file offset.  This would provide adequate space for
		// the xref stream as long as the last object in page
		// 1 starts with in the first 4 GB of the file, which
		// is extremely likely.  In the second pass, we will
		// know the actual value for this, but it's okay if
		// it's smaller.
		first_half_max_obj_offset = 1 << 25;
	    }
	    pos = this->m->pipeline->getCount();
	    writeXRefStream(first_half_xref, first_half_end,
			    first_half_max_obj_offset,
			    t_lin_first, first_half_start, first_half_end,
			    first_trailer_size,
			    hint_length + second_xref_offset,
			    hint_id, hint_offset, hint_length,
			    (pass == 1), pass);
	    qpdf_offset_t endpos = this->m->pipeline->getCount();
	    if (pass == 1)
	    {
		// Pad so we have enough room for the real xref
		// stream.
		writePad(calculateXrefStreamPadding(endpos - pos));
		first_xref_end = this->m->pipeline->getCount();
	    }
	    else
	    {
		// Pad so that the next object starts at the same
		// place as in pass 1.
		writePad(first_xref_end - endpos);

		if (this->m->pipeline->getCount() != first_xref_end)
                {
                    throw std::logic_error(
                        "insufficient padding for first pass xref stream");
                }
	    }
	    writeString("\n");
	}
	else
	{
	    writeXRefTable(t_lin_first, first_half_start, first_half_end,
			   first_trailer_size, hint_length + second_xref_offset,
			   (pass == 1), hint_id, hint_offset, hint_length,
                           pass);
	    writeString("startxref\n0\n%%EOF\n");
	}

	// Parts 4 through 9

	for (std::list<QPDFObjectHandle>::iterator iter =
		 this->m->object_queue.begin();
	     iter != this->m->object_queue.end(); ++iter)
	{
	    QPDFObjectHandle cur_object = (*iter);
	    if (cur_object.getObjectID() == part6_end_marker)
	    {
		first_half_max_obj_offset = this->m->pipeline->getCount();
	    }
	    writeObject(cur_object);
	    if (cur_object.getObjectID() == part4_end_marker)
	    {
		if (this->m->encrypted)
		{
		    writeEncryptionDictionary();
		}
		if (pass == 1)
		{
		    this->m->xref[hint_id] =
			QPDFXRefEntry(1, this->m->pipeline->getCount(), 0);
		}
		else
		{
		    // Part 5: hint stream
		    writeBuffer(hint_buffer);
		}
	    }
	    if (cur_object.getObjectID() == part6_end_marker)
	    {
		part6_end_offset = this->m->pipeline->getCount();
	    }
	}

	// Part 10: overflow hint stream -- not used

	// Part 11: main cross reference table and trailer

	second_xref_offset = this->m->pipeline->getCount();
	if (need_xref_stream)
	{
	    pos = this->m->pipeline->getCount();
	    space_before_zero =
		writeXRefStream(second_half_xref,
				second_half_end, second_xref_offset,
				t_lin_second, 0, second_half_end,
				second_trailer_size,
				0, 0, 0, 0, (pass == 1), pass);
	    qpdf_offset_t endpos = this->m->pipeline->getCount();

	    if (pass == 1)
	    {
		// Pad so we have enough room for the real xref
		// stream.  See comments for previous xref stream on
		// how we calculate the padding.
		writePad(calculateXrefStreamPadding(endpos - pos));
		writeString("\n");
		second_xref_end = this->m->pipeline->getCount();
	    }
	    else
	    {
		// Make the file size the same.
		qpdf_offset_t pos = this->m->pipeline->getCount();
		writePad(second_xref_end + hint_length - 1 - pos);
		writeString("\n");

		// If this assertion fails, maybe we didn't have
		// enough padding above.
		if (this->m->pipeline->getCount() !=
                    second_xref_end + hint_length)
                {
                    throw std::logic_error(
                        "count mismatch after xref stream;"
                        " possible insufficient padding?");
                }
	    }
	}
	else
	{
	    space_before_zero =
		writeXRefTable(t_lin_second, 0, second_half_end,
			       second_trailer_size, 0, false, 0, 0, 0, pass);
	}
	writeString("startxref\n");
	writeString(QUtil::int_to_string(first_xref_offset));
	writeString("\n%%EOF\n");

        discardGeneration(this->m->obj_renumber, this->m->obj_renumber_no_gen);

	if (pass == 1)
	{
            if (this->m->deterministic_id)
            {
                QTC::TC("qpdf", "QPDFWriter linearized deterministic ID",
                        need_xref_stream ? 0 : 1);
                computeDeterministicIDData();
                popPipelineStack();
                assert(this->m->md5_pipeline == 0);
            }

	    // Close first pass pipeline
	    file_size = this->m->pipeline->getCount();
	    popPipelineStack();

	    // Save hint offset since it will be set to zero by
	    // calling openObject.
	    qpdf_offset_t hint_offset = this->m->xref[hint_id].getOffset();

	    // Write hint stream to a buffer
	    pushPipeline(new Pl_Buffer("hint buffer"));
	    activatePipelineStack();
	    writeHintStream(hint_id);
	    popPipelineStack(&hint_buffer);
	    hint_length = hint_buffer->getSize();

	    // Restore hint offset
	    this->m->xref[hint_id] = QPDFXRefEntry(1, hint_offset, 0);
            if (lin_pass1_file)
            {
                // Write some debugging information
                fprintf(lin_pass1_file, "%% hint_offset=%s\n",
                        QUtil::int_to_string(hint_offset).c_str());
                fprintf(lin_pass1_file, "%% hint_length=%s\n",
                        QUtil::int_to_string(hint_length).c_str());
                fprintf(lin_pass1_file, "%% second_xref_offset=%s\n",
                        QUtil::int_to_string(second_xref_offset).c_str());
                fprintf(lin_pass1_file, "%% second_xref_end=%s\n",
                        QUtil::int_to_string(second_xref_end).c_str());
                fclose(lin_pass1_file);
                lin_pass1_file = 0;
            }
	}
    }
}


TEST_F ( ExternalProtocolHandlerTest , DISABLED_TestLaunchSchemeUnknownChromeDefault ) {
 DoTest ( ExternalProtocolHandler : : UNKNOWN , shell_integration : : IS_DEFAULT , Action : : BLOCK ) ;
 }


Pl_ASCII85Decoder::flush()
{
    if (this->pos == 0)
    {
	QTC::TC("libtests", "Pl_ASCII85Decoder no-op flush");
	return;
    }
    unsigned long lval = 0;
    for (int i = 0; i < 5; ++i)
    {
	lval *= 85;
	lval += (this->inbuf[i] - 33);
    }

    unsigned char outbuf[4];
    memset(outbuf, 0, 4);
    for (int i = 3; i >= 0; --i)
    {
	outbuf[i] = lval & 0xff;
	lval >>= 8;
    }

    QTC::TC("libtests", "Pl_ASCII85Decoder partial flush",
	    (this->pos == 5) ? 0 : 1);
    getNext()->write(outbuf, this->pos - 1);

    this->pos = 0;
    memset(this->inbuf, 117, 5);
}


void helper_sysenter(CPUX86State *env) { if (env->sysenter_cs == 0) { raise_exception_err(env, EXCP0D_GPF, 0); } env->eflags &= ~(VM_MASK | IF_MASK | RF_MASK); cpu_x86_set_cpl(env, 0); #ifdef TARGET_X86_64 if (env->hflags & HF_LMA_MASK) { cpu_x86_load_seg_cache(env, R_CS, env->sysenter_cs & 0xfffc, 0, 0xffffffff, DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK | DESC_L_MASK); } else #endif { cpu_x86_load_seg_cache(env, R_CS, env->sysenter_cs & 0xfffc, 0, 0xffffffff, DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK | DESC_CS_MASK | DESC_R_MASK | DESC_A_MASK); } cpu_x86_load_seg_cache(env, R_SS, (env->sysenter_cs + 8) & 0xfffc, 0, 0xffffffff, DESC_G_MASK | DESC_B_MASK | DESC_P_MASK | DESC_S_MASK | DESC_W_MASK | DESC_A_MASK); env->regs[R_ESP] = env->sysenter_esp; env->eip = env->sysenter_eip; }


int bdrv_snapshot_load_tmp_by_id_or_name(BlockDriverState *bs, const char *id_or_name, Error **errp) { int ret; Error *local_err = NULL; ret = bdrv_snapshot_load_tmp(bs, id_or_name, NULL, &local_err); if (ret == -ENOENT || ret == -EINVAL) { error_free(local_err); local_err = NULL; ret = bdrv_snapshot_load_tmp(bs, NULL, id_or_name, &local_err); } if (local_err) { error_propagate(errp, local_err); } return ret; }


static gboolean gst_asf_demux_check_activate_streams ( GstASFDemux * demux , gboolean force ) {
 guint i , actual_streams = 0 ;
 if ( demux -> activated_streams ) return TRUE ;
 if ( G_UNLIKELY ( ! gst_asf_demux_check_first_ts ( demux , force ) ) ) return FALSE ;
 if ( ! all_streams_prerolled ( demux ) && ! force ) {
 GST_DEBUG_OBJECT ( demux , "not all streams with data beyond preroll yet" ) ;
 return FALSE ;
 }
 for ( i = 0 ;
 i < demux -> num_streams ;
 ++ i ) {
 AsfStream * stream = & demux -> stream [ i ] ;
 if ( stream -> payloads -> len > 0 ) {
 if ( stream -> inspect_payload && ! stream -> active && ! gst_asf_demux_update_caps_from_payload ( demux , stream ) && stream -> payloads -> len < 20 ) {
 return FALSE ;
 }
 GST_LOG_OBJECT ( stream -> pad , "is prerolled - activate!" ) ;
 gst_asf_demux_activate_stream ( demux , stream ) ;
 actual_streams += 1 ;
 }
 else {
 GST_LOG_OBJECT ( stream -> pad , "no data, ignoring stream" ) ;
 }
 }
 if ( actual_streams == 0 ) {
 GST_ERROR_OBJECT ( demux , "No streams activated!" ) ;
 return FALSE ;
 }
 gst_asf_demux_release_old_pads ( demux ) ;
 demux -> activated_streams = TRUE ;
 GST_LOG_OBJECT ( demux , "signalling no more pads" ) ;
 gst_element_no_more_pads ( GST_ELEMENT ( demux ) ) ;
 return TRUE ;
 }


static int encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pic, int *got_packet) { ProresContext *ctx = avctx->priv_data; uint8_t *orig_buf, *buf, *slice_hdr, *slice_sizes, *tmp; uint8_t *picture_size_pos; PutBitContext pb; int x, y, i, mb, q = 0; int sizes[4] = { 0 }; int slice_hdr_size = 2 + 2 * (ctx->num_planes - 1); int frame_size, picture_size, slice_size; int mbs_per_slice = ctx->mbs_per_slice; int pkt_size, ret; *avctx->coded_frame = *pic; avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I; avctx->coded_frame->key_frame = 1; pkt_size = ctx->mb_width * ctx->mb_height * 64 * 3 * 12 + ctx->num_slices * 2 + 200 + FF_MIN_BUFFER_SIZE; if ((ret = ff_alloc_packet(pkt, pkt_size)) < 0) { av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n"); return ret; } orig_buf = pkt->data; // frame atom orig_buf += 4; // frame size bytestream_put_be32 (&orig_buf, FRAME_ID); // frame container ID buf = orig_buf; // frame header tmp = buf; buf += 2; // frame header size will be stored here bytestream_put_be16 (&buf, 0); // version 1 bytestream_put_buffer(&buf, "Lavc", 4); // creator bytestream_put_be16 (&buf, avctx->width); bytestream_put_be16 (&buf, avctx->height); bytestream_put_byte (&buf, ctx->chroma_factor << 6); // frame flags bytestream_put_byte (&buf, 0); // reserved bytestream_put_byte (&buf, 0); // primaries bytestream_put_byte (&buf, 0); // transfer function bytestream_put_byte (&buf, 6); // colour matrix - ITU-R BT.601-4 bytestream_put_byte (&buf, 0x40); // source format and alpha information bytestream_put_byte (&buf, 0); // reserved bytestream_put_byte (&buf, 0x03); // matrix flags - both matrices are present // luma quantisation matrix for (i = 0; i < 64; i++) bytestream_put_byte(&buf, ctx->profile_info->quant[i]); // chroma quantisation matrix for (i = 0; i < 64; i++) bytestream_put_byte(&buf, ctx->profile_info->quant[i]); bytestream_put_be16 (&tmp, buf - orig_buf); // write back frame header size // picture header picture_size_pos = buf + 1; bytestream_put_byte (&buf, 0x40); // picture header size (in bits) buf += 4; // picture data size will be stored here bytestream_put_be16 (&buf, ctx->num_slices); // total number of slices bytestream_put_byte (&buf, av_log2(ctx->mbs_per_slice) << 4); // slice width and height in MBs // seek table - will be filled during slice encoding slice_sizes = buf; buf += ctx->num_slices * 2; // slices for (y = 0; y < ctx->mb_height; y++) { mbs_per_slice = ctx->mbs_per_slice; for (x = mb = 0; x < ctx->mb_width; x += mbs_per_slice, mb++) { while (ctx->mb_width - x < mbs_per_slice) mbs_per_slice >>= 1; q = find_slice_quant(avctx, pic, (mb + 1) * TRELLIS_WIDTH, x, y, mbs_per_slice); } for (x = ctx->slices_width - 1; x >= 0; x--) { ctx->slice_q[x] = ctx->nodes[q].quant; q = ctx->nodes[q].prev_node; } mbs_per_slice = ctx->mbs_per_slice; for (x = mb = 0; x < ctx->mb_width; x += mbs_per_slice, mb++) { q = ctx->slice_q[mb]; while (ctx->mb_width - x < mbs_per_slice) mbs_per_slice >>= 1; bytestream_put_byte(&buf, slice_hdr_size << 3); slice_hdr = buf; buf += slice_hdr_size - 1; init_put_bits(&pb, buf, (pkt_size - (buf - orig_buf)) * 8); encode_slice(avctx, pic, &pb, sizes, x, y, q, mbs_per_slice); bytestream_put_byte(&slice_hdr, q); slice_size = slice_hdr_size + sizes[ctx->num_planes - 1]; for (i = 0; i < ctx->num_planes - 1; i++) { bytestream_put_be16(&slice_hdr, sizes[i]); slice_size += sizes[i]; } bytestream_put_be16(&slice_sizes, slice_size); buf += slice_size - slice_hdr_size; } } orig_buf -= 8; frame_size = buf - orig_buf; picture_size = buf - picture_size_pos - 6; bytestream_put_be32(&orig_buf, frame_size); bytestream_put_be32(&picture_size_pos, picture_size); pkt->size = frame_size; pkt->flags |= AV_PKT_FLAG_KEY; *got_packet = 1; return 0; }


static int scsi_write_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); n = r->iov.iov_len / 512; if (n) { qemu_iovec_init_external(&r->qiov, &r->iov, 1); r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n, scsi_write_complete, r); if (r->req.aiocb == NULL) { scsi_write_complete(r, -EIO); } } else { /* Invoke completion routine to fetch data from host. */ scsi_write_complete(r, 0); } return 0; }


ValueSetter::writeAppearance()
{
    this->replaced = true;

    // This code does not take quadding into consideration because
    // doing so requires font metric information, which we don't
    // have in many cases.

    double tfh = 1.2 * tf;
    int dx = 1;

    // Write one or more lines, centered vertically, possibly with
    // one row highlighted.

    size_t max_rows = static_cast<size_t>((bbox.ury - bbox.lly) / tfh);
    bool highlight = false;
    size_t highlight_idx = 0;

    std::vector<std::string> lines;
    if (opt.empty() || (max_rows < 2))
    {
        lines.push_back(V);
    }
    else
    {
        // Figure out what rows to write
        size_t nopt = opt.size();
        size_t found_idx = 0;
        bool found = false;
        for (found_idx = 0; found_idx < nopt; ++found_idx)
        {
            if (opt.at(found_idx) == V)
            {
                found = true;
                break;
            }
        }
        if (found)
        {
            // Try to make the found item the second one, but
            // adjust for under/overflow.
            int wanted_first = found_idx - 1;
            int wanted_last = found_idx + max_rows - 2;
            QTC::TC("qpdf", "QPDFFormFieldObjectHelper list found");
            while (wanted_first < 0)
            {
                QTC::TC("qpdf", "QPDFFormFieldObjectHelper list first too low");
                ++wanted_first;
                ++wanted_last;
            }
            while (wanted_last >= static_cast<int>(nopt))
            {
                QTC::TC("qpdf", "QPDFFormFieldObjectHelper list last too high");
                if (wanted_first > 0)
                {
                    --wanted_first;
                }
                --wanted_last;
            }
            highlight = true;
            highlight_idx = found_idx - wanted_first;
            for (int i = wanted_first; i <= wanted_last; ++i)
            {
                lines.push_back(opt.at(i));
            }
        }
        else
        {
            QTC::TC("qpdf", "QPDFFormFieldObjectHelper list not found");
            // include our value and the first n-1 rows
            highlight_idx = 0;
            highlight = true;
            lines.push_back(V);
            for (size_t i = 0; ((i < nopt) && (i < (max_rows - 1))); ++i)
            {
                lines.push_back(opt.at(i));
            }
        }
    }

    // Write the lines centered vertically, highlighting if needed
    size_t nlines = lines.size();
    double dy = bbox.ury - ((bbox.ury - bbox.lly - (nlines * tfh)) / 2.0);
    if (highlight)
    {
        write("q\n0.85 0.85 0.85 rg\n" +
              QUtil::double_to_string(bbox.llx) + " " +
              QUtil::double_to_string(bbox.lly + dy -
                                      (tfh * (highlight_idx + 1))) + " " +
              QUtil::double_to_string(bbox.urx - bbox.llx) + " " +
              QUtil::double_to_string(tfh) +
              " re f\nQ\n");
    }
    dy -= tf;
    write("q\nBT\n" + DA + "\n");
    for (size_t i = 0; i < nlines; ++i)
    {
        // We could adjust Tm to translate to the beginning the first
        // line, set TL to tfh, and use T* for each subsequent line,
        // but doing this would require extracting any Tm from DA,
        // which doesn't seem really worth the effort.
        if (i == 0)
        {
            write(QUtil::double_to_string(bbox.llx + dx) + " " +
                  QUtil::double_to_string(bbox.lly + dy) + " Td\n");
        }
        else
        {
            write("0 " + QUtil::double_to_string(-tfh) + " Td\n");
        }
        write(QPDFObjectHandle::newString(lines.at(i)).unparse() + " Tj\n");
    }
    write("ET\nQ\nEMC");
}


QPDF::writeHSharedObject(BitWriter& w)
{
    HSharedObject& t = this->m->shared_object_hints;

    w.writeBits(t.first_shared_obj, 32);		    // 1
    w.writeBits(t.first_shared_offset, 32);		    // 2
    w.writeBits(t.nshared_first_page, 32);		    // 3
    w.writeBits(t.nshared_total, 32);			    // 4
    w.writeBits(t.nbits_nobjects, 16);			    // 5
    w.writeBits(t.min_group_length, 32);		    // 6
    w.writeBits(t.nbits_delta_group_length, 16);	    // 7

    QTC::TC("qpdf", "QPDF lin write nshared_total > nshared_first_page",
	    (t.nshared_total > t.nshared_first_page) ? 1 : 0);

    int nitems = t.nshared_total;
    std::vector<HSharedObjectEntry>& entries = t.entries;

    write_vector_int(w, nitems, entries,
		     t.nbits_delta_group_length,
		     &HSharedObjectEntry::delta_group_length);
    write_vector_int(w, nitems, entries,
		     1, &HSharedObjectEntry::signature_present);
    for (int i = 0; i < nitems; ++i)
    {
	// If signature were present, we'd have to write a 128-bit hash.
	if (entries.at(i).signature_present != 0)
        {
            stopOnError("found unexpected signature present"
                        " while writing linearization data");
        }
    }
    write_vector_int(w, nitems, entries,
		     t.nbits_nobjects,
		     &HSharedObjectEntry::nobjects_minus_one);
}


PPC_OP(test_ctr_true) { T0 = (regs->ctr != 0 && (T0 & PARAM(1)) != 0); RETURN(); }


static int tipc_nl_compat_node_dump ( struct tipc_nl_compat_msg * msg , struct nlattr * * attrs ) {
 struct tipc_node_info node_info ;
 struct nlattr * node [ TIPC_NLA_NODE_MAX + 1 ] ;
 int err ;
 if ( ! attrs [ TIPC_NLA_NODE ] ) return - EINVAL ;
 err = nla_parse_nested ( node , TIPC_NLA_NODE_MAX , attrs [ TIPC_NLA_NODE ] , NULL ) ;
 if ( err ) return err ;
 node_info . addr = htonl ( nla_get_u32 ( node [ TIPC_NLA_NODE_ADDR ] ) ) ;
 node_info . up = htonl ( nla_get_flag ( node [ TIPC_NLA_NODE_UP ] ) ) ;
 return tipc_add_tlv ( msg -> rep , TIPC_TLV_NODE_INFO , & node_info , sizeof ( node_info ) ) ;
 }


Pl_PNGFilter::decodeSub()
{
    QTC::TC("libtests", "Pl_PNGFilter decodeSub");
    unsigned char* buffer = this->cur_row + 1;
    unsigned int bpp = this->bytes_per_pixel;

    for (unsigned int i = 0; i < this->bytes_per_row; ++i)
    {
        unsigned char left = 0;

        if (i >= bpp)
        {
            left = buffer[i - bpp];
        }

        buffer[i] += left;
    }
}


void spapr_events_init(sPAPREnvironment *spapr) { spapr->epow_irq = spapr_allocate_msi(0); spapr->epow_notifier.notify = spapr_powerdown_req; qemu_register_powerdown_notifier(&spapr->epow_notifier); spapr_rtas_register("check-exception", check_exception); }


target_ulong helper_add_suov(CPUTriCoreState *env, target_ulong r1, target_ulong r2) { int64_t t1 = extract64(r1, 0, 32); int64_t t2 = extract64(r2, 0, 32); int64_t result = t1 + t2; return suov32(env, result); }


static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (track->entry) { sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); } av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS); for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } entries++; if (!group) return 0; /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; }


int main(int argc, char* argv[])
{
    if (argc != 4)
    {
	std::cerr << "Usage: rc4 hex-key infile outfile" << std::endl;
	exit(2);
    }

    char* hexkey = argv[1];
    char* infilename = argv[2];
    char* outfilename = argv[3];
    unsigned int hexkeylen = strlen(hexkey);
    unsigned int keylen = hexkeylen / 2;
    unsigned char* key = new unsigned char[keylen + 1];
    key[keylen] = '\0';

    FILE* infile = QUtil::safe_fopen(infilename, "rb");
    for (unsigned int i = 0; i < strlen(hexkey); i += 2)
    {
	char t[3];
	t[0] = hexkey[i];
	t[1] = hexkey[i + 1];
	t[2] = '\0';

	long val = strtol(t, 0, 16);
	key[i/2] = static_cast<unsigned char>(val);
    }

    FILE* outfile = QUtil::safe_fopen(outfilename, "wb");
    Pl_StdioFile* out = new Pl_StdioFile("stdout", outfile);
    // Use a small buffer size (64) for testing
    Pl_RC4* rc4 = new Pl_RC4("rc4", out, key, keylen, 64);
    delete [] key;

    // 64 < buffer size < 512, buffer_size is not a power of 2 for testing
    unsigned char buf[100];
    bool done = false;
    while (! done)
    {
	size_t len = fread(buf, 1, sizeof(buf), infile);
	if (len <= 0)
	{
	    done = true;
	}
	else
	{
	    rc4->write(buf, len);
	}
    }
    rc4->finish();
    delete rc4;
    delete out;
    fclose(infile);
    fclose(outfile);
    return 0;
}


QPDF::dumpHSharedObject()
{
    HSharedObject& t = this->m->shared_object_hints;
    *this->m->out_stream
	<< "first_shared_obj: " << t.first_shared_obj
	<< std::endl
	<< "first_shared_offset: " << adjusted_offset(t.first_shared_offset)
	<< std::endl
	<< "nshared_first_page: " << t.nshared_first_page
	<< std::endl
	<< "nshared_total: " << t.nshared_total
	<< std::endl
	<< "nbits_nobjects: " << t.nbits_nobjects
	<< std::endl
	<< "min_group_length: " << t.min_group_length
	<< std::endl
	<< "nbits_delta_group_length: " << t.nbits_delta_group_length
	<< std::endl;

    for (int i = 0; i < t.nshared_total; ++i)
    {
	HSharedObjectEntry& se = t.entries.at(i);
	*this->m->out_stream
            << "Shared Object " << i << ":" << std::endl
            << "  group length: "
            << se.delta_group_length + t.min_group_length << std::endl;
	// PDF spec says signature present nobjects_minus_one are
	// always 0, so print them only if they have a non-zero value.
	if (se.signature_present)
	{
	    *this->m->out_stream << "  signature present" << std::endl;
	}
	if (se.nobjects_minus_one != 0)
	{
	    *this->m->out_stream << "  nobjects: "
                                 << se.nobjects_minus_one + 1 << std::endl;
	}
    }
}


void proto_reg_handoff_gsm_a_dtap ( void ) {
 dissector_handle_t dtap_handle ;
 dtap_handle = find_dissector ( "gsm_a_dtap" ) ;
 dissector_add_uint ( "bssap.pdu_type" , BSSAP_PDU_TYPE_DTAP , dtap_handle ) ;
 dissector_add_uint ( "ranap.nas_pdu" , BSSAP_PDU_TYPE_DTAP , dtap_handle ) ;
 dissector_add_uint ( "llcgprs.sapi" , 1 , dtap_handle ) ;
 dissector_add_uint ( "llcgprs.sapi" , 7 , dtap_handle ) ;
 dissector_add_uint ( "lapdm.sapi" , 0 , dtap_handle ) ;
 dissector_add_uint ( "lapdm.sapi" , 3 , dtap_handle ) ;
 gsm_map_handle = find_dissector_add_dependency ( "gsm_map" , proto_a_dtap ) ;
 rp_handle = find_dissector_add_dependency ( "gsm_a_rp" , proto_a_dtap ) ;
 }


QUtil::utf16_to_utf8(std::string const& val)
{
    std::string result;
    // This code uses unsigned long and unsigned short to hold
    // codepoint values. It requires unsigned long to be at least
    // 32 bits and unsigned short to be at least 16 bits, but it
    // will work fine if they are larger.
    unsigned long codepoint = 0L;
    size_t len = val.length();
    size_t start = 0;
    if (is_utf16(val))
    {
        start += 2;
    }
    // If the string has an odd number of bytes, the last byte is
    // ignored.
    for (unsigned int i = start; i < len; i += 2)
    {
        // Convert from UTF16-BE.  If we get a malformed
        // codepoint, this code will generate incorrect output
        // without giving a warning.  Specifically, a high
        // codepoint not followed by a low codepoint will be
        // discarded, and a low codepoint not preceded by a high
        // codepoint will just get its low 10 bits output.
        unsigned short bits =
            (static_cast<unsigned char>(val.at(i)) << 8) +
            static_cast<unsigned char>(val.at(i+1));
        if ((bits & 0xFC00) == 0xD800)
        {
            codepoint = 0x10000 + ((bits & 0x3FF) << 10);
            continue;
        }
        else if ((bits & 0xFC00) == 0xDC00)
        {
            if (codepoint != 0)
            {
                QTC::TC("qpdf", "QUtil non-trivial UTF-16");
            }
            codepoint += bits & 0x3FF;
        }
        else
        {
            codepoint = bits;
        }

        result += QUtil::toUTF8(codepoint);
        codepoint = 0;
    }
    return result;
}


static sig_handler signal_handler ( int sig ) {
 fprintf ( stderr , "mysqltest got " SIGNAL_FMT "\n" , sig ) ;
 dump_backtrace ( ) ;
 fprintf ( stderr , "Writing a core file...\n" ) ;
 fflush ( stderr ) ;
 my_write_core ( sig ) ;
 # ifndef __WIN__ exit ( 1 ) ;
 # endif }


int nntp_check_msgid ( struct Context * ctx , const char * msgid ) {
 struct NntpData * nntp_data = ctx -> data ;
 char buf [ LONG_STRING ] ;
 FILE * fp = mutt_file_mkstemp ( ) ;
 if ( ! fp ) {
 mutt_perror ( "mutt_file_mkstemp() failed!" ) ;
 return - 1 ;
 }
 snprintf ( buf , sizeof ( buf ) , "HEAD %s\r\n" , msgid ) ;
 int rc = nntp_fetch_lines ( nntp_data , buf , sizeof ( buf ) , NULL , fetch_tempfile , fp ) ;
 if ( rc ) {
 mutt_file_fclose ( & fp ) ;
 if ( rc < 0 ) return - 1 ;
 if ( mutt_str_strncmp ( "430" , buf , 3 ) == 0 ) return 1 ;
 mutt_error ( "HEAD: %s" , buf ) ;
 return - 1 ;
 }
 if ( ctx -> msgcount == ctx -> hdrmax ) mx_alloc_memory ( ctx ) ;
 struct Header * hdr = ctx -> hdrs [ ctx -> msgcount ] = mutt_header_new ( ) ;
 hdr -> data = mutt_mem_calloc ( 1 , sizeof ( struct NntpHeaderData ) ) ;
 hdr -> env = mutt_rfc822_read_header ( fp , hdr , 0 , 0 ) ;
 mutt_file_fclose ( & fp ) ;
 if ( hdr -> env -> xref ) nntp_parse_xref ( ctx , hdr ) ;
 else {
 snprintf ( buf , sizeof ( buf ) , "STAT %s\r\n" , msgid ) ;
 if ( nntp_query ( nntp_data , buf , sizeof ( buf ) ) < 0 ) {
 mutt_header_free ( & hdr ) ;
 return - 1 ;
 }
 sscanf ( buf + 4 , ANUM , & NHDR ( hdr ) -> article_num ) ;
 }
 hdr -> read = false ;
 hdr -> old = false ;
 hdr -> deleted = false ;
 hdr -> changed = true ;
 hdr -> received = hdr -> date_sent ;
 hdr -> index = ctx -> msgcount ++ ;
 mx_update_context ( ctx , 1 ) ;
 return 0 ;
 }


void vp9_quantize_fp_c ( const int16_t * coeff_ptr , intptr_t count , int skip_block , const int16_t * zbin_ptr , const int16_t * round_ptr , const int16_t * quant_ptr , const int16_t * quant_shift_ptr , int16_t * qcoeff_ptr , int16_t * dqcoeff_ptr , const int16_t * dequant_ptr , int zbin_oq_value , uint16_t * eob_ptr , const int16_t * scan , const int16_t * iscan ) {
 int i , eob = - 1 ;
 ( void ) zbin_ptr ;
 ( void ) quant_shift_ptr ;
 ( void ) zbin_oq_value ;
 ( void ) iscan ;
 vpx_memset ( qcoeff_ptr , 0 , count * sizeof ( int16_t ) ) ;
 vpx_memset ( dqcoeff_ptr , 0 , count * sizeof ( int16_t ) ) ;
 if ( ! skip_block ) {
 for ( i = 0 ;
 i < count ;
 i ++ ) {
 const int rc = scan [ i ] ;
 const int coeff = coeff_ptr [ rc ] ;
 const int coeff_sign = ( coeff >> 31 ) ;
 const int abs_coeff = ( coeff ^ coeff_sign ) - coeff_sign ;
 int tmp = clamp ( abs_coeff + round_ptr [ rc != 0 ] , INT16_MIN , INT16_MAX ) ;
 tmp = ( tmp * quant_ptr [ rc != 0 ] ) >> 16 ;
 qcoeff_ptr [ rc ] = ( tmp ^ coeff_sign ) - coeff_sign ;
 dqcoeff_ptr [ rc ] = qcoeff_ptr [ rc ] * dequant_ptr [ rc != 0 ] ;
 if ( tmp ) eob = i ;
 }
 }
 * eob_ptr = eob + 1 ;
 }


skip_buffer_input_data(j_decompress_ptr cinfo, long num_bytes)
{
    if (num_bytes < 0)
    {
        throw std::runtime_error(
            "reading jpeg: jpeg library requested"
            " skipping a negative number of bytes");
    }
    size_t to_skip = static_cast<size_t>(num_bytes);
    if ((to_skip > 0) && (to_skip <= cinfo->src->bytes_in_buffer))
    {
        cinfo->src->next_input_byte += to_skip;
        cinfo->src->bytes_in_buffer -= to_skip;
    }
    else if (to_skip != 0)
    {
        cinfo->src->next_input_byte += cinfo->src->bytes_in_buffer;
        cinfo->src->bytes_in_buffer = 0;
    }
}


int ieee80211_radiotap_iterator_next ( struct ieee80211_radiotap_iterator * iterator ) {
 while ( 1 ) {
 int hit = 0 ;
 int pad , align , size , subns ;
 guint32 oui ;
 if ( ( iterator -> _arg_index % 32 ) == IEEE80211_RADIOTAP_EXT && ! ( iterator -> _bitmap_shifter & 1 ) ) return - ENOENT ;
 if ( ! ( iterator -> _bitmap_shifter & 1 ) ) goto next_entry ;
 switch ( iterator -> _arg_index % 32 ) {
 case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE : case IEEE80211_RADIOTAP_EXT : align = 1 ;
 size = 0 ;
 break ;
 case IEEE80211_RADIOTAP_VENDOR_NAMESPACE : align = 2 ;
 size = 6 ;
 break ;
 default : # ifdef RADIOTAP_SUPPORT_OVERRIDES if ( find_override ( iterator , & align , & size ) ) {
 }
 else # endif if ( ! iterator -> current_namespace || iterator -> _arg_index >= iterator -> current_namespace -> n_bits ) {
 if ( iterator -> current_namespace == & radiotap_ns ) return - ENOENT ;
 align = 0 ;
 }
 else {
 align = iterator -> current_namespace -> align_size [ iterator -> _arg_index ] . align ;
 size = iterator -> current_namespace -> align_size [ iterator -> _arg_index ] . size ;
 }
 if ( ! align ) {
 if ( ! iterator -> _next_ns_data ) return - EINVAL ;
 iterator -> _arg = iterator -> _next_ns_data ;
 iterator -> current_namespace = NULL ;
 iterator -> _next_ns_data = NULL ;
 if ( ! ITERATOR_VALID ( iterator , 0 ) ) return - EINVAL ;
 goto next_entry ;
 }
 break ;
 }
 pad = ( int ) ( ( iterator -> _arg - ( unsigned char * ) iterator -> _rtheader ) & ( align - 1 ) ) ;
 if ( pad ) iterator -> _arg += align - pad ;
 if ( iterator -> _arg_index % 32 == IEEE80211_RADIOTAP_VENDOR_NAMESPACE ) {
 int vnslen ;
 if ( ! ITERATOR_VALID ( iterator , size ) ) return - EINVAL ;
 oui = ( * iterator -> _arg << 16 ) | ( * ( iterator -> _arg + 1 ) << 8 ) | * ( iterator -> _arg + 2 ) ;
 subns = * ( iterator -> _arg + 3 ) ;
 find_ns ( iterator , oui , subns ) ;
 vnslen = get_unaligned_le16 ( iterator -> _arg + 4 ) ;
 iterator -> _next_ns_data = iterator -> _arg + size + vnslen ;
 if ( ! iterator -> current_namespace ) size += vnslen ;
 }
 iterator -> this_arg_index = iterator -> _arg_index ;
 iterator -> this_arg = iterator -> _arg ;
 iterator -> this_arg_size = size ;
 iterator -> _arg += size ;
 if ( ! ITERATOR_VALID ( iterator , 0 ) ) return - EINVAL ;
 switch ( iterator -> _arg_index % 32 ) {
 case IEEE80211_RADIOTAP_VENDOR_NAMESPACE : iterator -> _reset_on_ext = 1 ;
 iterator -> is_radiotap_ns = 0 ;
 iterator -> this_arg_index = IEEE80211_RADIOTAP_VENDOR_NAMESPACE ;
 if ( ! iterator -> current_namespace ) hit = 1 ;
 goto next_entry ;
 case IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE : iterator -> _reset_on_ext = 1 ;
 iterator -> current_namespace = & radiotap_ns ;
 iterator -> is_radiotap_ns = 1 ;
 goto next_entry ;
 case IEEE80211_RADIOTAP_EXT : iterator -> _bitmap_shifter = get_unaligned_le32 ( iterator -> _next_bitmap ) ;
 iterator -> _next_bitmap ++ ;
 if ( iterator -> _reset_on_ext ) iterator -> _arg_index = 0 ;
 else iterator -> _arg_index ++ ;
 iterator -> _reset_on_ext = 0 ;
 break ;
 default : hit = 1 ;
 next_entry : iterator -> _bitmap_shifter >>= 1 ;
 iterator -> _arg_index ++ ;
 }
 if ( hit ) return 0 ;
 }
 }


QPDFPageData::QPDFPageData(std::string const& filename,
                           QPDF* qpdf,
                           char const* range) :
    filename(filename),
    qpdf(qpdf),
    orig_pages(qpdf->getAllPages())
{
    try
    {
        this->selected_pages =
            QUtil::parse_numrange(range, this->orig_pages.size());
    }
    catch (std::runtime_error& e)
    {
        usageExit("parsing numeric range for " + filename + ": " + e.what());
    }
}


ImageInverter::provideStreamData(int objid, int generation,
				 Pipeline* pipeline)
{
    // Use the object and generation number supplied to look up the
    // image data.  Then invert the image data and write the inverted
    // data to the pipeline.
    PointerHolder<Buffer> data =
        this->image_data[QPDFObjGen(objid, generation)];
    size_t size = data->getSize();
    unsigned char* buf = data->getBuffer();
    unsigned char ch;
    for (size_t i = 0; i < size; ++i)
    {
	ch = static_cast<unsigned char>(0xff) - buf[i];
	pipeline->write(&ch, 1);
    }
    pipeline->finish();
}


static int usb_net_handle_data(USBDevice *dev, USBPacket *p) { USBNetState *s = (USBNetState *) dev; int ret = 0; switch(p->pid) { case USB_TOKEN_IN: switch (p->devep) { case 1: ret = usb_net_handle_statusin(s, p); break; case 2: ret = usb_net_handle_datain(s, p); break; default: goto fail; } break; case USB_TOKEN_OUT: switch (p->devep) { case 2: ret = usb_net_handle_dataout(s, p); break; default: goto fail; } break; default: fail: ret = USB_RET_STALL; break; } if (ret == USB_RET_STALL) fprintf(stderr, "usbnet: failed data transaction: " "pid 0x%x ep 0x%x len 0x%x\n", p->pid, p->devep, p->len); return ret; }


void mime_parser_init ( MIMEParser * parser ) {
 mime_scanner_init ( & parser -> m_scanner ) ;
 _mime_parser_init ( parser ) ;
 }


static void assert_codec_experimental(AVCodecContext *c, int encoder) { const char *codec_string = encoder ? "encoder" : "decoder"; AVCodec *codec; if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL && c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(NULL, AV_LOG_ERROR, "%s '%s' is experimental and might produce bad " "results.\nAdd '-strict experimental' if you want to use it.\n", codec_string, c->codec->name); codec = encoder ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL)) av_log(NULL, AV_LOG_ERROR, "Or use the non experimental %s '%s'.\n", codec_string, codec->name); ffmpeg_exit(1); } }


BitStream::skipToNextByte()
{
    if (bit_offset != 7)
    {
	unsigned int bits_to_skip = bit_offset + 1;
	if (bits_available < bits_to_skip)
	{
	    throw std::logic_error(
		"INTERNAL ERROR: overflow skipping to next byte in bitstream");
	}
	bit_offset = 7;
	++p;
	bits_available -= bits_to_skip;
    }
}


static gint dissect_rtp ( tvbuff_t * tvb , packet_info * pinfo , proto_tree * tree , void * data _U_ ) {
 proto_item * ti = NULL ;
 proto_tree * volatile rtp_tree = NULL ;
 proto_tree * rtp_csrc_tree = NULL ;
 proto_tree * rtp_hext_tree = NULL ;
 guint8 octet1 , octet2 ;
 unsigned int version ;
 gboolean padding_set ;
 gboolean extension_set ;
 unsigned int csrc_count ;
 gboolean marker_set ;
 unsigned int payload_type ;
 gchar * payload_type_str = NULL ;
 gboolean is_srtp = FALSE ;
 unsigned int i = 0 ;
 unsigned int hdr_extension_len = 0 ;
 unsigned int hdr_extension_id = 0 ;
 volatile unsigned int padding_count ;
 gint length , reported_length ;
 int data_len ;
 volatile unsigned int offset = 0 ;
 guint16 seq_num ;
 guint32 timestamp ;
 guint32 sync_src ;
 guint32 csrc_item ;
 struct _rtp_conversation_info * p_conv_data = NULL ;
 unsigned int hdrext_offset = 0 ;
 tvbuff_t * newtvb = NULL ;
 const char * pt = NULL ;
 static struct _rtp_info rtp_info_arr [ 4 ] ;
 static int rtp_info_current = 0 ;
 struct _rtp_info * rtp_info ;
 rtp_info_current ++ ;
 if ( rtp_info_current == 4 ) {
 rtp_info_current = 0 ;
 }
 rtp_info = & rtp_info_arr [ rtp_info_current ] ;
 octet1 = tvb_get_guint8 ( tvb , offset ) ;
 version = RTP_VERSION ( octet1 ) ;
 if ( version == 0 ) {
 switch ( global_rtp_version0_type ) {
 case RTP0_STUN : call_dissector ( stun_handle , tvb , pinfo , tree ) ;
 return tvb_length ( tvb ) ;
 case RTP0_CLASSICSTUN : call_dissector ( classicstun_handle , tvb , pinfo , tree ) ;
 return tvb_length ( tvb ) ;
 case RTP0_T38 : call_dissector ( t38_handle , tvb , pinfo , tree ) ;
 return tvb_length ( tvb ) ;
 case RTP0_SPRT : call_dissector ( sprt_handle , tvb , pinfo , tree ) ;
 return tvb_length ( tvb ) ;
 case RTP0_INVALID : if ( ! ( tvb_memeql ( tvb , 4 , "ZRTP" , 4 ) ) ) {
 call_dissector ( zrtp_handle , tvb , pinfo , tree ) ;
 return tvb_length ( tvb ) ;
 }
 default : ;
 }
 }
 rtp_info -> info_version = version ;
 if ( version != 2 ) {
 col_set_str ( pinfo -> cinfo , COL_PROTOCOL , "RTP" ) ;
 col_add_fstr ( pinfo -> cinfo , COL_INFO , "Unknown RTP version %u" , version ) ;
 if ( tree ) {
 ti = proto_tree_add_item ( tree , proto_rtp , tvb , offset , - 1 , ENC_NA ) ;
 rtp_tree = proto_item_add_subtree ( ti , ett_rtp ) ;
 proto_tree_add_uint ( rtp_tree , hf_rtp_version , tvb , offset , 1 , octet1 ) ;
 }
 return offset ;
 }
 padding_set = RTP_PADDING ( octet1 ) ;
 extension_set = RTP_EXTENSION ( octet1 ) ;
 csrc_count = RTP_CSRC_COUNT ( octet1 ) ;
 octet2 = tvb_get_guint8 ( tvb , offset + 1 ) ;
 marker_set = RTP_MARKER ( octet2 ) ;
 payload_type = RTP_PAYLOAD_TYPE ( octet2 ) ;
 if ( marker_set && payload_type >= FIRST_RTCP_CONFLICT_PAYLOAD_TYPE && payload_type <= LAST_RTCP_CONFLICT_PAYLOAD_TYPE ) {
 call_dissector ( rtcp_handle , tvb , pinfo , tree ) ;
 return tvb_length ( tvb ) ;
 }
 seq_num = tvb_get_ntohs ( tvb , offset + 2 ) ;
 timestamp = tvb_get_ntohl ( tvb , offset + 4 ) ;
 sync_src = tvb_get_ntohl ( tvb , offset + 8 ) ;
 rtp_info -> info_padding_set = padding_set ;
 rtp_info -> info_padding_count = 0 ;
 rtp_info -> info_marker_set = marker_set ;
 rtp_info -> info_is_video = FALSE ;
 rtp_info -> info_payload_type = payload_type ;
 rtp_info -> info_seq_num = seq_num ;
 rtp_info -> info_timestamp = timestamp ;
 rtp_info -> info_sync_src = sync_src ;
 rtp_info -> info_is_srtp = FALSE ;
 rtp_info -> info_setup_frame_num = 0 ;
 rtp_info -> info_payload_type_str = NULL ;
 rtp_info -> info_payload_rate = 0 ;
 length = tvb_length_remaining ( tvb , offset ) ;
 reported_length = tvb_reported_length_remaining ( tvb , offset ) ;
 if ( reported_length >= 0 && length >= reported_length ) {
 rtp_info -> info_all_data_present = TRUE ;
 rtp_info -> info_data_len = reported_length ;
 rtp_info -> info_data = tvb_get_ptr ( tvb , 0 , - 1 ) ;
 }
 else {
 rtp_info -> info_all_data_present = FALSE ;
 rtp_info -> info_data_len = 0 ;
 rtp_info -> info_data = NULL ;
 }
 get_conv_info ( pinfo , rtp_info ) ;
 p_conv_data = ( struct _rtp_conversation_info * ) p_get_proto_data ( wmem_file_scope ( ) , pinfo , proto_rtp , 0 ) ;
 if ( p_conv_data ) rtp_info -> info_is_video = p_conv_data -> is_video ;
 if ( p_conv_data && p_conv_data -> srtp_info ) is_srtp = TRUE ;
 rtp_info -> info_is_srtp = is_srtp ;
 col_set_str ( pinfo -> cinfo , COL_PROTOCOL , ( is_srtp ) ? "SRTP" : "RTP" ) ;
 p_conv_data = ( struct _rtp_conversation_info * ) p_get_proto_data ( wmem_file_scope ( ) , pinfo , proto_rtp , 0 ) ;
 # if 0 if ( p_conv_data && p_conv_data -> srtp_info ) {
 srtp_info = p_conv_data -> srtp_info ;
 if ( rtp_info -> info_all_data_present ) {
 srtp_offset = rtp_info -> info_data_len - srtp_info -> mki_len - srtp_info -> auth_tag_len ;
 }
 }
 # endif if ( p_conv_data && p_conv_data -> bta2dp_info && p_conv_data -> bta2dp_info -> codec_dissector ) {
 rtp_info -> info_payload_type_str = ( const char * ) dissector_handle_get_short_name ( p_conv_data -> bta2dp_info -> codec_dissector ) ;
 }
 else if ( p_conv_data && p_conv_data -> btvdp_info && p_conv_data -> btvdp_info -> codec_dissector ) {
 rtp_info -> info_payload_type_str = ( const char * ) dissector_handle_get_short_name ( p_conv_data -> btvdp_info -> codec_dissector ) ;
 }
 if ( ( payload_type > 95 ) && ( payload_type < 128 ) ) {
 if ( p_conv_data && p_conv_data -> rtp_dyn_payload ) {
 encoding_name_and_rate_t * encoding_name_and_rate_pt = NULL ;
 # ifdef DEBUG_CONVERSATION rtp_dump_dyn_payload ( p_conv_data -> rtp_dyn_payload ) ;
 # endif DPRINT ( ( "looking up conversation data for dyn_pt=%d" , payload_type ) ) ;
 encoding_name_and_rate_pt = ( encoding_name_and_rate_t * ) g_hash_table_lookup ( p_conv_data -> rtp_dyn_payload , & payload_type ) ;
 DPRINT ( ( "did %sfind conversation data for dyn_pt=%d" , encoding_name_and_rate_pt ? "" : "not " , payload_type ) ) ;
 if ( encoding_name_and_rate_pt ) {
 DPRINT ( ( "found conversation data for dyn_pt=%d, enc_name=%s" , payload_type , encoding_name_and_rate_pt -> encoding_name ) ) ;
 rtp_info -> info_payload_type_str = payload_type_str = encoding_name_and_rate_pt -> encoding_name ;
 rtp_info -> info_payload_rate = encoding_name_and_rate_pt -> sample_rate ;
 }
 }
 }
 if ( p_conv_data && p_conv_data -> bta2dp_info ) {
 pt = ( p_conv_data -> bta2dp_info -> codec_dissector ) ? dissector_handle_get_short_name ( p_conv_data -> bta2dp_info -> codec_dissector ) : "Unknown" ;
 }
 else if ( p_conv_data && p_conv_data -> btvdp_info ) {
 pt = ( p_conv_data -> btvdp_info -> codec_dissector ) ? dissector_handle_get_short_name ( p_conv_data -> btvdp_info -> codec_dissector ) : "Unknown" ;
 }
 else {
 pt = ( payload_type_str ? payload_type_str : val_to_str_ext ( payload_type , & rtp_payload_type_vals_ext , "Unknown (%u)" ) ) ;
 }
 col_add_fstr ( pinfo -> cinfo , COL_INFO , "PT=%s, SSRC=0x%X, Seq=%u, Time=%u%s" , pt , sync_src , seq_num , timestamp , marker_set ? ", Mark" : "" ) ;
 if ( tree ) {
 proto_tree * item ;
 ti = proto_tree_add_item ( tree , proto_rtp , tvb , offset , - 1 , ENC_NA ) ;
 rtp_tree = proto_item_add_subtree ( ti , ett_rtp ) ;
 if ( global_rtp_show_setup_info ) {
 show_setup_info ( tvb , pinfo , rtp_tree ) ;
 }
 proto_tree_add_uint ( rtp_tree , hf_rtp_version , tvb , offset , 1 , octet1 ) ;
 proto_tree_add_boolean ( rtp_tree , hf_rtp_padding , tvb , offset , 1 , octet1 ) ;
 proto_tree_add_boolean ( rtp_tree , hf_rtp_extension , tvb , offset , 1 , octet1 ) ;
 proto_tree_add_uint ( rtp_tree , hf_rtp_csrc_count , tvb , offset , 1 , octet1 ) ;
 offset ++ ;
 proto_tree_add_boolean ( rtp_tree , hf_rtp_marker , tvb , offset , 1 , octet2 ) ;
 proto_tree_add_uint_format ( rtp_tree , hf_rtp_payload_type , tvb , offset , 1 , octet2 , "Payload type: %s (%u)" , pt , payload_type ) ;
 offset ++ ;
 proto_tree_add_uint ( rtp_tree , hf_rtp_seq_nr , tvb , offset , 2 , seq_num ) ;
 if ( p_conv_data != NULL ) {
 item = proto_tree_add_uint ( rtp_tree , hf_rtp_ext_seq_nr , tvb , offset , 2 , p_conv_data -> extended_seqno ) ;
 PROTO_ITEM_SET_GENERATED ( item ) ;
 }
 offset += 2 ;
 proto_tree_add_uint ( rtp_tree , hf_rtp_timestamp , tvb , offset , 4 , timestamp ) ;
 offset += 4 ;
 proto_tree_add_uint ( rtp_tree , hf_rtp_ssrc , tvb , offset , 4 , sync_src ) ;
 offset += 4 ;
 }
 else {
 offset += 12 ;
 }
 if ( csrc_count > 0 ) {
 ti = proto_tree_add_item ( rtp_tree , hf_rtp_csrc_items , tvb , offset , csrc_count * 4 , ENC_NA ) ;
 proto_item_append_text ( ti , " (%u items)" , csrc_count ) ;
 rtp_csrc_tree = proto_item_add_subtree ( ti , ett_csrc_list ) ;
 for ( i = 0 ;
 i < csrc_count ;
 i ++ ) {
 csrc_item = tvb_get_ntohl ( tvb , offset ) ;
 proto_tree_add_uint_format ( rtp_csrc_tree , hf_rtp_csrc_item , tvb , offset , 4 , csrc_item , "CSRC item %d: 0x%X" , i , csrc_item ) ;
 offset += 4 ;
 }
 }
 if ( extension_set ) {
 hdr_extension_id = tvb_get_ntohs ( tvb , offset ) ;
 if ( tree ) proto_tree_add_uint ( rtp_tree , hf_rtp_prof_define , tvb , offset , 2 , hdr_extension_id ) ;
 offset += 2 ;
 hdr_extension_len = tvb_get_ntohs ( tvb , offset ) ;
 if ( tree ) proto_tree_add_uint ( rtp_tree , hf_rtp_length , tvb , offset , 2 , hdr_extension_len ) ;
 offset += 2 ;
 if ( hdr_extension_len > 0 ) {
 if ( tree ) {
 ti = proto_tree_add_item ( rtp_tree , hf_rtp_hdr_exts , tvb , offset , hdr_extension_len * 4 , ENC_NA ) ;
 rtp_hext_tree = proto_item_add_subtree ( ti , ett_hdr_ext ) ;
 }
 newtvb = tvb_new_subset ( tvb , offset , hdr_extension_len * 4 , hdr_extension_len * 4 ) ;
 if ( hdr_extension_id == RTP_RFC5215_ONE_BYTE_SIG ) {
 dissect_rtp_hext_rfc5215_onebyte ( newtvb , pinfo , rtp_hext_tree ) ;
 }
 else if ( ( hdr_extension_id & RTP_RFC5215_TWO_BYTE_MASK ) == RTP_RFC5215_TWO_BYTE_SIG ) {
 dissect_rtp_hext_rfc5215_twobytes ( tvb , offset - 4 , hdr_extension_id , newtvb , pinfo , rtp_hext_tree ) ;
 }
 else {
 if ( ! ( dissector_try_uint ( rtp_hdr_ext_dissector_table , hdr_extension_id , newtvb , pinfo , rtp_hext_tree ) ) ) {
 hdrext_offset = offset ;
 for ( i = 0 ;
 i < hdr_extension_len ;
 i ++ ) {
 if ( tree ) proto_tree_add_uint ( rtp_hext_tree , hf_rtp_hdr_ext , tvb , hdrext_offset , 4 , tvb_get_ntohl ( tvb , hdrext_offset ) ) ;
 hdrext_offset += 4 ;
 }
 }
 }
 }
 offset += hdr_extension_len * 4 ;
 }
 if ( padding_set ) {
 if ( tvb_length ( tvb ) < tvb_reported_length ( tvb ) ) {
 if ( tree ) proto_tree_add_text ( rtp_tree , tvb , 0 , 0 , "Frame has padding, but not all the frame data was captured" ) ;
 call_dissector ( data_handle , tvb_new_subset_remaining ( tvb , offset ) , pinfo , rtp_tree ) ;
 return tvb_length ( tvb ) ;
 }
 padding_count = tvb_get_guint8 ( tvb , tvb_reported_length ( tvb ) - 1 ) ;
 data_len = tvb_reported_length_remaining ( tvb , offset ) - padding_count ;
 rtp_info -> info_payload_offset = offset ;
 rtp_info -> info_payload_len = tvb_length_remaining ( tvb , offset ) ;
 rtp_info -> info_padding_count = padding_count ;
 if ( p_conv_data && p_conv_data -> bta2dp_info ) {
 if ( p_conv_data -> bta2dp_info -> codec_dissector == sbc_handle ) {
 rtp_info -> info_payload_offset += 1 ;
 rtp_info -> info_payload_len -= 1 ;
 }
 if ( p_conv_data -> bta2dp_info -> content_protection_type == BTAVDTP_CONTENT_PROTECTION_TYPE_SCMS_T ) {
 rtp_info -> info_payload_offset += 1 ;
 rtp_info -> info_payload_len -= 1 ;
 }
 }
 if ( p_conv_data && p_conv_data -> btvdp_info && p_conv_data -> bta2dp_info -> content_protection_type == BTAVDTP_CONTENT_PROTECTION_TYPE_SCMS_T ) {
 rtp_info -> info_payload_offset += 1 ;
 rtp_info -> info_payload_len -= 1 ;
 }
 if ( data_len > 0 ) {
 TRY {
 dissect_rtp_data ( tvb , pinfo , tree , rtp_tree , offset , data_len , data_len , payload_type ) ;
 }
 CATCH_ALL {
 if ( ! pinfo -> flags . in_error_pkt ) tap_queue_packet ( rtp_tap , pinfo , rtp_info ) ;
 RETHROW ;
 }
 ENDTRY ;
 offset += data_len ;
 }
 else if ( data_len < 0 ) {
 padding_count = tvb_reported_length_remaining ( tvb , offset ) ;
 }
 if ( padding_count > 1 ) {
 if ( tree ) proto_tree_add_item ( rtp_tree , hf_rtp_padding_data , tvb , offset , padding_count - 1 , ENC_NA ) ;
 offset += padding_count - 1 ;
 }
 if ( tree ) proto_tree_add_item ( rtp_tree , hf_rtp_padding_count , tvb , offset , 1 , ENC_BIG_ENDIAN ) ;
 }
 else {
 rtp_info -> info_payload_offset = offset ;
 rtp_info -> info_payload_len = tvb_length_remaining ( tvb , offset ) ;
 if ( p_conv_data && p_conv_data -> bta2dp_info ) {
 if ( p_conv_data -> bta2dp_info -> codec_dissector == sbc_handle ) {
 rtp_info -> info_payload_offset += 1 ;
 rtp_info -> info_payload_len -= 1 ;
 }
 if ( p_conv_data -> bta2dp_info -> content_protection_type == BTAVDTP_CONTENT_PROTECTION_TYPE_SCMS_T ) {
 rtp_info -> info_payload_offset += 1 ;
 rtp_info -> info_payload_len -= 1 ;
 }
 }
 if ( p_conv_data && p_conv_data -> btvdp_info && p_conv_data -> bta2dp_info -> content_protection_type == BTAVDTP_CONTENT_PROTECTION_TYPE_SCMS_T ) {
 rtp_info -> info_payload_offset += 1 ;
 rtp_info -> info_payload_len -= 1 ;
 }
 if ( tvb_reported_length_remaining ( tvb , offset ) > 0 ) {
 TRY {
 dissect_rtp_data ( tvb , pinfo , tree , rtp_tree , offset , tvb_length_remaining ( tvb , offset ) , tvb_reported_length_remaining ( tvb , offset ) , payload_type ) ;
 }
 CATCH_ALL {
 if ( ! pinfo -> flags . in_error_pkt ) tap_queue_packet ( rtp_tap , pinfo , rtp_info ) ;
 RETHROW ;
 }
 ENDTRY ;
 }
 }
 if ( ! pinfo -> flags . in_error_pkt ) tap_queue_packet ( rtp_tap , pinfo , rtp_info ) ;
 return offset ;
 }


static void unassigned_mem_writew(void *opaque, target_phys_addr_t addr, uint32_t val) { #ifdef DEBUG_UNASSIGNED printf("Unassigned mem write " TARGET_FMT_plx " = 0x%x\n", addr, val); #endif #if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE) do_unassigned_access(addr, 1, 0, 0, 2); #endif }


TSSslConnection TSVConnSSLConnectionGet ( TSVConn sslp ) {
 TSSslConnection ssl = nullptr ;
 NetVConnection * vc = reinterpret_cast < NetVConnection * > ( sslp ) ;
 SSLNetVConnection * ssl_vc = dynamic_cast < SSLNetVConnection * > ( vc ) ;
 if ( ssl_vc != nullptr ) {
 ssl = reinterpret_cast < TSSslConnection > ( ssl_vc -> ssl ) ;
 }
 return ssl ;
 }


const gx_device_memory * gdev_mem_word_device_for_bits ( int bits_per_pixel ) {
 return ( ( uint ) bits_per_pixel > 64 ? ( const gx_device_memory * ) 0 : mem_word_devices [ bits_per_pixel ] ) ;
 }


    WindowsCryptProvider()
    {
        if (!CryptAcquireContext(&crypt_prov,
                                 "Container",
                                 NULL,
                                 PROV_RSA_FULL,
                                 0))
        {
#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \
     defined(__clang__))
#           pragma GCC diagnostic push
#           pragma GCC diagnostic ignored "-Wold-style-cast"
#           pragma GCC diagnostic ignored "-Wsign-compare"
#endif
            if (GetLastError() == NTE_BAD_KEYSET)
#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \
     defined(__clang__))
#           pragma GCC diagnostic pop
#endif
            {
                if (! CryptAcquireContext(&crypt_prov,
                                         "Container",
                                         NULL,
                                         PROV_RSA_FULL,
                                         CRYPT_NEWKEYSET))
                {
                    throw std::runtime_error(
                        "unable to acquire crypt context with new keyset");
                }
            }
            else
            {
                throw std::runtime_error("unable to acquire crypt context");
            }
        }
    }


static void set_good_speed_feature ( VP9_COMP * cpi , VP9_COMMON * cm , SPEED_FEATURES * sf , int speed ) {
 const int boosted = frame_is_boosted ( cpi ) ;
 sf -> adaptive_rd_thresh = 1 ;
 sf -> allow_skip_recode = 1 ;
 if ( speed >= 1 ) {
 sf -> use_square_partition_only = ! frame_is_intra_only ( cm ) ;
 sf -> less_rectangular_check = 1 ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) sf -> disable_split_mask = cm -> show_frame ? DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT ;
 else sf -> disable_split_mask = DISABLE_COMPOUND_SPLIT ;
 sf -> use_rd_breakout = 1 ;
 sf -> adaptive_motion_search = 1 ;
 sf -> mv . auto_mv_step_size = 1 ;
 sf -> adaptive_rd_thresh = 2 ;
 sf -> mv . subpel_iters_per_step = 1 ;
 sf -> mode_skip_start = 10 ;
 sf -> adaptive_pred_interp_filter = 1 ;
 sf -> recode_loop = ALLOW_RECODE_KFARFGF ;
 sf -> intra_y_mode_mask [ TX_32X32 ] = INTRA_DC_H_V ;
 sf -> intra_uv_mode_mask [ TX_32X32 ] = INTRA_DC_H_V ;
 sf -> intra_y_mode_mask [ TX_16X16 ] = INTRA_DC_H_V ;
 sf -> intra_uv_mode_mask [ TX_16X16 ] = INTRA_DC_H_V ;
 sf -> tx_size_search_breakout = 1 ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) sf -> partition_search_breakout_dist_thr = ( 1 << 23 ) ;
 else sf -> partition_search_breakout_dist_thr = ( 1 << 21 ) ;
 sf -> partition_search_breakout_rate_thr = 500 ;
 }
 if ( speed >= 2 ) {
 sf -> tx_size_search_method = frame_is_boosted ( cpi ) ? USE_FULL_RD : USE_LARGESTALL ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) {
 sf -> disable_split_mask = cm -> show_frame ? DISABLE_ALL_SPLIT : DISABLE_ALL_INTER_SPLIT ;
 sf -> adaptive_pred_interp_filter = 0 ;
 }
 else {
 sf -> disable_split_mask = LAST_AND_INTRA_SPLIT_ONLY ;
 }
 sf -> reference_masking = 1 ;
 sf -> mode_search_skip_flags = FLAG_SKIP_INTRA_DIRMISMATCH | FLAG_SKIP_INTRA_BESTINTER | FLAG_SKIP_COMP_BESTINTRA | FLAG_SKIP_INTRA_LOWVAR ;
 sf -> disable_filter_search_var_thresh = 100 ;
 sf -> comp_inter_joint_search_thresh = BLOCK_SIZES ;
 sf -> auto_min_max_partition_size = CONSTRAIN_NEIGHBORING_MIN_MAX ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) sf -> partition_search_breakout_dist_thr = ( 1 << 24 ) ;
 else sf -> partition_search_breakout_dist_thr = ( 1 << 22 ) ;
 sf -> partition_search_breakout_rate_thr = 700 ;
 }
 if ( speed >= 3 ) {
 sf -> tx_size_search_method = frame_is_intra_only ( cm ) ? USE_FULL_RD : USE_LARGESTALL ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) {
 sf -> disable_split_mask = DISABLE_ALL_SPLIT ;
 sf -> schedule_mode_search = cm -> base_qindex < 220 ? 1 : 0 ;
 }
 else {
 sf -> max_intra_bsize = BLOCK_32X32 ;
 sf -> disable_split_mask = DISABLE_ALL_INTER_SPLIT ;
 sf -> schedule_mode_search = cm -> base_qindex < 175 ? 1 : 0 ;
 }
 sf -> adaptive_pred_interp_filter = 0 ;
 sf -> adaptive_mode_search = 1 ;
 sf -> cb_partition_search = ! boosted ;
 sf -> cb_pred_filter_search = 1 ;
 sf -> alt_ref_search_fp = 1 ;
 sf -> motion_field_mode_search = ! boosted ;
 sf -> recode_loop = ALLOW_RECODE_KFMAXBW ;
 sf -> adaptive_rd_thresh = 3 ;
 sf -> mode_skip_start = 6 ;
 sf -> intra_y_mode_mask [ TX_32X32 ] = INTRA_DC ;
 sf -> intra_uv_mode_mask [ TX_32X32 ] = INTRA_DC ;
 sf -> adaptive_interp_filter_search = 1 ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) sf -> partition_search_breakout_dist_thr = ( 1 << 25 ) ;
 else sf -> partition_search_breakout_dist_thr = ( 1 << 23 ) ;
 sf -> partition_search_breakout_rate_thr = 1000 ;
 }
 if ( speed >= 4 ) {
 sf -> use_square_partition_only = 1 ;
 sf -> tx_size_search_method = USE_LARGESTALL ;
 sf -> disable_split_mask = DISABLE_ALL_SPLIT ;
 sf -> mv . search_method = BIGDIA ;
 sf -> mv . subpel_search_method = SUBPEL_TREE_PRUNED ;
 sf -> adaptive_rd_thresh = 4 ;
 sf -> mode_search_skip_flags |= FLAG_EARLY_TERMINATE ;
 sf -> disable_filter_search_var_thresh = 200 ;
 sf -> use_lp32x32fdct = 1 ;
 sf -> use_fast_coef_updates = ONE_LOOP_REDUCED ;
 sf -> use_fast_coef_costing = 1 ;
 if ( MIN ( cm -> width , cm -> height ) >= 720 ) sf -> partition_search_breakout_dist_thr = ( 1 << 26 ) ;
 else sf -> partition_search_breakout_dist_thr = ( 1 << 24 ) ;
 sf -> partition_search_breakout_rate_thr = 1500 ;
 }
 if ( speed >= 5 ) {
 int i ;
 sf -> partition_search_type = FIXED_PARTITION ;
 sf -> optimize_coefficients = 0 ;
 sf -> mv . search_method = HEX ;
 sf -> disable_filter_search_var_thresh = 500 ;
 for ( i = 0 ;
 i < TX_SIZES ;
 ++ i ) {
 sf -> intra_y_mode_mask [ i ] = INTRA_DC ;
 sf -> intra_uv_mode_mask [ i ] = INTRA_DC ;
 }
 cpi -> allow_encode_breakout = ENCODE_BREAKOUT_ENABLED ;
 }
 if ( speed >= 6 ) {
 sf -> mv . reduce_first_step_size = 1 ;
 }
 }


QPDFXRefEntry::getObjStreamNumber() const
{
    if (this->type != 2)
    {
	throw std::logic_error(
	    "getObjStreamNumber called for xref entry of type != 2");
    }
    return this->field1;
}


static void read_file_into_memory(
    char const* filename,
    PointerHolder<char>& file_buf, size_t& size)
{
    FILE* f = QUtil::safe_fopen(filename, "rb");
    fseek(f, 0, SEEK_END);
    size = QUtil::tell(f);
    fseek(f, 0, SEEK_SET);
    file_buf = PointerHolder<char>(true, new char[size]);
    char* buf_p = file_buf.getPointer();
    size_t bytes_read = 0;
    size_t len = 0;
    while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0)
    {
        bytes_read += len;
    }
    if (bytes_read != size)
    {
        if (ferror(f))
        {
            throw std::runtime_error(
                std::string("failure reading file ") + filename +
                " into memory: read " +
                QUtil::uint_to_string(bytes_read) + "; wanted " +
                QUtil::uint_to_string(size));
        }
        else
        {
            throw std::logic_error(
                std::string("premature eof reading file ") + filename +
                " into memory: read " +
                QUtil::uint_to_string(bytes_read) + "; wanted " +
                QUtil::uint_to_string(size));
        }
    }
    fclose(f);
}


QPDF_Array::insertItem(int at, QPDFObjectHandle const& item)
{
    // As special case, also allow insert beyond the end
    if ((at < 0) || (at > static_cast<int>(this->items.size())))
    {
	throw std::logic_error(
	    "INTERNAL ERROR: bounds error accessing QPDF_Array element");
    }
    this->items.insert(this->items.begin() + at, item);
}


static void qapi_dealloc_type_str(Visitor *v, char **obj, const char *name, Error **errp) { g_free(*obj); }


static VALUE mFloat_to_json ( int argc , VALUE * argv , VALUE self ) {
 GENERATE_JSON ( float ) ;
 }


static void restore_cs_variables ( FILE * sql_file , const char * delimiter ) {
 fprintf ( sql_file , "/*!50003 SET character_set_client = @saved_cs_client */ %s\n" "/*!50003 SET character_set_results = @saved_cs_results */ %s\n" "/*!50003 SET collation_connection = @saved_col_connection */ %s\n" , ( const char * ) delimiter , ( const char * ) delimiter , ( const char * ) delimiter ) ;
 }


QPDF_Array::setItem(int n, QPDFObjectHandle const& oh)
{
    // Call getItem for bounds checking
    (void) getItem(n);
    this->items.at(n) = oh;
}


ArgParser::checkCompletion()
{
    // See if we're being invoked from bash completion.
    std::string bash_point_env;
    if (QUtil::get_env("COMP_LINE", &bash_line) &&
        QUtil::get_env("COMP_POINT", &bash_point_env))
    {
        int p = QUtil::string_to_int(bash_point_env.c_str());
        if ((p > 0) && (p <= static_cast<int>(bash_line.length())))
        {
            // Truncate the line. We ignore everything at or after the
            // cursor for completion purposes.
            bash_line = bash_line.substr(0, p);
        }
        // Set bash_cur and bash_prev based on bash_line rather than
        // relying on argv. This enables us to use bashcompinit to get
        // completion in zsh too since bashcompinit sets COMP_LINE and
        // COMP_POINT but doesn't invoke the command with options like
        // bash does.

        // p is equal to length of the string. Walk backwards looking
        // for the first separator. bash_cur is everything after the
        // last separator, possibly empty.
        char sep(0);
        while (--p > 0)
        {
            char ch = bash_line.at(p);
            if ((ch == ' ') || (ch == '=') || (ch == ':'))
            {
                sep = ch;
                break;
            }
        }
        bash_cur = bash_line.substr(1+p, std::string::npos);
        if ((sep == ':') || (sep == '='))
        {
            // Bash sets prev to the non-space separator if any.
            // Actually, if there are multiple separators in a row,
            // they are all included in prev, but that detail is not
            // important to us and not worth coding.
            bash_prev = bash_line.substr(p, 1);
        }
        else
        {
            // Go back to the last separator and set prev based on
            // that.
            int p1 = p;
            while (--p1 > 0)
            {
                char ch = bash_line.at(p1);
                if ((ch == ' ') || (ch == ':') || (ch == '='))
                {
                    bash_prev = bash_line.substr(p1 + 1, p - p1 - 1);
                    break;
                }
            }
        }
        if (bash_prev.empty())
        {
            bash_prev = bash_line.substr(0, p);
        }
        if (argc == 1)
        {
            // This is probably zsh using bashcompinit. There are a
            // few differences in the expected output.
            zsh_completion = true;
        }
        handleBashArguments();
        bash_completion = true;
    }
}


static void write_outfile(QPDF& pdf, Options& o)
{
    if (o.split_pages)
    {
        // Generate output file pattern
        std::string before;
        std::string after;
        size_t len = strlen(o.outfilename);
        char* num_spot = strstr(const_cast<char*>(o.outfilename), "%d");
        if (num_spot != 0)
        {
            QTC::TC("qpdf", "qpdf split-pages %d");
            before = std::string(o.outfilename, (num_spot - o.outfilename));
            after = num_spot + 2;
        }
        else if ((len >= 4) &&
                 (QUtil::strcasecmp(o.outfilename + len - 4, ".pdf") == 0))
        {
            QTC::TC("qpdf", "qpdf split-pages .pdf");
            before = std::string(o.outfilename, len - 4) + "-";
            after = o.outfilename + len - 4;
        }
        else
        {
            QTC::TC("qpdf", "qpdf split-pages other");
            before = std::string(o.outfilename) + "-";
        }

        if (! o.preserve_unreferenced_page_resources)
        {
            QPDFPageDocumentHelper dh(pdf);
            dh.removeUnreferencedResources();
        }
        QPDFPageLabelDocumentHelper pldh(pdf);
        std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();
        int pageno_len = QUtil::int_to_string(pages.size()).length();
        unsigned int num_pages = pages.size();
        for (unsigned int i = 0; i < num_pages; i += o.split_pages)
        {
            unsigned int first = i + 1;
            unsigned int last = i + o.split_pages;
            if (last > num_pages)
            {
                last = num_pages;
            }
            QPDF outpdf;
            outpdf.emptyPDF();
            for (unsigned int pageno = first; pageno <= last; ++pageno)
            {
                QPDFObjectHandle page = pages.at(pageno - 1);
                outpdf.addPage(page, false);
            }
            if (pldh.hasPageLabels())
            {
                std::vector<QPDFObjectHandle> labels;
                pldh.getLabelsForPageRange(first - 1, last - 1, 0, labels);
                QPDFObjectHandle page_labels =
                    QPDFObjectHandle::newDictionary();
                page_labels.replaceKey(
                    "/Nums", QPDFObjectHandle::newArray(labels));
                outpdf.getRoot().replaceKey("/PageLabels", page_labels);
            }
            std::string page_range = QUtil::int_to_string(first, pageno_len);
            if (o.split_pages > 1)
            {
                page_range += "-" + QUtil::int_to_string(last, pageno_len);
            }
            std::string outfile = before + page_range + after;
            QPDFWriter w(outpdf, outfile.c_str());
            set_writer_options(outpdf, o, w);
            w.write();
            if (o.verbose)
            {
                std::cout << whoami << ": wrote file " << outfile << std::endl;
            }
        }
    }
    else
    {
        if (strcmp(o.outfilename, "-") == 0)
        {
            o.outfilename = 0;
        }
        QPDFWriter w(pdf, o.outfilename);
        set_writer_options(pdf, o, w);
        w.write();
        if (o.verbose)
        {
            std::cout << whoami << ": wrote file "
                      << o.outfilename << std::endl;
        }
    }
}


static spl_ptr_llist * spl_ptr_llist_init ( spl_ptr_llist_ctor_func ctor , spl_ptr_llist_dtor_func dtor ) {
 spl_ptr_llist * llist = emalloc ( sizeof ( spl_ptr_llist ) ) ;
 llist -> head = NULL ;
 llist -> tail = NULL ;
 llist -> count = 0 ;
 llist -> dtor = dtor ;
 llist -> ctor = ctor ;
 return llist ;
 }


CPUAlphaState * cpu_alpha_init (const char *cpu_model) { CPUAlphaState *env; int implver, amask, i, max; env = qemu_mallocz(sizeof(CPUAlphaState)); cpu_exec_init(env); alpha_translate_init(); tlb_flush(env, 1); /* Default to ev67; no reason not to emulate insns by default. */ implver = IMPLVER_21264; amask = (AMASK_BWX | AMASK_FIX | AMASK_CIX | AMASK_MVI | AMASK_TRAP | AMASK_PREFETCH); max = ARRAY_SIZE(cpu_defs); for (i = 0; i < max; i++) { if (strcmp (cpu_model, cpu_defs[i].name) == 0) { implver = cpu_defs[i].implver; amask = cpu_defs[i].amask; break; } } env->implver = implver; env->amask = amask; env->ps = 0x1F00; #if defined (CONFIG_USER_ONLY) env->ps |= 1 << 3; cpu_alpha_store_fpcr(env, (FPCR_INVD | FPCR_DZED | FPCR_OVFD | FPCR_UNFD | FPCR_INED | FPCR_DNOD)); #endif pal_init(env); /* Initialize IPR */ #if defined (CONFIG_USER_ONLY) env->ipr[IPR_EXC_ADDR] = 0; env->ipr[IPR_EXC_SUM] = 0; env->ipr[IPR_EXC_MASK] = 0; #else { uint64_t hwpcb; hwpcb = env->ipr[IPR_PCBB]; env->ipr[IPR_ASN] = 0; env->ipr[IPR_ASTEN] = 0; env->ipr[IPR_ASTSR] = 0; env->ipr[IPR_DATFX] = 0; /* XXX: fix this */ // env->ipr[IPR_ESP] = ldq_raw(hwpcb + 8); // env->ipr[IPR_KSP] = ldq_raw(hwpcb + 0); // env->ipr[IPR_SSP] = ldq_raw(hwpcb + 16); // env->ipr[IPR_USP] = ldq_raw(hwpcb + 24); env->ipr[IPR_FEN] = 0; env->ipr[IPR_IPL] = 31; env->ipr[IPR_MCES] = 0; env->ipr[IPR_PERFMON] = 0; /* Implementation specific */ // env->ipr[IPR_PTBR] = ldq_raw(hwpcb + 32); env->ipr[IPR_SISR] = 0; env->ipr[IPR_VIRBND] = -1ULL; } #endif qemu_init_vcpu(env); return env; }


static guint nlm_msg_res_matched_hash ( gconstpointer k ) {
 guint hash = GPOINTER_TO_UINT ( k ) ;
 return hash ;
 }


static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf,
		RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da,
		size_t offset, const ut8 *debug_str, size_t debug_str_len) {
	const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7);
	ut64 abbr_code;
	size_t i;

	if (cu->hdr.length > debug_str_len) {
		//avoid oob read
		return NULL;
	}
	while (buf && buf < buf_end && buf >= obuf) {
		if (cu->length && cu->capacity == cu->length) {
			r_bin_dwarf_expand_cu (cu);
		}
		buf = r_uleb128 (buf, buf_end - buf, &abbr_code);
		if (abbr_code > da->length || !buf) {
			return NULL;
		}

		r_bin_dwarf_init_die (&cu->dies[cu->length]);
		if (!abbr_code) {
			cu->dies[cu->length].abbrev_code = 0;
			cu->length++;
			buf++;
			continue;
		}

		cu->dies[cu->length].abbrev_code = abbr_code;
		cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag;
		abbr_code += offset;

		if (da->capacity < abbr_code) {
			return NULL;
		}

		for (i = 0; i < da->decls[abbr_code - 1].length; i++) {
			if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) {
				r_bin_dwarf_expand_die (&cu->dies[cu->length]);
			}
			if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) {
				eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n");
				break;
			}
			memset (&cu->dies[cu->length].attr_values[i], 0, sizeof
					(cu->dies[cu->length].attr_values[i]));
			buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf,
					&da->decls[abbr_code - 1].specs[i],
					&cu->dies[cu->length].attr_values[i],
					&cu->hdr, debug_str, debug_str_len);
			if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) {
				const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string;
				sdb_set (s, "DW_AT_comp_dir", name, 0);
			}
			cu->dies[cu->length].length++;
		}
		cu->length++;
	}
	return buf;
}


static int dissect_h225_SEQUENCE_OF_RasUsageSpecification ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) {
 offset = dissect_per_sequence_of ( tvb , offset , actx , tree , hf_index , ett_h225_SEQUENCE_OF_RasUsageSpecification , SEQUENCE_OF_RasUsageSpecification_sequence_of ) ;
 return offset ;
 }


static ssize_t ib_uverbs_write(struct file *filp, const char __user *buf,
			     size_t count, loff_t *pos)
{
	struct ib_uverbs_file *file = filp->private_data;
	struct ib_device *ib_dev;
	struct ib_uverbs_cmd_hdr hdr;
	__u32 command;
	__u32 flags;
	int srcu_key;
	ssize_t ret;

	if (count < sizeof hdr)
		return -EINVAL;

	if (copy_from_user(&hdr, buf, sizeof hdr))
		return -EFAULT;

	srcu_key = srcu_read_lock(&file->device->disassociate_srcu);
	ib_dev = srcu_dereference(file->device->ib_dev,
				  &file->device->disassociate_srcu);
	if (!ib_dev) {
		ret = -EIO;
		goto out;
	}

	if (hdr.command & ~(__u32)(IB_USER_VERBS_CMD_FLAGS_MASK |
				   IB_USER_VERBS_CMD_COMMAND_MASK)) {
		ret = -EINVAL;
		goto out;
	}

	command = hdr.command & IB_USER_VERBS_CMD_COMMAND_MASK;
	if (verify_command_mask(ib_dev, command)) {
		ret = -EOPNOTSUPP;
		goto out;
	}

	if (!file->ucontext &&
	    command != IB_USER_VERBS_CMD_GET_CONTEXT) {
		ret = -EINVAL;
		goto out;
	}

	flags = (hdr.command &
		 IB_USER_VERBS_CMD_FLAGS_MASK) >> IB_USER_VERBS_CMD_FLAGS_SHIFT;

	if (!flags) {
		if (command >= ARRAY_SIZE(uverbs_cmd_table) ||
		    !uverbs_cmd_table[command]) {
			ret = -EINVAL;
			goto out;
		}

		if (hdr.in_words * 4 != count) {
			ret = -EINVAL;
			goto out;
		}

		ret = uverbs_cmd_table[command](file, ib_dev,
						 buf + sizeof(hdr),
						 hdr.in_words * 4,
						 hdr.out_words * 4);

	} else if (flags == IB_USER_VERBS_CMD_FLAG_EXTENDED) {
		struct ib_uverbs_ex_cmd_hdr ex_hdr;
		struct ib_udata ucore;
		struct ib_udata uhw;
		size_t written_count = count;

		if (command >= ARRAY_SIZE(uverbs_ex_cmd_table) ||
		    !uverbs_ex_cmd_table[command]) {
			ret = -ENOSYS;
			goto out;
		}

		if (!file->ucontext) {
			ret = -EINVAL;
			goto out;
		}

		if (count < (sizeof(hdr) + sizeof(ex_hdr))) {
			ret = -EINVAL;
			goto out;
		}

		if (copy_from_user(&ex_hdr, buf + sizeof(hdr), sizeof(ex_hdr))) {
			ret = -EFAULT;
			goto out;
		}

		count -= sizeof(hdr) + sizeof(ex_hdr);
		buf += sizeof(hdr) + sizeof(ex_hdr);

		if ((hdr.in_words + ex_hdr.provider_in_words) * 8 != count) {
			ret = -EINVAL;
			goto out;
		}

		if (ex_hdr.cmd_hdr_reserved) {
			ret = -EINVAL;
			goto out;
		}

		if (ex_hdr.response) {
			if (!hdr.out_words && !ex_hdr.provider_out_words) {
				ret = -EINVAL;
				goto out;
			}

			if (!access_ok(VERIFY_WRITE,
				       (void __user *) (unsigned long) ex_hdr.response,
				       (hdr.out_words + ex_hdr.provider_out_words) * 8)) {
				ret = -EFAULT;
				goto out;
			}
		} else {
			if (hdr.out_words || ex_hdr.provider_out_words) {
				ret = -EINVAL;
				goto out;
			}
		}

		INIT_UDATA_BUF_OR_NULL(&ucore, buf, (unsigned long) ex_hdr.response,
				       hdr.in_words * 8, hdr.out_words * 8);

		INIT_UDATA_BUF_OR_NULL(&uhw,
				       buf + ucore.inlen,
				       (unsigned long) ex_hdr.response + ucore.outlen,
				       ex_hdr.provider_in_words * 8,
				       ex_hdr.provider_out_words * 8);

		ret = uverbs_ex_cmd_table[command](file,
						   ib_dev,
						   &ucore,
						   &uhw);
		if (!ret)
			ret = written_count;
	} else {
		ret = -ENOSYS;
	}

out:
	srcu_read_unlock(&file->device->disassociate_srcu, srcu_key);
	return ret;
}


void min_heap_shift_down_ ( min_heap_t * s , unsigned hole_index , struct event * e ) {
 unsigned min_child = 2 * ( hole_index + 1 ) ;
 while ( min_child <= s -> n ) {
 min_child -= min_child == s -> n || min_heap_elem_greater ( s -> p [ min_child ] , s -> p [ min_child - 1 ] ) ;
 if ( ! ( min_heap_elem_greater ( e , s -> p [ min_child ] ) ) ) break ;
 ( s -> p [ hole_index ] = s -> p [ min_child ] ) -> min_heap_idx = hole_index ;
 hole_index = min_child ;
 min_child = 2 * ( hole_index + 1 ) ;
 }
 min_heap_shift_up_ ( s , hole_index , e ) ;
 }


static int selinux_socket_unix_may_send ( struct socket * sock , struct socket * other ) {
 struct sk_security_struct * ssec = sock -> sk -> sk_security ;
 struct sk_security_struct * osec = other -> sk -> sk_security ;
 struct common_audit_data ad ;
 struct lsm_network_audit net = {
 0 , }
 ;
 ad . type = LSM_AUDIT_DATA_NET ;
 ad . u . net = & net ;
 ad . u . net -> sk = other -> sk ;
 return avc_has_perm ( ssec -> sid , osec -> sid , osec -> sclass , SOCKET__SENDTO , & ad ) ;
 }


static int nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply, int len) { NBDClient *client = req->client; int csock = client->sock; int rc, ret; qemu_co_mutex_lock(&client->send_lock); qemu_set_fd_handler2(csock, NULL, nbd_read, nbd_restart_write, client); client->send_coroutine = qemu_coroutine_self(); if (!len) { rc = nbd_send_reply(csock, reply); if (rc == -1) { rc = -errno; } } else { socket_set_cork(csock, 1); rc = nbd_send_reply(csock, reply); if (rc != -1) { ret = qemu_co_send(csock, req->data, len); if (ret != len) { errno = EIO; rc = -1; } } if (rc == -1) { rc = -errno; } socket_set_cork(csock, 0); } client->send_coroutine = NULL; qemu_set_fd_handler2(csock, NULL, nbd_read, NULL, client); qemu_co_mutex_unlock(&client->send_lock); return rc; }


static int proxy_fsync(FsContext *ctx, int fid_type, V9fsFidOpenState *fs, int datasync) { int fd; if (fid_type == P9_FID_DIR) { fd = dirfd(fs->dir); } else { fd = fs->fd; } if (datasync) { return qemu_fdatasync(fd); } else { return fsync(fd); } }


uint32_t ssi_transfer(SSIBus *bus, uint32_t val) { DeviceState *dev; SSISlave *slave; dev = LIST_FIRST(&bus->qbus.children); if (!dev) { return 0; } slave = SSI_SLAVE_FROM_QDEV(dev); return slave->info->transfer(slave, val); }


static int dissect_btgatt ( tvbuff_t * tvb , packet_info * pinfo , proto_tree * tree , void * data ) {
 proto_item * main_item ;
 proto_tree * main_tree ;
 proto_item * patron_item = NULL ;
 bluetooth_uuid_t uuid ;
 main_item = proto_tree_add_item ( tree , ( gint ) GPOINTER_TO_UINT ( wmem_list_frame_data ( wmem_list_tail ( pinfo -> layers ) ) ) , tvb , 0 , tvb_captured_length ( tvb ) , ENC_NA ) ;
 main_tree = proto_item_add_subtree ( main_item , ett_btgatt ) ;
 if ( strlen ( pinfo -> current_proto ) > 7 ) {
 uuid . size = 2 ;
 uuid . bt_uuid = ( guint16 ) g_ascii_strtoull ( pinfo -> current_proto + strlen ( pinfo -> current_proto ) - 7 , NULL , 16 ) ;
 uuid . data [ 1 ] = uuid . bt_uuid & 0xFF ;
 uuid . data [ 0 ] = ( uuid . bt_uuid >> 8 ) & 0xFF ;
 }
 else {
 uuid . size = 2 ;
 uuid . bt_uuid = 0 ;
 }
 return dissect_attribute_value ( main_tree , patron_item , pinfo , tvb , 0 , tvb_captured_length ( tvb ) , 0 , uuid , ( btatt_data_t * ) data ) ;
 }


static void cirrus_linear_write(void *opaque, target_phys_addr_t addr, uint64_t val, unsigned size) { CirrusVGAState *s = opaque; unsigned mode; addr &= s->cirrus_addr_mask; if (((s->vga.sr[0x17] & 0x44) == 0x44) && ((addr & s->linear_mmio_mask) == s->linear_mmio_mask)) { /* memory-mapped I/O */ cirrus_mmio_blt_write(s, addr & 0xff, val); } else if (s->cirrus_srcptr != s->cirrus_srcptr_end) { /* bitblt */ *s->cirrus_srcptr++ = (uint8_t) val; if (s->cirrus_srcptr >= s->cirrus_srcptr_end) { cirrus_bitblt_cputovideo_next(s); } } else { /* video memory */ if ((s->vga.gr[0x0B] & 0x14) == 0x14) { addr <<= 4; } else if (s->vga.gr[0x0B] & 0x02) { addr <<= 3; } addr &= s->cirrus_addr_mask; mode = s->vga.gr[0x05] & 0x7; if (mode < 4 || mode > 5 || ((s->vga.gr[0x0B] & 0x4) == 0)) { *(s->vga.vram_ptr + addr) = (uint8_t) val; memory_region_set_dirty(&s->vga.vram, addr, 1); } else { if ((s->vga.gr[0x0B] & 0x14) != 0x14) { cirrus_mem_writeb_mode4and5_8bpp(s, mode, addr, val); } else { cirrus_mem_writeb_mode4and5_16bpp(s, mode, addr, val); } } } }


MIMEField * _mime_hdr_field_list_search_by_wks ( MIMEHdrImpl * mh , int wks_idx ) {
 MIMEFieldBlockImpl * fblock ;
 MIMEField * field , * too_far_field ;
 ink_assert ( hdrtoken_is_valid_wks_idx ( wks_idx ) ) ;
 for ( fblock = & ( mh -> m_first_fblock ) ;
 fblock != nullptr ;
 fblock = fblock -> m_next ) {
 field = & ( fblock -> m_field_slots [ 0 ] ) ;
 too_far_field = & ( fblock -> m_field_slots [ fblock -> m_freetop ] ) ;
 while ( field < too_far_field ) {
 if ( field -> is_live ( ) && ( field -> m_wks_idx == wks_idx ) ) {
 return field ;
 }
 ++ field ;
 }
 }
 return nullptr ;
 }


static uint32_t mt_exp_rand ( uint32_t mean , uint32_t max_value ) {
 double mean_d = mean ;
 double erand = log ( 1.0 / ( mt_random ( & static_mtrand ) / ( double ) UINT32_MAX ) ) ;
 uint32_t x = ( uint32_t ) ( mean_d * erand + 0.5 ) ;
 return min ( x , max_value ) ;
 }


void run_query_stmt ( struct st_connection * cn , struct st_command * command , char * query , int query_len , DYNAMIC_STRING * ds , DYNAMIC_STRING * ds_warnings ) {
 MYSQL_RES * res = NULL ;
 MYSQL * mysql = cn -> mysql ;
 MYSQL_STMT * stmt ;
 DYNAMIC_STRING ds_prepare_warnings ;
 DYNAMIC_STRING ds_execute_warnings ;
 DBUG_ENTER ( "run_query_stmt" ) ;
 DBUG_PRINT ( "query" , ( "'%-.60s'" , query ) ) ;
 if ( ! ( stmt = cn -> stmt ) ) {
 if ( ! ( stmt = mysql_stmt_init ( mysql ) ) ) die ( "unable to init stmt structure" ) ;
 cn -> stmt = stmt ;
 }
 if ( ! disable_warnings ) {
 init_dynamic_string ( & ds_prepare_warnings , NULL , 0 , 256 ) ;
 init_dynamic_string ( & ds_execute_warnings , NULL , 0 , 256 ) ;
 }
 if ( do_stmt_prepare ( cn , query , query_len ) ) {
 handle_error ( command , mysql_stmt_errno ( stmt ) , mysql_stmt_error ( stmt ) , mysql_stmt_sqlstate ( stmt ) , ds ) ;
 goto end ;
 }
 if ( ! disable_warnings ) append_warnings ( & ds_prepare_warnings , mysql ) ;
 # if MYSQL_VERSION_ID >= 50000 if ( cursor_protocol_enabled ) {
 ulong type = CURSOR_TYPE_READ_ONLY ;
 if ( mysql_stmt_attr_set ( stmt , STMT_ATTR_CURSOR_TYPE , ( void * ) & type ) ) die ( "mysql_stmt_attr_set(STMT_ATTR_CURSOR_TYPE) failed': %d %s" , mysql_stmt_errno ( stmt ) , mysql_stmt_error ( stmt ) ) ;
 }
 # endif if ( do_stmt_execute ( cn ) ) {
 handle_error ( command , mysql_stmt_errno ( stmt ) , mysql_stmt_error ( stmt ) , mysql_stmt_sqlstate ( stmt ) , ds ) ;
 goto end ;
 }
 if ( cursor_protocol_enabled && ! disable_warnings ) append_warnings ( & ds_execute_warnings , mysql ) ;
 {
 my_bool one = 1 ;
 if ( mysql_stmt_attr_set ( stmt , STMT_ATTR_UPDATE_MAX_LENGTH , ( void * ) & one ) ) die ( "mysql_stmt_attr_set(STMT_ATTR_UPDATE_MAX_LENGTH) failed': %d %s" , mysql_stmt_errno ( stmt ) , mysql_stmt_error ( stmt ) ) ;
 }
 if ( mysql_stmt_field_count ( stmt ) && mysql_stmt_store_result ( stmt ) ) {
 handle_error ( command , mysql_stmt_errno ( stmt ) , mysql_stmt_error ( stmt ) , mysql_stmt_sqlstate ( stmt ) , ds ) ;
 goto end ;
 }
 handle_no_error ( command ) ;
 if ( ! disable_result_log ) {
 if ( ( res = mysql_stmt_result_metadata ( stmt ) ) != NULL ) {
 MYSQL_FIELD * fields = mysql_fetch_fields ( res ) ;
 uint num_fields = mysql_num_fields ( res ) ;
 if ( display_metadata ) append_metadata ( ds , fields , num_fields ) ;
 if ( ! display_result_vertically ) append_table_headings ( ds , fields , num_fields ) ;
 append_stmt_result ( ds , stmt , fields , num_fields ) ;
 mysql_free_result ( res ) ;
 if ( ! disable_warnings && ! prepare_warnings_enabled ) dynstr_set ( & ds_prepare_warnings , NULL ) ;
 }
 else {
 }
 if ( ! disable_info ) append_info ( ds , mysql_stmt_affected_rows ( stmt ) , mysql_info ( mysql ) ) ;
 if ( ! disable_warnings ) {
 if ( append_warnings ( & ds_execute_warnings , mysql ) || ds_execute_warnings . length || ds_prepare_warnings . length || ds_warnings -> length ) {
 dynstr_append_mem ( ds , "Warnings:\n" , 10 ) ;
 if ( ds_warnings -> length ) dynstr_append_mem ( ds , ds_warnings -> str , ds_warnings -> length ) ;
 if ( ds_prepare_warnings . length ) dynstr_append_mem ( ds , ds_prepare_warnings . str , ds_prepare_warnings . length ) ;
 if ( ds_execute_warnings . length ) dynstr_append_mem ( ds , ds_execute_warnings . str , ds_execute_warnings . length ) ;
 }
 }
 }
 end : if ( ! disable_warnings ) {
 dynstr_free ( & ds_prepare_warnings ) ;
 dynstr_free ( & ds_execute_warnings ) ;
 }
 var_set_errno ( mysql_stmt_errno ( stmt ) ) ;
 revert_properties ( ) ;
 if ( mysql -> reconnect ) {
 mysql_stmt_close ( stmt ) ;
 cn -> stmt = NULL ;
 }
 DBUG_VOID_RETURN ;
 }