/*
 * Copyright 2009 Robey Pointer <robeypointer@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.lag

import scala.util.matching.Regex

final class ConfiggyString(wrapped: String) {
  /**
   * For every section of a string that matches a regular expression, call
   * a function to determine a replacement (as in python's
   * `re.sub`). The function will be passed the Matcher object
   * corresponding to the substring that matches the pattern, and that
   * substring will be replaced by the function's result.
   *
   * For example, this call:
   *
   *     "ohio".regexSub("""h.""".r) { m => "n" }
   *
   * will return the string `"ono"`.
   *
   * The matches are found using `Matcher.find()` and so
   * will obey all the normal java rules (the matches will not overlap,
   * etc).
   *
   * @param re the regex pattern to replace
   * @param replace a function that takes Regex.MatchData objects and
   *     returns a string to substitute
   * @return the resulting string with replacements made
   */
  def regexSub(re: Regex)(replace: (Regex.MatchData => String)): String = {
    var offset = 0
    var out = new StringBuilder

    for (val m <- re.findAllIn(wrapped).matchData) {
      if (m.start > offset) {
        out.append(wrapped.substring(offset, m.start))
      }

      out.append(replace(m))
      offset = m.end
    }

    if (offset < wrapped.length) {
      out.append(wrapped.substring(offset))
    }
    out.toString
  }

  private val QUOTE_RE = "[\u0000-\u001f\u007f-\uffff\\\\\"]".r

  /**
   * Quote a string so that unprintable chars (in ASCII) are represented by
   * C-style backslash expressions. For example, a raw linefeed will be
   * translated into "\n". Control codes (anything below 0x20)
   * and unprintables (anything above 0x7E) are turned into either
   * "\xHH" or "\\uHHHH" expressions, depending on
   * their range. Embedded backslashes and double-quotes are also quoted.
   *
   * @return a quoted string, suitable for ASCII display
   */
  def quoteC(): String = {
    regexSub(QUOTE_RE) { m =>
      m.matched.charAt(0) match {
        case '\r' => "\\r"
        case '\n' => "\\n"
        case '\t' => "\\t"
        case '"' => "\\\""
        case '\\' => "\\\\"
        case c =>
          if (c <= 255) {
              "\\x%02x".format(c.asInstanceOf[Int])
          } else {
              "\\u%04x" format c.asInstanceOf[Int]
          }
      }
    }
  }

  // we intentionally don't unquote "\$" here, so it can be used to escape interpolation later.
  private val UNQUOTE_RE = """\\(u[\dA-Fa-f]{4}|x[\dA-Fa-f]{2}|[/rnt\"\\])""".r

  /**
   * Unquote an ASCII string that has been quoted in a style like
   * {@link #quoteC} and convert it into a standard unicode string.
   * "\\uHHHH" and "\xHH" expressions are unpacked
   * into unicode characters, as well as "\r", "\n",
   * "\t", "\\", and '\"'.
   *
   * @return an unquoted unicode string
   */
  def unquoteC() = {
    regexSub(UNQUOTE_RE) { m =>
      val ch = m.group(1).charAt(0) match {
        // holy crap! this is terrible:
        case 'u' => Character.valueOf(Integer.valueOf(m.group(1).substring(1), 16).asInstanceOf[Int].toChar)
        case 'x' => Character.valueOf(Integer.valueOf(m.group(1).substring(1), 16).asInstanceOf[Int].toChar)
        case 'r' => '\r'
        case 'n' => '\n'
        case 't' => '\t'
        case x => x
      }
      ch.toString
    }
  }

  /**
   * Turn a string of hex digits into a byte array. This does the exact
   * opposite of `Array[Byte]#hexlify`.
   */
  def unhexlify(): Array[Byte] = {
    val buffer = new Array[Byte](wrapped.length / 2)
    for (val i <- 0.until(wrapped.length, 2)) {
      buffer(i/2) = Integer.parseInt(wrapped.substring(i, i+2), 16).toByte
    }
    buffer
  }
}

final class ConfiggyByteArray(wrapped: Array[Byte]) {
  /**
   * Turn an Array[Byte] into a string of hex digits.
   */
  def hexlify(): String = {
    val out = new StringBuffer
    for (val b <- wrapped) {
      val s = (b.toInt & 0xff).toHexString
      if (s.length < 2) {
        out append '0'
      }
      out append s
    }
    out.toString
  }
}

object extensions {
  implicit def stringToConfiggyString(s: String): ConfiggyString = new ConfiggyString(s)
  implicit def byteArrayToConfiggyByteArray(b: Array[Byte]): ConfiggyByteArray = new ConfiggyByteArray(b)
}


<?php

if (!defined('FRAMEWORK_PATH')) {
    echo "FRAMEWORK_PATH hasn't been defined. This probably means that framework/Core/Constants.php hasn't been " .
        "included by Composer's autoloader.\n" .
        "Make sure the you are running your tests via vendor/bin/phpunit and your autoloader is up to date.\n";
    exit(1);
}

if (empty($_SERVER['HTTP_HOST'])) {
    $_SERVER['HTTP_HOST'] = 'localhost';
}


/*
 * Copyright (c) 2006-2007 Hyperic, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.hyperic.sigar.jmx;

/*
 * yeah, yeah, we could generate this class via xdoclet,
 * whoopdi-friggin-do... by hand is much less pain.
 */

public interface SigarProcessMBean {

    public Long getMemSize();

    /**
     * @deprecated
     * @see getMemSize
     */
    public Long getMemVsize();

    public Long getMemResident();

    public Long getMemShare();

    public Long getMemPageFaults();

    public Long getTimeUser();

    public Long getTimeSys();

    public Double getCpuUsage();

    public Long getOpenFd();

    public Double getBytesReadWriteTotal();
}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE infoType SYSTEM "infoType.dtd">
<!--
        新闻类别
-->
<infoType>
    <infoTypeContents>
        <infoTypeContent lang="zh" infoTypeName="新闻类别"/>
        <infoTypeContent lang="en" infoTypeName="News categories"/>
    </infoTypeContents>
    <subInfoTypes>
        <infoType>
            <infoTypeContents>
                <infoTypeContent lang="zh" infoTypeName="综合信息"/>
                <infoTypeContent lang="en" infoTypeName="Information"/>
            </infoTypeContents>
            <subInfoTypes>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="通知公告"/>
                        <infoTypeContent lang="en" infoTypeName="The notice"/>
                    </infoTypeContents>
                </infoType>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="图片新闻"/>
                        <infoTypeContent lang="en" infoTypeName="Picture news"/>
                    </infoTypeContents>
                </infoType>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="新闻动态"/>
                        <infoTypeContent lang="en" infoTypeName="Dynamic news"/>
                    </infoTypeContents>
                </infoType>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="投诉处理"/>
                        <infoTypeContent lang="en" infoTypeName="Complaint handling"/>
                    </infoTypeContents>
                </infoType>
            </subInfoTypes>
        </infoType>
        <infoType>
            <infoTypeContents>
                <infoTypeContent lang="zh" infoTypeName="政策法规"/>
                <infoTypeContent lang="en" infoTypeName="Policies and regulations"/>
            </infoTypeContents>
            <subInfoTypes>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="国家"/>
                        <infoTypeContent lang="en" infoTypeName="Country"/>
                    </infoTypeContents>
                </infoType>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="地方"/>
                        <infoTypeContent lang="en" infoTypeName="Place"/>
                    </infoTypeContents>
                    <subInfoTypes>
                        <infoType>
                            <infoTypeContents>
                                <infoTypeContent lang="zh" infoTypeName="省"/>
                                <infoTypeContent lang="en" infoTypeName="Province"/>
                            </infoTypeContents>
                        </infoType>
                        <infoType>
                            <infoTypeContents>
                                <infoTypeContent lang="zh" infoTypeName="市"/>
                                <infoTypeContent lang="en" infoTypeName="City"/>
                            </infoTypeContents>
                        </infoType>
                        <infoType>
                            <infoTypeContents>
                                <infoTypeContent lang="zh" infoTypeName="县"/>
                                <infoTypeContent lang="en" infoTypeName="County"/>
                            </infoTypeContents>
                        </infoType>
                        <infoType>
                            <infoTypeContents>
                                <infoTypeContent lang="zh" infoTypeName="乡"/>
                                <infoTypeContent lang="en" infoTypeName="Township"/>
                            </infoTypeContents>
                        </infoType>
                    </subInfoTypes>
                </infoType>
            </subInfoTypes>
        </infoType>
        <infoType>
            <infoTypeContents>
                <infoTypeContent lang="zh" infoTypeName="办事指南"/>
                <infoTypeContent lang="en" infoTypeName="The service guide"/>
            </infoTypeContents>
            <subInfoTypes>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="办事程序"/>
                        <infoTypeContent lang="en" infoTypeName="Work procedures"/>
                    </infoTypeContents>
                </infoType>
                <infoType>
                    <infoTypeContents>
                        <infoTypeContent lang="zh" infoTypeName="投诉处理程序"/>
                        <infoTypeContent lang="en" infoTypeName="Complaint handling procedure"/>
                    </infoTypeContents>
                </infoType>
            </subInfoTypes>
        </infoType>
        <infoType>
            <infoTypeContents>
                <infoTypeContent lang="zh" infoTypeName="关于"/>
                <infoTypeContent lang="en" infoTypeName="About"/>
            </infoTypeContents>
        </infoType>
        <infoType>
            <infoTypeContents>
                <infoTypeContent lang="zh" infoTypeName="帮助"/>
                <infoTypeContent lang="en" infoTypeName="Help"/>
            </infoTypeContents>
        </infoType>
    </subInfoTypes>
</infoType>


import QtQuick 2.2

Rectangle {
    width: 500
    height: Math.min(400, mailListView.contentHeight)

    radius: 3
    gradient: Gradient {
        GradientStop {
            position: 0
            color: colorProxy.color_TextView_TopColor
        }
        GradientStop {
            position: 1
            color: colorProxy.color_TextView_BottomColor
        }
    }

    smooth: true

    ListView {
        id: mailListView
        anchors.fill: parent

        model: mailListModel

        delegate: Rectangle {
            width: mailListView.width
            height: subjectLabel.height + dateLabel.height + authorLabel.height + summaryLabel.height

            smooth: true

            radius: 3
            gradient: Gradient {
                GradientStop {
                    position: 0
                    color: colorProxy.color_TextBox_TopColor
                }
                GradientStop {
                    position: 1
                    color: colorProxy.color_TextBox_BottomColor
                }
            }

            border.color: colorProxy.color_TextBox_BorderColor
            border.width: 1

            Text {
                id: subjectLabel
                anchors.top: parent.top
                anchors.topMargin: 2
                anchors.left: parent.left
                anchors.leftMargin: 2
                anchors.right: parent.right
                anchors.rightMargin: 2

                text: subject

                color: colorProxy.color_TextBox_TitleTextColor
                font.bold: true
                elide: Text.ElideRight
            }

            Text {
                id: dateLabel
                anchors.top: subjectLabel.bottom
                anchors.topMargin: 2
                anchors.right: parent.right
                anchors.rightMargin: 2

                text: modifiedDate

                color: colorProxy.color_TextBox_TextColor
            }

            Text {
                id: authorLabel
                anchors.top: subjectLabel.bottom
                anchors.topMargin: 2
                anchors.left: parent.left
                anchors.leftMargin: 2
                anchors.right: dateLabel.left
                anchors.rightMargin: 2

                text: authorName + " <" + authorEmail + ">"

                color: colorProxy.color_TextBox_TextColor
                font.italic: true
                elide: Text.ElideRight
            }

            Text {
                id: summaryLabel
                anchors.top: authorLabel.bottom
                anchors.topMargin: 2
                anchors.left: parent.left
                anchors.leftMargin: 2
                anchors.right: parent.right
                anchors.rightMargin: 2

                text: summary

                color: colorProxy.color_TextBox_Aux1TextColor
                wrapMode: Text.WrapAtWordBoundaryOrAnywhere
            }
        }
    }
}


#include "UnityCG.cginc"

#if _USEMAINTEX_ON
    UNITY_DECLARE_TEX2D(_MainTex);
    float4 _MainTex_ST;
#endif

#if _USECOLOR_ON
    float4 _Color;
#endif

struct appdata_t
{
    float4 vertex : POSITION;
    #if _USEMAINTEX_ON
        float2 texcoord : TEXCOORD0;
    #endif
};

struct v2f
{
    float4 vertex : SV_POSITION;
    #if _USEMAINTEX_ON
        float2 texcoord : TEXCOORD0;
    #endif
    UNITY_FOG_COORDS(1)
    #if _NEAR_PLANE_FADE_ON
        float fade : TEXCOORD2;
    #endif
};

v2f vert(appdata_t v)
{
    v2f o;
    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);

    #if _USEMAINTEX_ON
        o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
    #endif

    #if _NEAR_PLANE_FADE_ON
        o.fade = ComputeNearPlaneFadeLinear(v.vertex);
    #endif

    UNITY_TRANSFER_FOG(o, o.vertex);
    return o;
}

float4 frag(v2f i) : SV_Target
{
    float4 c;

    #if _USEMAINTEX_ON
        c = UNITY_SAMPLE_TEX2D(_MainTex, i.texcoord);
    #else
        c = 1;
    #endif

    #if _USECOLOR_ON
        c *= _Color;
    #endif

    UNITY_APPLY_FOG(i.fogCoord, c);

    #if _NEAR_PLANE_FADE_ON
        c.rgb *= i.fade;
    #endif

    return c;
}


app: CalendarApp
GtkApplicationWindow(toplevel): title='Moda Stoq', hidden
  GtkBox(orientation=vertical):
    GtkBox(orientation=horizontal, expand=True, fill=True):
      GtkBox(main_vbox, orientation=vertical, expand=True, fill=True):
        GtkBox(hbox, orientation=horizontal, padding=6):
          stoq+gui+widgets+ButtonGroup(nav_header, padding=6):
            GtkButton():
            GtkButton():
            GtkButton():
          GtkLabel(date_label, expand=True, fill=True, padding=6): '<big><b></b></big>'
          stoq+gui+widgets+ButtonGroup(view_header, padding=6):
            GtkToggleButton(month_button): 'Month', active
            GtkToggleButton(week_button): 'Week'
            GtkToggleButton(day_button): 'Day'
        stoq+gui+calendar+CalendarView(_calendar, expand=True, fill=True):
          WebKitWebView():
    ShellStatusbar():
      GtkFrame(expand=True, fill=True): hidden
        GtkBox(orientation=horizontal):
          GtkLabel(fill=True):
      GtkBox(orientation=horizontal, fill=True):
        GtkBox(orientation=horizontal, expand=True, fill=True):
          GtkLabel(expand=True, fill=True): 'Test Statusbar test'
          GtkVSeparator():
          GtkButton(): 'Feedback'
  GtkHeaderBar():
    stoq+gui+widgets+ButtonGroup():
      GtkButton():
      GtkMenuButton():
          GtkPopover(): hidden
            GtkStack():
              GtkMenuSectionBox(orientation=vertical):
                GtkBox(orientation=vertical, pack-end):
                  GtkMenuSectionBox(orientation=vertical, fill=True):
                    GtkBox(orientation=vertical, pack-end):
                      GtkModelButton(fill=True): Client call
                      GtkModelButton(fill=True): Account payable
                      GtkModelButton(fill=True): Account receivable
                      GtkModelButton(fill=True): Work order
    GtkBox(orientation=horizontal):
      GtkButton():
      GtkButton():
    stoq+gui+widgets+ButtonGroup():
      GtkMenuButton():
          GtkPopover(): hidden
            GtkStack():
              GtkMenuSectionBox(orientation=vertical):
                GtkBox(orientation=vertical, pack-end):
                  GtkMenuSectionBox(orientation=vertical, fill=True):
                    GtkBox(orientation=vertical, pack-end):
                      GtkModelButton(fill=True): Client Calls
                      GtkModelButton(fill=True): Client Birthdays
                      GtkModelButton(fill=True): Accounts payable
                      GtkModelButton(fill=True): Accounts receivable
                      GtkModelButton(fill=True): Purchases
                      GtkModelButton(fill=True): Work orders
      GtkMenuButton(): insensitive
          GtkPopover(): hidden, insensitive
            GtkStack():
              GtkMenuSectionBox(orientation=vertical):
                GtkBox(orientation=vertical, pack-end):
      GtkMenuButton():
          GtkPopover(): hidden
            GtkStack():
              GtkMenuSectionBox(orientation=vertical):
                GtkBox(orientation=vertical, pack-end):
                  GtkMenuSectionBox(orientation=vertical, fill=True):
                    GtkBox(orientation=vertical, pack-end):
                      GtkModelButton(fill=True): Preferences...
                      GtkModelButton(fill=True): Change password...
                      GtkModelButton(fill=True): Sign out...
                  GtkMenuSectionBox(orientation=vertical, fill=True):
                    GtkBox(orientation=vertical, pack-end):
                      GtkModelButton(fill=True): Calendar help
                      GtkModelButton(fill=True): Contents
                      GtkModelButton(fill=True): Translate Stoq...
                      GtkModelButton(fill=True): Get support online...
                      GtkModelButton(fill=True): Online chat...
                      GtkModelButton(fill=True): About
                  GtkMenuSectionBox(orientation=vertical, fill=True):
                    GtkBox(orientation=vertical, pack-end):
                      GtkModelButton(fill=True): Quit


/* -*- c++ -*- */
/*
 * Copyright 2004,2009,2012,2015 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 */

#ifndef ADD_CONST_BB_IMPL
#define ADD_CONST_BB_IMPL

#include <gnuradio/blocks/add_const_bb.h>

namespace gr {
namespace blocks {

class BLOCKS_API add_const_bb_impl : public add_const_bb
{
private:
    unsigned char d_k;

public:
    add_const_bb_impl(unsigned char k);
    ~add_const_bb_impl();

    void setup_rpc();

    unsigned char k() const { return d_k; }
    void set_k(unsigned char k) { d_k = k; }

    int work(int noutput_items,
             gr_vector_const_void_star& input_items,
             gr_vector_void_star& output_items);
};

} /* namespace blocks */
} /* namespace gr */

#endif /* ADD_CONST_BB_IMPL */


var config = {

    /*
     |--------------------------------------------------------------------------
     | Transport driver
     |--------------------------------------------------------------------------
     |
     | Here you may specify nodemailer transport driver you wish to use. If you
     | specify anything other  than the default driver you may have to install
     | that driver manually using npm install command
     | Find more drivers at https://github.com/nodemailer/nodemailer#send-using-a-transport-plugin
     |
     */

    'driver': 'nodemailer-smtp-transport',

    /*
     |--------------------------------------------------------------------------
     | Transport driver config
     |--------------------------------------------------------------------------
     |
     | Specify the configuration values for the driver you specified above.
     |
     */

    'driverConfig': {
        'service': 'gmail',
        'auth': {
            'user': 'sender@gmail.com',
            'pass': 'password'
        }
    },

    /*
     |--------------------------------------------------------------------------
     | Global "From" Address
     |--------------------------------------------------------------------------
     |
     | You may wish for all e-mails sent by your application to be sent from
     | the same address. Here, you may specify a name and address that is
     | used globally for all e-mails that are sent by your application.
     |
     */

    'from': {'address': null, 'name': null}

};

module.exports = config;


import { BaseTool } from '../base';
import {
  fillInsideCircle,
  fillOutsideCircle,
  eraseOutsideCircle,
  eraseInsideCircle,
} from './strategies';
import {
  segCircleFillInsideCursor,
  segCircleFillOutsideCursor,
  segCircleEraseOutsideCursor,
  segCircleEraseInsideCursor,
} from '../cursors';

/**
 * @public
 * @class CircleScissorsTool
 * @memberof Tools
 * @classdesc Tool for manipulating labelmap data by drawing a circle.
 * @extends Tools.Base.BaseTool
 */
export default class CircleScissorsTool extends BaseTool {
  /** @inheritdoc */
  constructor(props = {}) {
    const defaultProps = {
      name: 'CircleScissors',
      strategies: {
        FILL_INSIDE: fillInsideCircle,
        FILL_OUTSIDE: fillOutsideCircle,
        ERASE_OUTSIDE: eraseOutsideCircle,
        ERASE_INSIDE: eraseInsideCircle,
      },
      cursors: {
        FILL_INSIDE: segCircleFillInsideCursor,
        FILL_OUTSIDE: segCircleFillOutsideCursor,
        ERASE_OUTSIDE: segCircleEraseOutsideCursor,
        ERASE_INSIDE: segCircleEraseInsideCursor,
      },
      defaultStrategy: 'FILL_INSIDE',
      supportedInteractionTypes: ['Mouse', 'Touch'],
      svgCursor: segCircleFillInsideCursor,
      mixins: ['circleSegmentationMixin'],
    };

    super(props, defaultProps);
  }
}


# -*- coding: utf-8 -*-
#
#    LinOTP - the open source solution for two factor authentication
#    Copyright (C) 2010 - 2019 KeyIdentity GmbH
#
#    This file is part of LinOTP server.
#
#    This program is free software: you can redistribute it and/or
#    modify it under the terms of the GNU Affero General Public
#    License, version 3, as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the
#               GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
#    E-mail: linotp@keyidentity.com
#    Contact: www.linotp.org
#    Support: www.keyidentity.com
#

import json
import unittest
from mock import patch

from linotp.lib.user import get_user_from_options
from linotp.lib.user import User

class TestGetUserFromOptions(unittest.TestCase):

    @patch('linotp.lib.user.getUserFromParam')
    def test_run_test_vector(self,
                         mock_getUserFromParam
                         ):
        """
        test a set of options dict values with fallback user and fallback realm
        """

        test_sets = [
                    # 1. test simple login name in options
                    {'options_dict': {'user': 'amigo'},
                      'user_from_param' : User('amigo', 'defRealm'),
                      'result': {'login': 'amigo', 'realm': 'defRealm'}},

                     # 2. test login and realn in options
                     {'options_dict': {'user': 'amigo', 'realm': 'mexico'},
                      'user_from_param' : User('amigo', 'mexico'),
                      'result': {'login': 'amigo', 'realm': 'mexico'}},

                     # 3. test user object in options
                     {'options_dict': {'user': User('amigo', 'mexico')},
                      'user_from_param' : User('amigo', 'mexico'),
                      'result': {'login': 'amigo', 'realm': 'mexico'}},

                     # 4. test no login and no realn in options
                     {'options_dict': {},
                      'user_from_param' : User('', ''),
                      'result': {'login': 'token_owner', 'realm': 'norealm'}},

                     # 5. test no login and realn in options
                     {'options_dict': { 'user': '', 'realm': 'norway'},
                      'user_from_param' : User('', 'norway'),
                      'result': {'login': 'token_owner', 'realm': 'norealm'}},
        ]  # eof test sets

        for run in test_sets:

            options_dict = run['options_dict']
            mock_getUserFromParam.return_value = run['user_from_param']

            result = run['result']

            login, realm = get_user_from_options(
                                options_dict=options_dict,
                                fallback_user=User('token_owner', 'norealm'),
                                fallback_realm='norealm')

            assert (login == result['login'] and realm == result['realm'],
                        "failed on run %r:%r:%r" % (login, realm, run))

        return

    @patch('linotp.lib.user.getUserFromParam')
    def test_run_test_vector_without_fallback_user(self,
                         mock_getUserFromParam
                         ):
        """
        test a set of options dict values without fallback user and fallback realm
        """

        test_sets = [
                    # 1. test simple login name in options
                    {'options_dict': {'user': 'amigo'},
                      'user_from_param' : User('amigo', 'defRealm'),
                      'result': {'login': 'amigo', 'realm': 'defRealm'}},

                     # 2. test login and realn in options
                     {'options_dict': {'user': 'amigo', 'realm': 'mexico'},
                      'user_from_param' : User('amigo', 'mexico'),
                      'result': {'login': 'amigo', 'realm': 'mexico'}},

                     # 3. test user object in options
                     {'options_dict': {'user': User('amigo', 'mexico')},
                      'user_from_param' : User('amigo', 'mexico'),
                      'result': {'login': 'amigo', 'realm': 'mexico'}},

                     # 4. test no login and no realn in options
                     {'options_dict': {},
                      'user_from_param' : User('', ''),
                      'result': {'login': '', 'realm': 'norealm'}},

                     # 5. test no login and realn in options
                     {'options_dict': { 'user': '', 'realm': 'norway'},
                      'user_from_param' : User('', 'norway'),
                      'result': {'login': '', 'realm': 'norealm'}},

        ]  # eof test sets

        for run in test_sets:

            options_dict = run['options_dict']
            mock_getUserFromParam.return_value = run['user_from_param']

            result = run['result']

            login, realm = get_user_from_options(
                                options_dict=options_dict,
                                fallback_user=None,
                                fallback_realm='norealm')

            assert (login == result['login'] and realm == result['realm'],
                        "failed on run %r:%r:%r" % (login, realm, run))

        return

# eof #


/*
 * Copyright (c) 2008-2017 Nicira, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef OPENVSWITCH_NAMEMAP_H
#define OPENVSWITCH_NAMEMAP_H 1

#include "openvswitch/hmap.h"

struct ds;

#ifdef __cplusplus
extern "C" {
#endif

/* Name-number mapping.
 *
 * This data structure tracks and manages a mapping between names and 32-bit
 * unsigned integers, with provision for detecting names that are used more
 * than once.
 *
 * This structure is suitable for tracking mappings between OpenFlow port names
 * and numbers.  OpenFlow doesn't require either these kinds of names to be
 * unique, and in OVS it's possible for two ports to appear to have the same
 * name if their names are longer than the maximum length supported by a given
 * version of OpenFlow.
 *
 * OpenFlow does require port numbers to be unique.  We check for duplicate
 * ports numbers just in case a switch has a bug.
 *
 * This structure is also suitable for tracking mappings between OpenFlow table
 * names and number.  OpenFlow doesn't require table names to be unique and
 * Open vSwitch doesn't try to make them unique. */
struct namemap_node {
    struct hmap_node name_node;
    struct hmap_node number_node;

    uint32_t number;
    char *name;

    bool duplicate;
};

struct namemap {
    struct hmap by_name;
    struct hmap by_number;
};
#define NAMEMAP_INITIALIZER(MAP) \
    { HMAP_INITIALIZER(&(MAP)->by_name), HMAP_INITIALIZER(&(MAP)->by_number) }

void namemap_init(struct namemap *);
struct namemap_node *namemap_find_by_name(const struct namemap *,
                                              const char *);
struct namemap_node *namemap_find_by_number(const struct namemap *, uint32_t);
void namemap_put(struct namemap *, uint32_t, const char *);
void namemap_destroy(struct namemap *);

void namemap_put_name(const char *, struct ds *);

#ifdef __cplusplus
}
#endif

#endif  /* namemap.h */


fileFormatVersion: 2
guid: edcd15e84b7bb4ef1b6cb7b94b8e0d36
TextureImporter:
  fileIDToRecycleName: {}
  externalObjects: {}
  serializedVersion: 7
  mipmaps:
    mipMapMode: 0
    enableMipMap: 1
    sRGBTexture: 0
    linearTexture: 0
    fadeOut: 0
    borderMipMap: 0
    mipMapsPreserveCoverage: 0
    alphaTestReferenceValue: 0.5
    mipMapFadeDistanceStart: 1
    mipMapFadeDistanceEnd: 3
  bumpmap:
    convertToNormalMap: 1
    externalNormalMap: 0
    heightScale: 0.018
    normalMapFilter: 0
  isReadable: 0
  streamingMipmaps: 0
  streamingMipmapsPriority: 0
  grayScaleToAlpha: 0
  generateCubemap: 6
  cubemapConvolution: 0
  seamlessCubemap: 0
  textureFormat: -1
  maxTextureSize: 1024
  textureSettings:
    serializedVersion: 2
    filterMode: -1
    aniso: -1
    mipBias: -100
    wrapU: -1
    wrapV: -1
    wrapW: -1
  nPOTScale: 1
  lightmap: 0
  compressionQuality: 50
  spriteMode: 0
  spriteExtrude: 1
  spriteMeshType: 1
  alignment: 0
  spritePivot: {x: 0.5, y: 0.5}
  spritePixelsToUnits: 100
  spriteBorder: {x: 0, y: 0, z: 0, w: 0}
  spriteGenerateFallbackPhysicsShape: 1
  alphaUsage: 1
  alphaIsTransparency: 0
  spriteTessellationDetail: -1
  textureType: 1
  textureShape: 1
  singleChannelComponent: 0
  maxTextureSizeSet: 0
  compressionQualitySet: 0
  textureFormatSet: 0
  platformSettings:
  - serializedVersion: 2
    buildTarget: DefaultTexturePlatform
    maxTextureSize: 1024
    resizeAlgorithm: 0
    textureFormat: -1
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
  - serializedVersion: 2
    buildTarget: Standalone
    maxTextureSize: 1024
    resizeAlgorithm: 0
    textureFormat: -1
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
  spriteSheet:
    serializedVersion: 2
    sprites: []
    outline: []
    physicsShape: []
    bones: []
    spriteID:
    vertices: []
    indices:
    edges: []
    weights: []
  spritePackingTag:
  pSDRemoveMatte: 0
  pSDShowRemoveMatteOption: 0
  userData:
  assetBundleName:
  assetBundleVariant:


package com.lody.virtual.client.hook.proxies.pm;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageDeleteObserver2;
import android.content.pm.IPackageInstallerCallback;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Build;
import android.os.IInterface;
import android.os.Process;

import com.lody.virtual.client.core.VirtualCore;
import com.lody.virtual.client.hook.base.MethodProxy;
import com.lody.virtual.client.hook.utils.MethodParameterUtils;
import com.lody.virtual.client.ipc.VPackageManager;
import com.lody.virtual.helper.collection.ArraySet;
import com.lody.virtual.helper.compat.ParceledListSliceCompat;
import com.lody.virtual.helper.utils.ArrayUtils;
import com.lody.virtual.helper.utils.EncodeUtils;
import com.lody.virtual.os.VUserHandle;
import com.lody.virtual.server.IPackageInstaller;
import com.lody.virtual.server.pm.installer.SessionInfo;
import com.lody.virtual.server.pm.installer.SessionParams;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import mirror.android.content.pm.ParceledListSlice;

/**
 * @author Lody
 */
@SuppressWarnings("unused")
class MethodProxies {

    static class IsPackageAvailable extends MethodProxy {

        @Override
        public String getMethodName() {
            return "isPackageAvailable";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String pkgName = (String) args[0];
            if (isAppPkg(pkgName)) {
                return true;
            }
            return method.invoke(who, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetInstallerPackageName extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getInstallerPackageName";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            return "com.android.vending";
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetPreferredActivities extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPreferredActivities";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceLastAppPkg(args);
            return method.invoke(who, args);
        }
    }

    static class GetComponentEnabledSetting extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getComponentEnabledSetting";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            // NOTE: 有4个状态: 0默认 1可用 2禁止 3User Disable
            ComponentName component = (ComponentName) args[0];
            if (component != null) {
                return 1;
            }
            return method.invoke(who, args);
        }
    }

    static class RemovePackageFromPreferred extends MethodProxy {

        @Override
        public String getMethodName() {
            return "removePackageFromPreferred";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }
    }

    /**
     * @author Lody
     *

     *         public ActivityInfo getServiceInfo(ComponentName className, int
     *         flags, int userId)
     */
    static class GetServiceInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getServiceInfo";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            ComponentName componentName = (ComponentName) args[0];
            int flags = (int) args[1];
            int userId = VUserHandle.myUserId();
            ServiceInfo info = VPackageManager.get().getServiceInfo(componentName, flags, userId);
            if (info != null) {
                return info;
            }
            info = (ServiceInfo) method.invoke(who, args);
            if (info == null || !isVisiblePackage(info.applicationInfo)) {
                return null;
            }
            return info;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetPackageUid extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPackageUid";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String pkgName = (String) args[0];
            if (pkgName.equals(getHostPkg())) {
                return method.invoke(who, args);
            }
            int uid = VPackageManager.get().getPackageUid(pkgName, 0);
            return VUserHandle.getAppId(uid);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }

    }

    /**
     * @author Lody
     *

     *

     *         public ActivityInfo getActivityInfo(ComponentName className, int
     *         flags, int userId)
     */
    static class GetActivityInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getActivityInfo";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            ComponentName componentName = (ComponentName) args[0];
            if (getHostPkg().equals(componentName.getPackageName())) {
                return method.invoke(who, args);
            }
            int userId = VUserHandle.myUserId();
            int flags = (int) args[1];
            ActivityInfo info = VPackageManager.get().getActivityInfo(componentName, flags, userId);
            if (info == null) {
                info = (ActivityInfo) method.invoke(who, args);
                if (info == null || !isVisiblePackage(info.applicationInfo)) {
                    return null;
                }
            }
            return info;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetPackageUidEtc extends GetPackageUid {
        @Override
        public String getMethodName() {
            return super.getMethodName() + "Etc";
        }
    }

    static class GetPackageInstaller extends MethodProxy {

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }

        @Override
        public String getMethodName() {
            return "getPackageInstaller";
        }

        @Override
        public Object call(final Object who, Method method, Object... args) throws Throwable {
            final IInterface installer = (IInterface) method.invoke(who, args);
            final IPackageInstaller vInstaller = VPackageManager.get().getPackageInstaller();
            return Proxy.newProxyInstance(installer.getClass().getClassLoader(), installer.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            switch (method.getName()) {
                                case "createSession": {
                                    SessionParams params = SessionParams.create((PackageInstaller.SessionParams) args[0]);
                                    String installerPackageName = (String) args[1];
                                    return vInstaller.createSession(params, installerPackageName, VUserHandle.myUserId());
                                }
                                case "updateSessionAppIcon": {
                                    int sessionId = (int) args[0];
                                    Bitmap appIcon = (Bitmap) args[1];
                                    vInstaller.updateSessionAppIcon(sessionId, appIcon);
                                    return 0;
                                }
                                case "updateSessionAppLabel": {
                                    int sessionId = (int) args[0];
                                    String appLabel = (String) args[1];
                                    vInstaller.updateSessionAppLabel(sessionId, appLabel);
                                    return 0;
                                }
                                case "abandonSession": {
                                    vInstaller.abandonSession((Integer) args[0]);
                                    return 0;
                                }
                                case "openSession": {
                                    return vInstaller.openSession((Integer) args[0]);
                                }
                                case "getSessionInfo": {
                                    SessionInfo info = vInstaller.getSessionInfo((Integer) args[0]);
                                    if (info != null) {
                                        return info.alloc();
                                    }
                                    return null;
                                }
                                case "getAllSessions": {
                                    return ParceledListSliceCompat.create(
                                            vInstaller.getAllSessions((Integer) args[0]).getList()
                                    );
                                }
                                case "getMySessions": {
                                    String installerPackageName = (String) args[0];
                                    int userId = (int) args[1];
                                    return ParceledListSliceCompat.create(
                                            vInstaller.getMySessions(installerPackageName, userId).getList()
                                    );
                                }
                                case "registerCallback": {
                                    IPackageInstallerCallback callback = (IPackageInstallerCallback) args[0];
                                    vInstaller.registerCallback(callback, VUserHandle.myUserId());
                                    return 0;
                                }
                                case "unregisterCallback": {
                                    IPackageInstallerCallback callback = (IPackageInstallerCallback) args[0];
                                    vInstaller.unregisterCallback(callback);
                                    return 0;
                                }
                                case "setPermissionsResult": {
                                    int sessionId = (int) args[0];
                                    boolean accepted = (boolean) args[1];
                                    vInstaller.setPermissionsResult(sessionId, accepted);
                                    return 0;
                                }
                            }
                            throw new RuntimeException("Not support PackageInstaller method : " + method.getName());
                        }
                    });
        }
    }

    static class FreeStorageAndNotify extends MethodProxy {
        @Override
        public String getMethodName() {
            return "freeStorageAndNotify";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            if (args[args.length - 1] instanceof IPackageDataObserver) {
                IPackageDataObserver observer = (IPackageDataObserver) args[args.length - 1];
                observer.onRemoveCompleted(null, true);
            }
            return 0;
        }
    }

    static class GetPackageGids extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPackageGids";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }

    }

    static class RevokeRuntimePermission extends MethodProxy {

        @Override
        public String getMethodName() {
            return "revokeRuntimePermission";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class ClearPackagePreferredActivities extends MethodProxy {

        @Override
        public String getMethodName() {
            return "clearPackagePreferredActivities";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }
    }

    static class ResolveContentProvider extends MethodProxy {

        @Override
        public String getMethodName() {
            return "resolveContentProvider";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String name = (String) args[0];
            int flags = (int) args[1];
            int userId = VUserHandle.myUserId();
            ProviderInfo info = VPackageManager.get().resolveContentProvider(name, flags, userId);
            if (info == null) {
                info = (ProviderInfo) method.invoke(who, args);
                if (info != null && isVisiblePackage(info.applicationInfo)) {
                    return info;
                }
            }
            return info;
        }
    }

    @SuppressWarnings("unchecked")
    static class QueryIntentServices extends MethodProxy {

        @Override
        public String getMethodName() {
            return "queryIntentServices";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            boolean slice = ParceledListSliceCompat.isReturnParceledListSlice(method);
            int userId = VUserHandle.myUserId();
            List<ResolveInfo> appResult = VPackageManager.get().queryIntentServices((Intent) args[0],
                    (String) args[1], (Integer) args[2], userId);
            Object _hostResult = method.invoke(who, args);
            if (_hostResult != null) {
                List<ResolveInfo> hostResult = slice ? ParceledListSlice.getList.call(_hostResult)
                        : (List) _hostResult;
                if (hostResult != null) {
                    Iterator<ResolveInfo> iterator = hostResult.iterator();
                    while (iterator.hasNext()) {
                        ResolveInfo info = iterator.next();
                        if (info == null || info.serviceInfo == null || !isVisiblePackage(info.serviceInfo.applicationInfo)) {
                            iterator.remove();
                        }
                    }
                    appResult.addAll(hostResult);
                }
            }
            if (slice) {
                return ParceledListSliceCompat.create(appResult);
            }
            return appResult;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetPermissions extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPermissions";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            return method.invoke(who, args);
        }
    }

    static class IsPackageForzen extends MethodProxy {

        @Override
        public String getMethodName() {
            return "isPackageForzen";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            return false;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetPackageGidsEtc extends GetPackageGids {

        @Override
        public String getMethodName() {
            return super.getMethodName() + "Etc";
        }

    }

    @SuppressWarnings("unchecked")
    static class QueryIntentActivities extends MethodProxy {

        @Override
        public String getMethodName() {
            return "queryIntentActivities";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            boolean slice = ParceledListSliceCompat.isReturnParceledListSlice(method);
            int userId = VUserHandle.myUserId();
            List<ResolveInfo> appResult = VPackageManager.get().queryIntentActivities((Intent) args[0],
                    (String) args[1], (Integer) args[2], userId);
            Object _hostResult = method.invoke(who, args);
            if (_hostResult != null) {
                List<ResolveInfo> hostResult = slice ? ParceledListSlice.getList.call(_hostResult)
                        : (List) _hostResult;
                if (hostResult != null) {
                    Iterator<ResolveInfo> iterator = hostResult.iterator();
                    while (iterator.hasNext()) {
                        ResolveInfo info = iterator.next();
                        if (info == null || info.activityInfo == null || !isVisiblePackage(info.activityInfo.applicationInfo)) {
                            iterator.remove();
                        }
                    }
                    appResult.addAll(hostResult);
                }
            }
            if (slice) {
                return ParceledListSliceCompat.create(appResult);
            }
            return appResult;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class ResolveService extends MethodProxy {

        @Override
        public String getMethodName() {
            return "resolveService";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            Intent intent = (Intent) args[0];
            String resolvedType = (String) args[1];
            int flags = (int) args[2];
            int userId = VUserHandle.myUserId();
            ResolveInfo resolveInfo = VPackageManager.get().resolveService(intent, resolvedType, flags, userId);
            if (resolveInfo == null) {
                resolveInfo = (ResolveInfo) method.invoke(who, args);
            }
            return resolveInfo;
        }
    }

    static class ClearPackagePersistentPreferredActivities extends MethodProxy {

        @Override
        public String getMethodName() {
            return "clearPackagePersistentPreferredActivities";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }
    }

    static class GetPermissionGroupInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPermissionGroupInfo";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String name = (String) args[0];
            int flags = (int) args[1];
            PermissionGroupInfo info = VPackageManager.get().getPermissionGroupInfo(name, flags);
            if (info != null) {
                return info;
            }
            return super.call(who, method, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static final class GetPackageInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPackageInfo";
        }

        @Override
        public boolean beforeCall(Object who, Method method, Object... args) {
            return args != null && args[0] != null;
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String pkg = (String) args[0];
            int flags = (int) args[1];
            int userId = VUserHandle.myUserId();
            PackageInfo packageInfo = VPackageManager.get().getPackageInfo(pkg, flags, userId);
            if (packageInfo != null) {
                return packageInfo;
            }
            packageInfo = (PackageInfo) method.invoke(who, args);
            if (packageInfo != null) {
                if (isVisiblePackage(packageInfo.applicationInfo)) {
                    return packageInfo;
                }
            }
            return null;
        }

    }

    static class DeleteApplicationCacheFiles extends MethodProxy {

        @Override
        public String getMethodName() {
            return "deleteApplicationCacheFiles";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            // TODO
            return method.invoke(who, args);
        }
    }

    static class SetApplicationBlockedSettingAsUser extends MethodProxy {

        @Override
        public String getMethodName() {
            return "setApplicationBlockedSettingAsUser";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetApplicationEnabledSetting extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getApplicationEnabledSetting";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }
    }

    static class AddPackageToPreferred extends MethodProxy {

        @Override
        public String getMethodName() {
            return "addPackageToPreferred";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            return 0;
        }
    }

    static class CheckPermission extends MethodProxy {

        @Override
        public String getMethodName() {
            return "checkPermission";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String permName = (String) args[0];
            String pkgName = (String) args[1];
            int userId = VUserHandle.myUserId();
            return VPackageManager.get().checkPermission(permName, pkgName, userId);
        }

        @Override
        public Object afterCall(Object who, Method method, Object[] args, Object result) throws Throwable {
            return super.afterCall(who, method, args, result);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetPackagesForUid extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPackagesForUid";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            int uid = (int) args[0];
            int callingUid = Binder.getCallingUid();
            if (uid == VirtualCore.get().myUid()) {
                uid = getBaseVUid();
            }
            String[] callingPkgs = VPackageManager.get().getPackagesForUid(callingUid);
            String[] targetPkgs = VPackageManager.get().getPackagesForUid(uid);
            String[] selfPkgs = VPackageManager.get().getPackagesForUid(Process.myUid());

            Set<String> pkgList = new ArraySet<>(2);
            if (callingPkgs != null && callingPkgs.length > 0) {
                pkgList.addAll(Arrays.asList(callingPkgs));
            }
            if (targetPkgs != null && targetPkgs.length > 0) {
                pkgList.addAll(Arrays.asList(targetPkgs));
            }
            if (selfPkgs != null && selfPkgs.length > 0) {
                pkgList.addAll(Arrays.asList(selfPkgs));
            }
            return pkgList.toArray(new String[pkgList.size()]);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    @SuppressWarnings("unchecked")
    static class QueryContentProviders extends MethodProxy {

        @Override
        public String getMethodName() {
            return "queryContentProviders";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String processName = (String) args[0];
            int uid = (int) args[1];
            int flags = (int) args[2];
            List<ProviderInfo> infos = VPackageManager.get().queryContentProviders(processName, uid, flags);
            if (ParceledListSliceCompat.isReturnParceledListSlice(method)) {
                return ParceledListSliceCompat.create(infos);
            }
            return infos;
        }

    }

    static class SetApplicationEnabledSetting extends MethodProxy {

        @Override
        public String getMethodName() {
            return "setApplicationEnabledSetting";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    @SuppressLint("PackageManagerGetSignatures")
    static class CheckSignatures extends MethodProxy {

        @Override
        public String getMethodName() {
            return "checkSignatures";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {

            if (args.length == 2 && args[0] instanceof String && args[1] instanceof String) {

                PackageManager pm = VirtualCore.getPM();

                String pkgNameOne = (String) args[0], pkgNameTwo = (String) args[1];
                try {
                    PackageInfo pkgOne = pm.getPackageInfo(pkgNameOne, PackageManager.GET_SIGNATURES);
                    PackageInfo pkgTwo = pm.getPackageInfo(pkgNameTwo, PackageManager.GET_SIGNATURES);

                    Signature[] one = pkgOne.signatures;
                    Signature[] two = pkgTwo.signatures;

                    if (ArrayUtils.isEmpty(one)) {
                        if (!ArrayUtils.isEmpty(two)) {
                            return PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
                        } else {
                            return PackageManager.SIGNATURE_NEITHER_SIGNED;
                        }
                    } else {
                        if (ArrayUtils.isEmpty(two)) {
                            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
                        } else {
                            if (Arrays.equals(one, two)) {
                                return PackageManager.SIGNATURE_MATCH;
                            } else {
                                return PackageManager.SIGNATURE_NO_MATCH;
                            }
                        }
                    }
                } catch (Throwable e) {
                    // Ignore
                }
            }

            return method.invoke(who, args);
        }
    }

    static class checkUidSignatures extends MethodProxy {

        @Override
        public String getMethodName() {
            return "checkUidSignatures";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            int uid1 = (int) args[0];
            int uid2 = (int) args[1];
            // TODO: verify the signatures by uid.
            return PackageManager.SIGNATURE_MATCH;
        }
    }

    static class getNameForUid extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getNameForUid";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            int uid = (int) args[0];
            return VPackageManager.get().getNameForUid(uid);
        }
    }

    static class DeletePackage extends MethodProxy {

        @Override
        public String getMethodName() {
            return "deletePackage";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String pkgName = (String) args[0];
            try {
                VirtualCore.get().uninstallPackage(pkgName);
                IPackageDeleteObserver2 observer = (IPackageDeleteObserver2) args[1];
                if (observer != null) {
                    observer.onPackageDeleted(pkgName, 0, "done.");
                }
            } catch (Throwable e) {
                // Ignore
            }
            return 0;
        }

    }

    static class ActivitySupportsIntent extends MethodProxy {
        @Override
        public String getMethodName() {
            return "activitySupportsIntent";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            ComponentName component = (ComponentName) args[0];
            Intent intent = (Intent) args[1];
            String resolvedType = (String) args[2];
            return VPackageManager.get().activitySupportsIntent(component, intent, resolvedType);
        }
    }

    static class ResolveIntent extends MethodProxy {

        @Override
        public String getMethodName() {
            return "resolveIntent";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            Intent intent = (Intent) args[0];
            String resolvedType = (String) args[1];
            int flags = (int) args[2];
            int userId = VUserHandle.myUserId();
            ResolveInfo resolveInfo = VPackageManager.get().resolveIntent(intent, resolvedType, flags, userId);
            if (resolveInfo == null) {
                resolveInfo = (ResolveInfo) method.invoke(who, args);
            }
            return resolveInfo;
        }
    }

    static class GetApplicationInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getApplicationInfo";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            String pkg = (String) args[0];
            int flags = (int) args[1];
            if (getHostPkg().equals(pkg)) {
                return method.invoke(who, args);
            }
            int userId = VUserHandle.myUserId();
            ApplicationInfo info = VPackageManager.get().getApplicationInfo(pkg, flags, userId);
            if (info != null) {
                return info;
            }
            info = (ApplicationInfo) method.invoke(who, args);
            if (info == null || !isVisiblePackage(info)) {
                return null;
            }
            return info;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetProviderInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getProviderInfo";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            ComponentName componentName = (ComponentName) args[0];
            int flags = (int) args[1];
            if (getHostPkg().equals(componentName.getPackageName())) {
                return method.invoke(who, args);
            }
            int userId = VUserHandle.myUserId();
            ProviderInfo info = VPackageManager.get().getProviderInfo(componentName, flags, userId);
            if (info == null) {
                info = (ProviderInfo) method.invoke(who, args);
                if (info == null || !isVisiblePackage(info.applicationInfo)) {
                    return null;
                }
            }
            return info;
        }

    }

    static class SetComponentEnabledSetting extends MethodProxy {

        @Override
        public String getMethodName() {
            // return "setComponentEnabledSetting";
            // anti-virus, fuck ESET-NOD32: a variant of Android/AdDisplay.AdLock.AL potentially unwanted
            return EncodeUtils.decode("c2V0Q29tcG9uZW50RW5hYmxlZFNldHRpbmc=");
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            return 0;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetInstalledApplications extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getInstalledApplications";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {

            int flags = (Integer) args[0];
            int userId = VUserHandle.myUserId();
            List<ApplicationInfo> appInfos = VPackageManager.get().getInstalledApplications(flags, userId);
            if (ParceledListSliceCompat.isReturnParceledListSlice(method)) {
                return ParceledListSliceCompat.create(appInfos);
            }
            return appInfos;
        }
    }

    @SuppressWarnings({"unchecked", "WrongConstant"})
    static class GetInstalledPackages extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getInstalledPackages";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            int flags = (int) args[0];
            int userId = VUserHandle.myUserId();
            List<PackageInfo> packageInfos;
            if (isAppProcess()) {
                packageInfos = new ArrayList<>(VirtualCore.get().getInstalledAppCount());
            } else {
                packageInfos = VirtualCore.get().getUnHookPackageManager().getInstalledPackages(flags);
            }
            packageInfos.addAll(VPackageManager.get().getInstalledPackages(flags, userId));
            if (ParceledListSliceCompat.isReturnParceledListSlice(method)) {
                return ParceledListSliceCompat.create(packageInfos);
            } else {
                return packageInfos;
            }
        }
    }

    @SuppressWarnings("unchecked")
    static class QueryIntentReceivers extends MethodProxy {

        @Override
        public String getMethodName() {
            return "queryIntentReceivers";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            boolean slice = ParceledListSliceCompat.isReturnParceledListSlice(method);
            int userId = VUserHandle.myUserId();
            List<ResolveInfo> appResult = VPackageManager.get().queryIntentReceivers((Intent) args[0], (String) args[1],
                    (Integer) args[2], userId);
            Object _hostResult = method.invoke(who, args);
            List<ResolveInfo> hostResult = slice ? ParceledListSlice.getList.call(_hostResult)
                    : (List) _hostResult;
            if (hostResult != null) {
                Iterator<ResolveInfo> iterator = hostResult.iterator();
                while (iterator.hasNext()) {
                    ResolveInfo info = iterator.next();
                    if (info == null || info.activityInfo == null || !isVisiblePackage(info.activityInfo.applicationInfo)) {
                        iterator.remove();
                    }
                }
                appResult.addAll(hostResult);
            }
            if (slice) {
                return ParceledListSliceCompat.create(appResult);
            }
            return appResult;
        }
    }

    static class GetReceiverInfo extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getReceiverInfo";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            ComponentName componentName = (ComponentName) args[0];
            if (getHostPkg().equals(componentName.getPackageName())) {
                return method.invoke(who, args);
            }
            int flags = (int) args[1];
            ActivityInfo info = VPackageManager.get().getReceiverInfo(componentName, flags, 0);
            if (info == null) {
                info = (ActivityInfo) method.invoke(who, args);
                if (info == null || !isVisiblePackage(info.applicationInfo)) {
                    return null;
                }
            }
            return info;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    static class GetPermissionFlags extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getPermissionFlags";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            // TODO
            return method.invoke(who, args);
        }

    }

    static class SetPackageStoppedState extends MethodProxy {

        @Override
        public String getMethodName() {
            return "setPackageStoppedState";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    @SuppressWarnings("unchecked")
    @TargetApi(Build.VERSION_CODES.KITKAT)
    static class QueryIntentContentProviders extends MethodProxy {

        @Override
        public String getMethodName() {
            return "queryIntentContentProviders";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            boolean slice = ParceledListSliceCompat.isReturnParceledListSlice(method);
            int userId = VUserHandle.myUserId();
            List<ResolveInfo> appResult = VPackageManager.get().queryIntentContentProviders((Intent) args[0], (String) args[1],
                    (Integer) args[2], userId);
            Object _hostResult = method.invoke(who, args);
            List<ResolveInfo> hostResult = slice ? ParceledListSlice.getList.call(_hostResult)
                    : (List) _hostResult;
            if (hostResult != null) {
                Iterator<ResolveInfo> iterator = hostResult.iterator();
                while (iterator.hasNext()) {
                    ResolveInfo info = iterator.next();
                    if (info == null || info.providerInfo == null || !isVisiblePackage(info.providerInfo.applicationInfo)) {
                        iterator.remove();
                    }
                }
                appResult.addAll(hostResult);
            }
            if (ParceledListSliceCompat.isReturnParceledListSlice(method)) {
                return ParceledListSliceCompat.create(appResult);
            }
            return appResult;
        }

        @Override
        public boolean isEnable() {
            return isAppProcess();
        }
    }

    static class GetApplicationBlockedSettingAsUser extends MethodProxy {

        @Override
        public String getMethodName() {
            return "getApplicationBlockedSettingAsUser";
        }

        @Override
        public Object call(Object who, Method method, Object... args) throws Throwable {
            MethodParameterUtils.replaceFirstAppPkg(args);
            return method.invoke(who, args);
        }
    }

}


#
# This program is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
# Foundation.
#
# You should have received a copy of the GNU Lesser General Public License along with this
# program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
# or from the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# Copyright (c) 2005-2017 Hitachi Vantara.  All rights reserved.
#

display-name=RTF / Flow + ZIP
grouping=Core
grouping.ordinal=50
ordinal=10
deprecated=


// -*- mode: c++; c-basic-offset: 4; -*-
// Copyright 2005,2006,2007 Markus Schordan, Gergo Barany
// $Id: pag_support.C,v 1.19 2009-02-09 11:02:36 gergo Exp $

#include <iostream>

#include <satire_rose.h>

#include "syntree.h"
#include "pignodelist.h"
#include "pag_support.h"
#include "IrCreation.h"

CFG *global_cfg = NULL;

CFG *get_global_cfg()
{
    return global_cfg;
}

PIG_EXTERN_C
const char *basic_type_name(const void *p)
{
    const SgNode *node = (SgNode *) p;

    switch (node->variantT())
    {
    case V_SgTypeBool: return "bool"; break;
    case V_SgTypeChar: return "char"; break;
    case V_SgTypeDouble: return "double"; break;
    case V_SgTypeFloat: return "float"; break;
    case V_SgTypeInt: return "int"; break;
    case V_SgTypeLong: return "long"; break;
    case V_SgTypeLongDouble: return "long double"; break;
    case V_SgTypeLongLong: return "long long"; break;
    case V_SgTypeShort: return "short"; break;
    case V_SgTypeSignedChar: return "signed char"; break;
    case V_SgTypeSignedInt: return "signed int"; break;
    case V_SgTypeSignedLong: return "signed long"; break;
    case V_SgTypeSignedShort: return "signed short"; break;
    case V_SgTypeString: return "string"; break;
    case V_SgTypeUnsignedChar: return "unsigned char"; break;
    case V_SgTypeUnsignedInt: return "unsinged int"; break;
    case V_SgTypeUnsignedLong: return "unsigned long"; break;
    case V_SgTypeUnsignedLongLong: return "unsigned long long"; break;
    case V_SgTypeUnsignedShort: return "unsigned short"; break;
    case V_SgTypeVoid: return "void"; break;
    case V_SgTypeWchar: return "wchar"; break;
    default: return NULL;
    }
}

#if HAVE_PAG

// GB (2008-05-08): The manual doesn't tell you this, but apparently these
// need to be initialized to negative values in the beginning; then the
// analyzer generated by PAG will call the syntax_init function, which is
// important.
int syntaxtype = -1;
int e_syntaxtype = -1;

#if OLD_GET_VALUE
#define get_value_macro(T) char *T##_get_value(void *s) \
    { if (s == NULL) return "<null>"; return (char *) s; }
#else
#define get_value_macro(T) char *T##_get_value(T x) \
{ std::stringstream s; s << x; return Ir::getCharPtr(s.str()); }
#endif

PIG_EXTERN_C get_value_macro(astint)
PIG_EXTERN_C get_value_macro(aststring)
PIG_EXTERN_C get_value_macro(astshort)
PIG_EXTERN_C get_value_macro(astchar)
PIG_EXTERN_C get_value_macro(astuchar)
PIG_EXTERN_C get_value_macro(astushort)
PIG_EXTERN_C get_value_macro(astuint)
PIG_EXTERN_C get_value_macro(astlong)
PIG_EXTERN_C get_value_macro(astllong)
PIG_EXTERN_C get_value_macro(astullong)
PIG_EXTERN_C get_value_macro(astulong)
PIG_EXTERN_C get_value_macro(astfloat)
PIG_EXTERN_C get_value_macro(astdouble)
PIG_EXTERN_C get_value_macro(astldouble)

#include "str.h"

PIG_EXTERN_C
const char *Expression_print(void *e)
{
    std::cout << expr_to_string(isSgExpression((SgNode *) e)) << std::flush;
    return str_create("");
}

PIG_EXTERN_C
const char *c_str_print(const void *s)
{
    std::cout << (const char *) s;
    return (const char *) s;
}

PIG_EXTERN_C
const char *LIST_VariableSymbolNT_print(void **l)
{
    std::cout << "[!";
    while (*l != NULL)
    {
        SgVariableSymbol *sym = (SgVariableSymbol *) *l;
        std::cout << sym->get_name().str() << ",";
        l++;
    }
    std::cout << "!]";
    return str_create("");
}

PIG_EXTERN_C
const char *Statement_print(void *s)
{
    SgStatement *stmt = isSgStatement((SgNode *) s);
    if (stmt != NULL && !isSgDoWhileStmt(stmt))
        std::cout << Ir::fragmentToString(stmt) << std::flush;
    else
        std::cout << ((SgNode *) s)->class_name() << std::flush;
    return str_create("");
}

// GB (2007-10-31): This has been commented out for a while. The reason is
// that these functions are now generated by pig.
#if 0
PIG_EXTERN_C
int LIST_VariableSymbolNT_empty(void *l)
{
    return ((PigNodeList *) l)->empty();
}

PIG_EXTERN_C
void *LIST_VariableSymbolNT_hd(void *l)
{
    return ((PigNodeList *) l)->head();
}

PIG_EXTERN_C
void *LIST_VariableSymbolNT_tl(void *l)
{
    return ((PigNodeList *) l)->tail();
}
#endif

#include "genkfg.h"

KFG_ATTR_DEF empty = { 0 };
KFG_ATTR_DEF *addr = ∅
int zero = 0;

char const *kfg_get_attribute_symbol(char *)
{
    return NULL;
}

int kfg_get_global_attribute_information(KFG, KFG_ATTR_DEF **arr, int *len)
{
    arr = &addr;
    len = &zero;
    return 1;
}

int kfg_get_routine_attribute_information(KFG, KFG_ATTR_DEF **arr, int *len)
{
    arr = &addr;
    len = &zero;
    return 1;
}

int kfg_get_bblock_attribute_information(KFG, KFG_ATTR_DEF **arr, int *len)
{
    arr = &addr;
    len = &zero;
    return 1;
}

int kfg_get_instruction_attribute_information(KFG, KFG_ATTR_DEF **arr, int *len)
{
    arr = &addr;
    len = &zero;
    return 1;
}

int kfg_remap_global_attributes(KFG, KFG_ATTR_DEF **, int)
{
    return 1;
}

int kfg_remap_routine_attributes(KFG, KFG_ATTR_DEF **, int)
{
    return 1;
}

int kfg_remap_bblock_attributes(KFG, KFG_ATTR_DEF **, int)
{
    return 1;
}

int kfg_remap_instruction_attributes(KFG, KFG_ATTR_DEF **, int)
{
    return 1;
}

char const *kfg_get_global_attribute(KFG, int)
{
    return "";
}

char const *kfg_get_routine_attribute(KFG, int, int)
{
    return "";
}

char const *kfg_get_bblock_attribute(KFG, KFG_NODE, int)
{
    return "";
}

char const *kfg_get_instruction_attribute(KFG, KFG_NODE, int, int)
{
    return "";
}

char const *kfg_get_global_attribute_by_name(KFG, char *)
{
    return "";
}

char const *kfg_get_routine_attribute_by_name(KFG, int, char*)
{
    return "";
}

char const *kfg_get_bblock_attribute_by_name(KFG, KFG_NODE, char *)
{
    return "";
}

char const *kfg_get_instruction_attribute_by_name(KFG, KFG_NODE, int, char *)
{
    return "";
}

// GB (2008-08-21): Inclusion of snum.h, below, also includes "general.h".
// Funnily, this is supposed to include PAG's general.h, but there is also
// one in ROSE, which takes precedence due to -I flags. But that's OK,
// actually.
// What's not OK is that ROSE's general.h #defines FALSE and TRUE without
// definition guards. However, these macros are also defined (in an
// incompatible way, but ironically *with* guards) by sage3.h, which is
// already included via satire_rose.h. So all in all, including "snum.h"
// fails with a multiple definition error. We will try to get around this by
// undefining TRUE and FALSE here.
#undef TRUE
#undef FALSE

/* static attributes */
//#define HAVE_MEMMOVE
#include "pagheader.h"
#include "snum.h"
#include "unum.h"
/* list of global variables */
extern "C" void *kfg_get_global_attribute__globals(KFG cfg)
{
    return Ir::createNodeList(((CFG *) cfg)->globals);
 // return new PigNodeList(((CFG *) cfg)->globals);
}
/* numbers of types and expressions */
extern "C" unum kfg_get_global_attribute__numtypes(KFG cfg)
{
    return int_to_unum(((CFG *) cfg)->types_numbers.size());
}
extern "C" unum kfg_get_global_attribute__numexprs(KFG cfg)
{
    return int_to_unum(((CFG *) cfg)->numbers_exprs.size());
}
/* number of the current procedure */
extern "C" snum kfg_get_routine_attribute__procnum(KFG, int procnum)
{
    return int_to_snum(procnum);
}
/* statement labels */
extern "C" snum kfg_get_bblock_attribute__label(KFG cfg, KFG_NODE bb)
{
    return int_to_snum(kfg_get_id(cfg, bb));
}
/* position (context) IDs */
extern "C" snum kfg_get_position_attribute__position(KFG, KFG_NODE, int, int p)
{
    return int_to_snum(p);
}
/* context objects */
#include "o_ContextInfo.h"
extern "C" void *kfg_get_position_attribute__context(KFG cfg, KFG_NODE bb,
                                                     int, int position)
{
    ContextInfo c(kfg_procnumnode(cfg, bb), position);
    return o_ContextInfo_duplicate(&c);
}

/* external support functions */
#include "bool.h"
extern "C" FLO_BOOL o_is_unary(void *expr)
{
    return (isSgUnaryOp((SgNode *) expr) ? FLO_TRUE : FLO_FALSE);
}

extern "C" FLO_BOOL o_is_binary(void *expr)
{
    return (isSgBinaryOp((SgNode *) expr) ? FLO_TRUE : FLO_FALSE);
}

extern "C" FLO_BOOL o_is_value(void *expr)
{
    return (isSgValueExp((SgNode *) expr) ? FLO_TRUE : FLO_FALSE);
}

#include "assert.h"

extern "C" void *o_unary_get_child(void *expr)
{
    assert(o_is_unary(expr) == FLO_TRUE);
    return isSgUnaryOp((SgNode *) expr)->get_operand();
}

extern "C" FLO_BOOL o_unary_is_prefix(void *expr)
{
    assert(o_is_unary(expr) == FLO_TRUE);
    return (isSgUnaryOp((SgNode *) expr)->get_mode() == SgUnaryOp::prefix ?
            FLO_TRUE : FLO_FALSE);
}

extern "C" void *o_binary_get_left_child(void *expr)
{
    assert(o_is_binary(expr) == FLO_TRUE);
    return isSgBinaryOp((SgNode *) expr)->get_lhs_operand();
}

extern "C" void *o_binary_get_right_child(void *expr)
{
    assert(o_is_binary(expr) == FLO_TRUE);
    return isSgBinaryOp((SgNode *) expr)->get_rhs_operand();
}

// GB (2008-07-01): Global variables are not very elegant. I know.
extern bool satire_warn_deprecated;

extern "C" void *o_typenum_to_type(unum n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'typenum_to_type'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return get_global_cfg()->numbers_types[unum_to_unsigned(n)];
}

extern "C" unum o_type_to_typenum(void *type)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'type_to_typenum'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return int_to_unum(get_global_cfg()->types_numbers[isSgType((SgNode *) type)]);
}

#include "str.h"

extern "C" str o_typenum_to_str(unum n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'typenum_to_str'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return Ir::getCharPtr(Ir::fragmentToString(isSgType((SgNode *)o_typenum_to_type(n))));
}

extern "C" void *o_exprnum_to_expr(unum n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'exprnum_to_expr'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return get_global_cfg()->numbers_exprs[unum_to_unsigned(n)];
}

extern "C" unum o_expr_to_exprnum(void *expr)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'expr_to_exprnum'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return int_to_unum(get_global_cfg()->exprs_numbers[isSgExpression((SgNode *) expr)]);
}

extern "C" str o_exprnum_to_str(unum n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'exprnum_to_str'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return expr_to_string((SgExpression *) o_exprnum_to_expr(n));
}

extern "C" void *o_expr_type(void *expr)
{
    return isSgExpression((SgNode *) expr)->get_type();
}

extern "C" unum o_exprnum_typenum(unum n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'exprnum_typenum'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return o_type_to_typenum(o_expr_type(o_exprnum_to_expr(n)));
}

extern "C" FLO_BOOL o_is_subtype_of(void *a, void *b)
{
    SgClassType *at = isSgClassType((SgType *) a),
                *bt = isSgClassType((SgType *) b);
    /* a is subtype of b if a inherits from b: look at a's
     * inheritances (base classes) */
    if (at == NULL) return FLO_FALSE;
    if (bt == NULL) return FLO_FALSE;
    const SgBaseClassPtrList &base_classes =
        isSgClassDeclaration(at->get_declaration())->get_definition()
            ->get_inheritances();
    SgBaseClassPtrList::const_iterator i;
    for (i = base_classes.begin(); i != base_classes.end(); ++i)
    {
        SgClassDeclaration *base = (*i)->get_base_class();
        SgClassDeclaration *bdecl
            = isSgClassDeclaration(bt->get_declaration());
        if (base == bdecl || (base->get_type() != NULL && bdecl != NULL
                    && o_is_subtype_of(base->get_type(), bdecl->get_type())))
            return FLO_TRUE;
    }
    return FLO_FALSE;
}

extern "C" FLO_BOOL o_is_subtypenum_of(unum a, unum b)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'is_subtypenum_of'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return o_is_subtype_of(o_typenum_to_type(a), o_typenum_to_type(b));
}

extern "C" void *o_global_get_type(void *symbol)
{
    SgVariableSymbol *varsym = (SgVariableSymbol *) symbol;
    return varsym->get_type();
}

extern "C" FLO_BOOL o_global_has_initializer(void *symbol)
{
    SgVariableSymbol *varsym = (SgVariableSymbol *) symbol;
    if (get_global_cfg()->globals_initializers.find(varsym)
            != get_global_cfg()->globals_initializers.end())
    {
        return FLO_TRUE;
    }
    else
        return FLO_FALSE;
}

extern "C" void *o_global_get_initializer(void *symbol)
{
    SgVariableSymbol *varsym = (SgVariableSymbol *) symbol;
    return get_global_cfg()->globals_initializers[varsym];
}

extern "C" FLO_BOOL o_global_has_defining_declaration(void *symbol)
{
    SgVariableSymbol *varsym = (SgVariableSymbol *) symbol;
    std::map<SgVariableSymbol *, const SgVariableDeclaration *>::iterator pos
        = get_global_cfg()->globals_definingdecls.find(varsym);
    if (pos != get_global_cfg()->globals_definingdecls.end()
        && pos->second != NULL)
    {
        return FLO_TRUE;
    }
    else
        return FLO_FALSE;
}

extern "C" FLO_BOOL o_is_integer_type(void *t)
{
    SgType *type = (SgType *) t;
    return (type->isIntegerType() ? FLO_TRUE : FLO_FALSE);
}

// GB (2008-08-04): Two functions requested by Viktor to make the structure
// of ASTs explicit when trying to write patterns that match them.
extern "C" str o_stmt_asttext(void *statement)
{
    SgStatement *stmt = (SgStatement *) statement;
    std::string result = Ir::fragmentToTreeRepresentation(stmt);
    return Ir::getCharPtr(result);
}

extern "C" str o_expr_asttext(void *expression)
{
    SgExpression *expr = (SgExpression *) expression;
    std::string result = Ir::fragmentToTreeRepresentation(expr);
    return Ir::getCharPtr(result);
}

// GB (2008-05-09): This function returns a variable symbol's "ID", which is
// just the expression number that we also assign to uses of the same
// variable. These IDs are computed by the ICFG builder after having
// numbered all expressions.
// GB (2008-05-13): (Temporarily?) renamed "ID" to varnum because the
// VariableID class was introduced.
// GB (2008-07-01): This function apprears unnecessary because we have
// varsym_varid and varref_varid; it was also never documented, apparently.
#if 0
extern "C" unum o_variable_varnum(void *symbol)
{
    SgVariableSymbol *varsym = (SgVariableSymbol *) symbol;
    unsigned long id = get_global_cfg()->varsyms_ids[varsym];
    return int_to_unum(id);
}
#endif

extern "C" str o_exp_root_str(void *exp)
{
    /* WARNING: This is not clean at all, but the Value Flow Graph
     * analysis relies on the fact that the strings representing
     * operators returned by this function begin with "op " (yes,
     * including the space character; that ensures it is not a
     * variable name beginning with "op").
     * Please do not change that without due cause, thanks. */
    SgExpression *expr = isSgExpression((SgNode *) exp);
    if (expr == NULL)
        return "'not an expression'";
    else switch (expr->variantT())
    {
    case V_SgAddOp:             return "op +";
    case V_SgSubtractOp:        return "op -";
    case V_SgMultiplyOp:        return "op *";
    case V_SgDivideOp:          return "op / (floating)";
    case V_SgIntegerDivideOp:   return "op / (integer)";
    case V_SgModOp:             return "op %";
    case V_SgAndOp:             return "op &&";
    case V_SgOrOp:              return "op ||";
    case V_SgBitXorOp:          return "op ^";
    case V_SgBitAndOp:          return "op &";
    case V_SgBitOrOp:           return "op |";
    case V_SgLshiftOp:          return "op <<";
    case V_SgRshiftOp:          return "op >>";
    case V_SgMinusOp:           return "op - (unary)";
    case V_SgPointerDerefExp:   return "op * (dereference)";
    case V_SgAddressOfOp :      return "op & (address of)";
    case V_SgVarRefExp:
        {
            SgVarRefExp *v = isSgVarRefExp(expr);
            std::string name = v->get_symbol()->get_name().str();
            return Ir::getCharPtr(name);
        }
    case V_SgIntVal:
        {
            std::stringstream value;
            value << isSgIntVal((SgNode *) expr)->get_value();
            return Ir::getCharPtr(value.str());
        }
    default:
        {
            SgValueExp *ve = isSgValueExp(expr);
            if (ve != NULL)
                return expr_to_string(ve);
            std::string class_name = expr->class_name();
            return Ir::getCharPtr(class_name);
        }
    }
}

extern "C" FLO_BOOL o_is_operatorname(str s)
{
    return (strncmp(s, "op ", 3) == 0 ? FLO_TRUE : FLO_FALSE);
}

#include <string.h>
#include "gc_mem.h"

unsigned long synttype_hash(void *x)
{
    return (unsigned long) x;
}

int syntax_eq(void *x, void *y)
{
    return (strcmp((const char *) x, (const char *) y) != 0);
}

void syntax_mcopy(void *x, void *y)
{
    strcpy((char *) y, (const char *) x);
}

void syntaxdummy(void *)
{
}

#ifdef __cplusplus
extern "C"
#endif
void syntax_init(void)
{
    bool calledBefore = false;
    if (!calledBefore)
    {
     // GB (2008-05-08): This code is required by PAG; in the manual I have,
     // it is in Section 9.4 "Additional Requirements" of Chapter 9
     // "Frontend Interface Reference".
        syntaxtype = GC_registertype(48, syntaxdummy, syntax_mcopy,
            syntax_eq, synttype_hash, 0);
        e_syntaxtype = GC_registertype(1024, syntaxdummy, syntax_mcopy,
            syntax_eq, synttype_hash, 0);
     // Don't execute this code again, even if this function should be
     // called again.
        calledBefore = true;
    }
}

#include "ast_support_funcs.h"

// GB (2007-10-31): These are not marked extern "C" because they are not
// called directly from the PAG code; PAG calls the functions with the o_
// prefixes.
SgType *typenum_to_type(unsigned long n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'typenum_to_type'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return get_global_cfg()->numbers_types[n];
}

unsigned long type_to_typenum(SgType *type)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'type_to_typenum'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return get_global_cfg()->types_numbers[type];
}

std::string typenum_to_str(unsigned long n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'typenum_to_str'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return Ir::fragmentToString(typenum_to_type(n));
}

SgExpression *exprnum_to_expr(unsigned long n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'exprnum_to_expr'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return get_global_cfg()->numbers_exprs[n];
}

unsigned long expr_to_exprnum(SgExpression *expr)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'expr_to_exprnum'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return get_global_cfg()->exprs_numbers[expr];
}

std::string exprnum_to_str(unsigned long n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'exprnum_to_str'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return expr_to_string(exprnum_to_expr(n));
}

SgType *expr_type(SgExpression *expr)
{
    return expr->get_type();
}

unsigned long exprnum_typenum(unsigned long n)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'exprnum_typenum'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    return type_to_typenum(expr_type(exprnum_to_expr(n)));
}

bool is_subtype_of(SgClassType *a, SgClassType *b)
{
    return o_is_subtype_of(a, b) == FLO_TRUE;
}

bool is_subtypenum_of(unsigned long a, unsigned long b)
{
    if (satire_warn_deprecated)
    {
        std::cerr
            << "** Warning: calling deprecated SATIrE support function 'is_subtypenum_of'"
            << std::endl
            << "(use --no-warn-deprecated command line flag to suppress this warning)"
            << std::endl;
    }
    SgClassType *ta = isSgClassType(typenum_to_type(a));
    SgClassType *tb = isSgClassType(typenum_to_type(b));
    return (ta != NULL && tb != NULL && is_subtype_of(ta, tb));
}

// Two support functions that PAG suddenly started to require at some point.
int kfg_routine_is_loop (KFG cfg, KFG_ROUTINE routine)
{
    return 0;
}

int kfg_routine_is_infeasible (KFG cfg, KFG_ROUTINE routine)
{
    return 0;
}

#endif