text:
Adversaries may try to gather information about registered local system services. Adversaries may obtain information about services using tools as well as OS utility commands such as sc query, tasklist /svc, systemctl --type=service, and net start.

Adversaries may use the information from [System Service Discovery](https://attack.mitre.org/techniques/T1007) during automated discovery to shape follow-on behaviors, including whether or not the adversary fully infects the target and/or attempts specific actions.

## Atomic Tests

- [Atomic Test #1 - System Service Discovery](#atomic-test-1---system-service-discovery)

- [Atomic Test #2 - System Service Discovery - net.exe](#atomic-test-2---system-service-discovery---netexe)

- [Atomic Test #3 - System Service Discovery - systemctl](#atomic-test-3---system-service-discovery---systemctl)

## Atomic Test #1 - System Service Discovery
Identify system services.

Upon successful execution, cmd.exe will execute service commands with expected result to stdout.

**Supported Platforms:** Windows

**auto_generated_guid:** 89676ba1-b1f8-47ee-b940-2e1a113ebc71

#### Attack Commands: Run with `command_prompt`!  Elevation Required (e.g. root or admin)

```cmd
tasklist.exe
sc query
sc query state= all
```

## Atomic Test #2 - System Service Discovery - net.exe
Enumerates started system services using net.exe and writes them to a file. This technique has been used by multiple threat actors.

Upon successful execution, net.exe will run from cmd.exe that queries services. Expected output is to a txt file in c:\Windows\Temp\service-list.txt.s

**Supported Platforms:** Windows

**auto_generated_guid:** 5f864a3f-8ce9-45c0-812c-bdf7d8aeacc3

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| output_file | Path of file to hold net.exe output | Path | C:\Windows\Temp\service-list.txt|

#### Attack Commands: Run with `command_prompt`!

```cmd
net.exe start >> #{output_file}
```

#### Cleanup Commands:
```cmd
del /f /q /s #{output_file} >nul 2>&1
```

## Atomic Test #3 - System Service Discovery - systemctl
Enumerates system service using systemctl

**Supported Platforms:** Linux

**auto_generated_guid:** f4b26bce-4c2c-46c0-bcc5-fce062d38bef

#### Attack Commands: Run with `bash`!

```bash
systemctl --type=service
```

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Fidry\AliceDataFixtures\Bridge\DoctrinePhpCr\Purger;

use Doctrine\Common\DataFixtures\Purger\ORMPurger as DoctrineOrmPurger;
use Doctrine\Common\DataFixtures\Purger\PHPCRPurger;
use Doctrine\ODM\PHPCR\DocumentManager;
use Fidry\AliceDataFixtures\Bridge\Doctrine\Purger\Purger;
use Fidry\AliceDataFixtures\Persistence\PurgerFactoryInterface;
use Fidry\AliceDataFixtures\Persistence\PurgerInterface;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use ReflectionClass;
use ReflectionObject;

/**
 * @covers \Fidry\AliceDataFixtures\Bridge\Doctrine\Purger\Purger
 */
class PurgerTest extends TestCase
{
    use ProphecyTrait;

    public function testIsAPurger(): void
    {
        self::assertTrue(is_a(Purger::class, PurgerInterface::class, true));
    }

    public function testIsAPurgerFactory(): void
    {
        self::assertTrue(is_a(Purger::class, PurgerFactoryInterface::class, true));
    }

    public function testIsNotClonable(): void
    {
        self::assertFalse((new ReflectionClass(Purger::class))->isCloneable());
    }

    public function testCreatesADoctrineOrmPurgerWithTheAppropriateManagerAndPurgeMode(): void
    {
        $manager = $this->prophesize(DocumentManager::class)->reveal();
        $purger = new Purger($manager);

        $decoratedPurgerReflection = (new ReflectionObject($purger))->getProperty('purger');
        $decoratedPurgerReflection->setAccessible(true);
        /** @var DoctrineOrmPurger $decoratedPurger */
        $decoratedPurger = $decoratedPurgerReflection->getValue($purger);

        self::assertInstanceOf(PHPCRPurger::class, $decoratedPurger);
        self::assertEquals($manager, $decoratedPurger->getObjectManager());
    }
}


text:
var webpack = require('webpack')

module.exports = {

  output: {
    library: 'History',
    libraryTarget: 'umd'
  },

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel?stage=0&loose=all' }
    ]
  },

  node: {
    Buffer: false
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
    })
  ]

}


text:
template <typename Item>
class all_custom_container
{
private :
    std::deque<Item> m_hidden_deque;

public :
    typedef typename std::deque<Item>::iterator custom_iterator_type;
    typedef typename std::deque<Item>::const_iterator custom_const_iterator_type;

    inline std::size_t custom_size() const { return m_hidden_deque.size(); }

    inline custom_const_iterator_type custom_begin() const { return m_hidden_deque.begin(); }
    inline custom_const_iterator_type custom_end() const { return m_hidden_deque.end(); }
    inline custom_iterator_type custom_begin() { return m_hidden_deque.begin(); }
    inline custom_iterator_type custom_end() { return m_hidden_deque.end(); }

    inline void custom_clear() { m_hidden_deque.clear(); }
    inline void custom_push_back(Item const& p) { m_hidden_deque.push_back(p); }
    inline void custom_resize(std::size_t new_size) { m_hidden_deque.resize(new_size); }
};

// 1. Adapt to Boost.Geometry (for e.g. inner rings)
namespace boost { namespace geometry
{

namespace traits
{
    template <typename Item>
    struct clear<all_custom_container<Item> >
    {
        static inline void apply(all_custom_container<Item>& container)
        {
            container.custom_clear();
        }
    };

    template <typename Item>
    struct push_back<all_custom_container<Item> >
    {
        static inline void apply(all_custom_container<Item>& container, Item const& item)
        {
            container.custom_push_back(item);
        }
    };

    template <typename Item>
    struct resize<all_custom_container<Item> >
    {
        static inline void apply(all_custom_container<Item>& container, std::size_t new_size)
        {
            container.custom_resize(new_size);
        }
    };

} // namespace traits

}} // namespace boost::geometry

// 2a. Adapt to Boost.Range, meta-functions
namespace boost
{
    template<typename Item>
    struct range_mutable_iterator<all_custom_container<Item> >
    {
        typedef typename all_custom_container<Item>::custom_iterator_type type;
    };

    template<typename Item>
    struct range_const_iterator<all_custom_container<Item> >
    {
        typedef typename all_custom_container<Item>::custom_const_iterator_type  type;
    };

} // namespace boost

// 2b. Adapt to Boost.Range, part 2, ADP

template<typename Item>
inline typename all_custom_container<Item>::custom_iterator_type
    range_begin(all_custom_container<Item>& container)
{
    return container.custom_begin();
}

template<typename Item>
inline typename all_custom_container<Item>::custom_const_iterator_type
    range_begin(all_custom_container<Item> const& container)
{
    return container.custom_begin();
}

template<typename Item>
inline typename all_custom_container<Item>::custom_iterator_type
    range_end(all_custom_container<Item>& container)
{
    return container.custom_end();
}

template<typename Item>
inline typename all_custom_container<Item>::custom_const_iterator_type
    range_end(all_custom_container<Item> const& container)
{
    return container.custom_end();
}

// (Optional)
template<typename Item>
inline std::size_t range_calculate_size(all_custom_container<Item> const& container)
{
    return container.custom_size();
}

#endif // GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_CONTAINER_HPP


text:
[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20BarCode%20Reader%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20BarCode%20Reader%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=EARSPJFIJMU](https://www.youtube.com/watch?v=EARSPJFIJMU)

<!-- code block begin -->

##### **Module1.vb:**

```
Imports System.IO
Imports Bytescout.BarCodeReader

Module Module1

    Sub Main()

        ' Replace barcode input file path here
        Const InputFile As String = "InputBarcodeImage.jpg"

        Console.WriteLine("Reading barcode(s) from image {0}", Path.GetFullPath(InputFile))

        Dim reader As New Reader()
        reader.RegistrationName = "demo"
        reader.RegistrationKey = "demo"

        ' Set barcode type to find
        reader.BarcodeTypesToFind.PDF417 = True

        ' -----------------------------------------------------------------------
        ' NOTE: We can read barcodes from specific page to increase performance .
        ' For sample please refer to "Decoding barcodes from PDF by pages" program.
        ' -----------------------------------------------------------------------

        ' Read barcodes
        Dim barcodes As FoundBarcode() = reader.ReadFrom(InputFile)

        If barcodes.Length > 0 Then

            Dim barcode As FoundBarcode = barcodes(0)

            ' Get specific fields

            Dim identificationCard As IdentificationCard = barcode.Metadata

            If Not identificationCard Is Nothing Then

                Console.WriteLine("ID Numer: " + identificationCard.IdNumber)
                Console.WriteLine("First Name: " + identificationCard.Name.First)
                Console.WriteLine("Middle Name: " + identificationCard.Name.Middle)
                Console.WriteLine("Last Name: " + identificationCard.Name.Last)
                Console.WriteLine("Sex: " + identificationCard.Sex.ToString())
                Console.WriteLine("Date Of Birth: " + identificationCard.DateOfBirth)
                Console.WriteLine("Address: " + identificationCard.Address.ToString())

                If TypeOf identificationCard Is DriversLicense Then
                    Dim driverLicense As DriversLicense = identificationCard

                    Console.WriteLine("Vehicle Class: " + driverLicense.Jurisdiction.VehicleClass)
                    Console.WriteLine("Endorsement Codes: " + driverLicense.Jurisdiction.EndorsementCodes)
                    Console.WriteLine("Restriction Codes: " + driverLicense.Jurisdiction.RestrictionCodes)
                End If

            Else
                Console.WriteLine("Could not retrieve AAMVA data from this barcode. Raw value: " + Environment.NewLine + barcode.Value)
            End If

            ' ... Or get the full information as JSON
            Console.WriteLine(Environment.NewLine + Environment.NewLine + "-----------------" + Environment.NewLine)

            Dim jsonString = reader.ExportFoundBarcodesToJSON()
            Console.WriteLine(jsonString)

        Else
            Console.WriteLine("No barcodes found!")
        End If

        ' Cleanup
        reader.Dispose()

        Console.WriteLine("Press any key to exit..")
        Console.ReadKey()

    End Sub

End Module

```

<!-- code block end -->

<!-- code block begin -->

##### **ReadDriverLicenseInformation.NETCore.vbproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
    <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
    <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
    <GenerateAssemblyFileVersionAttribute>false</GenerateAssemblyFileVersionAttribute>
    <GenerateAssemblyInformationalVersionAttribute>false</GenerateAssemblyInformationalVersionAttribute>
    <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
    <GenerateAssemblyTitleAttribute>false</GenerateAssemblyTitleAttribute>
    <GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
    <GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
    <GenerateAssemblyTrademarkAttribute>false</GenerateAssemblyTrademarkAttribute>
    <GenerateAssemblyCultureAttribute>false</GenerateAssemblyCultureAttribute>
    <GenerateAssemblyDescriptionAttribute>false</GenerateAssemblyDescriptionAttribute>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Module1.vb" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCodeReader">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>c:\Program Files\Bytescout BarCode Reader SDK\netcoreapp2.0\Bytescout.BarCodeReader.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### **ReadDriverLicenseInformation.VS2005.vbproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{75D64BA4-2691-4BBA-A89D-B575EE05AB63}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <StartupObject>ReadDriverLicenseInformation.Module1</StartupObject>
    <RootNamespace>ReadDriverLicenseInformation</RootNamespace>
    <AssemblyName>ReadDriverLicenseInformation</AssemblyName>
    <MyType>Console</MyType>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <DefineDebug>true</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <OutputPath>bin\Debug\</OutputPath>
    <DocumentationFile>ReadDriverLicenseInformation.xml</DocumentationFile>
    <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <DefineDebug>false</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DocumentationFile>ReadDriverLicenseInformation.xml</DocumentationFile>
    <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCodeReader, Version=8.20.0.1340, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net2.00\Bytescout.BarCodeReader.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Deployment" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Import Include="System.Collections" />
    <Import Include="System.Collections.Generic" />
    <Import Include="System.Data" />
    <Import Include="System.Diagnostics" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Module1.vb" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### **ReadDriverLicenseInformation.VS2008.vbproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{75D64BA4-2691-4BBA-A89D-B575EE05AB63}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <StartupObject>ReadDriverLicenseInformation.Module1</StartupObject>
    <RootNamespace>ReadDriverLicenseInformation</RootNamespace>
    <AssemblyName>ReadDriverLicenseInformation</AssemblyName>
    <MyType>Console</MyType>
    <OldToolsVersion>2.0</OldToolsVersion>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <DefineDebug>true</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <OutputPath>bin\Debug\</OutputPath>
    <DocumentationFile>ReadDriverLicenseInformation.xml</DocumentationFile>
    <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <DefineDebug>false</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DocumentationFile>ReadDriverLicenseInformation.xml</DocumentationFile>
    <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCodeReader, Version=8.20.0.1340, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net3.50\Bytescout.BarCodeReader.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Deployment" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Import Include="System.Collections" />
    <Import Include="System.Collections.Generic" />
    <Import Include="System.Data" />
    <Import Include="System.Diagnostics" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Module1.vb" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### **ReadDriverLicenseInformation.VS2010.vbproj:**

```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{75D64BA4-2691-4BBA-A89D-B575EE05AB63}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <StartupObject>ReadDriverLicenseInformation.Module1</StartupObject>
    <RootNamespace>ReadDriverLicenseInformation</RootNamespace>
    <AssemblyName>ReadDriverLicenseInformation</AssemblyName>
    <MyType>Console</MyType>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <DefineDebug>true</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <OutputPath>bin\Debug\</OutputPath>
    <DocumentationFile>ReadDriverLicenseInformation.xml</DocumentationFile>
    <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <DefineDebug>false</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DocumentationFile>ReadDriverLicenseInformation.xml</DocumentationFile>
    <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.BarCodeReader, Version=8.20.0.1340, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net4.00\Bytescout.BarCodeReader.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Deployment" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Import Include="System.Collections" />
    <Import Include="System.Collections.Generic" />
    <Import Include="System.Data" />
    <Import Include="System.Diagnostics" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Module1.vb" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->


text:
enum { max_length = 1024 };

class client
{
public:
  client(boost::asio::io_service& io_service,
      boost::asio::ssl::context& context,
      boost::asio::ip::tcp::resolver::iterator endpoint_iterator)
    : socket_(io_service, context)
  {
    socket_.set_verify_mode(boost::asio::ssl::verify_peer);
    socket_.set_verify_callback(
        boost::bind(&client::verify_certificate, this, _1, _2));

    boost::asio::async_connect(socket_.lowest_layer(), endpoint_iterator,
        boost::bind(&client::handle_connect, this,
          boost::asio::placeholders::error));
  }

  bool verify_certificate(bool preverified,
      boost::asio::ssl::verify_context& ctx)
  {
    // The verify callback can be used to check whether the certificate that is
    // being presented is valid for the peer. For example, RFC 2818 describes
    // the steps involved in doing this for HTTPS. Consult the OpenSSL
    // documentation for more details. Note that the callback is called once
    // for each certificate in the certificate chain, starting from the root
    // certificate authority.

    // In this example we will simply print the certificate's subject name.
    char subject_name[256];
    X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
    X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
    std::cout << "Verifying " << subject_name << "\n";

    return preverified;
  }

  void handle_connect(const boost::system::error_code& error)
  {
    if (!error)
    {
      socket_.async_handshake(boost::asio::ssl::stream_base::client,
          boost::bind(&client::handle_handshake, this,
            boost::asio::placeholders::error));
    }
    else
    {
      std::cout << "Connect failed: " << error.message() << "\n";
    }
  }

  void handle_handshake(const boost::system::error_code& error)
  {
    if (!error)
    {
      std::cout << "Enter message: ";
      std::cin.getline(request_, max_length);
      size_t request_length = strlen(request_);

      boost::asio::async_write(socket_,
          boost::asio::buffer(request_, request_length),
          boost::bind(&client::handle_write, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      std::cout << "Handshake failed: " << error.message() << "\n";
    }
  }

  void handle_write(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
    if (!error)
    {
      boost::asio::async_read(socket_,
          boost::asio::buffer(reply_, bytes_transferred),
          boost::bind(&client::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      std::cout << "Write failed: " << error.message() << "\n";
    }
  }

  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
    if (!error)
    {
      std::cout << "Reply: ";
      std::cout.write(reply_, bytes_transferred);
      std::cout << "\n";
    }
    else
    {
      std::cout << "Read failed: " << error.message() << "\n";
    }
  }

private:
  boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_;
  char request_[max_length];
  char reply_[max_length];
};

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 3)
    {
      std::cerr << "Usage: client <host> <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    boost::asio::ip::tcp::resolver resolver(io_service);
    boost::asio::ip::tcp::resolver::query query(argv[1], argv[2]);
    boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);

    boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
    ctx.load_verify_file("ca.pem");

    client c(io_service, ctx, iterator);

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}


text:
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#include "ParticleEmitterPressure.h"
#include "PsMathUtils.h"

//----------------------------------------------------------------------------//

ParticleEmitterPressure::ParticleEmitterPressure(ParticleEmitter::Shape::Enum shape, PxReal	extentX, PxReal extentY, PxReal spacing) :
	ParticleEmitter(shape, extentX, extentY, spacing),
	mSimulationAcceleration(0.0f),
	mSimulationMaxVelocity(1.0f),
	mMaxRate(10000.0f)
{
	mMaxZNoiseOffset = spacing/4.0f;
	mSites.resize(mNumSites);
	clearPredecessors();
}

//----------------------------------------------------------------------------//

ParticleEmitterPressure::~ParticleEmitterPressure()
{
}

//----------------------------------------------------------------------------//

void ParticleEmitterPressure::stepInternal(ParticleData& particles, PxReal dt, const PxVec3& externalAcceleration, PxReal maxParticleVelocity)
{
	PX_ASSERT(mNumX > 0 && mNumY > 0);

	mSimulationAcceleration = externalAcceleration;
	mSimulationMaxVelocity = maxParticleVelocity;

	PxU32 numEmittedParticles = 0;

	PxU32 maxParticlesPerStep = (PxU32)physx::shdfnd::floor(mMaxRate*dt);
	PxU32 maxParticles = PxMin(particles.maxParticles - particles.numParticles, maxParticlesPerStep);

	PxU32 siteNr = 0;
	for(PxU32 y = 0; y != mNumY; y++)
	{
		PxReal offset = 0.0f;
		if (y%2) offset = mSpacingX * 0.5f;

		for(PxU32 x = 0; x != mNumX; x++)
		{
			if (isOutsideShape(x,y,offset))
				continue;

			SiteData& siteData = mSites[siteNr];

			//position noise
			PxVec3 posNoise;
			posNoise.x = randInRange(-mRandomPos.x, mRandomPos.x);
			posNoise.y = randInRange(-mRandomPos.y, mRandomPos.y);

			//special code for Z noise
			if (!siteData.predecessor)
				siteData.noiseZ = randInRange(-mRandomPos.z, mRandomPos.z);
			else
			{
				PxReal noiseZOffset = PxMin(mMaxZNoiseOffset, mRandomPos.z);
				siteData.noiseZ += randInRange(-noiseZOffset, noiseZOffset);
				siteData.noiseZ = PxClamp(siteData.noiseZ, mRandomPos.z, -mRandomPos.z);
			}

			posNoise.z = siteData.noiseZ;

			//set position
			PxVec3 sitePos = mBasePos + mAxisX*(offset+mSpacingX*x) + mAxisY*(mSpacingY*y) + mAxisZ*siteData.noiseZ;
			PxVec3 particlePos = sitePos + mAxisX*posNoise.x + mAxisY*posNoise.y;

			PxVec3 siteVel;
			computeSiteVelocity(siteVel, particlePos);

			if (siteData.predecessor)
			{
				predictPredecessorPos(siteData, dt);
			}
			else			{
				bool isSpawned = spawnParticle(particles, numEmittedParticles, maxParticles, particlePos, siteVel);
				if(isSpawned)
				{
					updatePredecessor(siteData, particlePos, siteVel);
				}
				else
				{
					siteData.predecessor = false;
					return;
				}
			}

			bool allSpawned = stepEmissionSite(siteData, particles, numEmittedParticles, maxParticles, sitePos, siteVel, dt);
			if(!allSpawned)
				return;

			siteNr++;
		}
	}
}

//----------------------------------------------------------------------------//

void ParticleEmitterPressure::clearPredecessors()
{
	PX_ASSERT(mSites.size() == mNumSites);
	for (PxU32 i = 0; i < mNumSites; i++)
		mSites[i].predecessor = false;
}

//----------------------------------------------------------------------------//

bool ParticleEmitterPressure::stepEmissionSite(
	SiteData& siteData,
	ParticleData& spawnData,
	PxU32& spawnNum,
	const PxU32 spawnMax,
	const PxVec3 &sitePos,
	const PxVec3 &siteVel,
	const PxReal dt)
{
	PxReal maxDistanceMoved = 5.0f * mSpacingZ;	// don't generate long particle beams

	/**
	 * Find displacement vector of the particle's motion this frame
	 * this is not necessarily v*stepSize because a collision might have occured
	 */
	PxVec3 displacement = siteData.position - sitePos;
	PxVec3 normal = displacement;
	PxReal distanceMoved = normal.normalize();

	if (distanceMoved > maxDistanceMoved)
		distanceMoved = maxDistanceMoved;

	/**
	 * Place particles along line between emission point and new position
	 * starting backwards from the new position
	 * spacing between the particles is the rest spacing of the fluid
	 */
	PxReal lastPlaced = 0.0f;
	while((lastPlaced + mSpacingZ) <= distanceMoved)
	{
		PxVec3 pos = sitePos + normal * (distanceMoved - (lastPlaced + mSpacingZ));

		PxVec3 posNoise;
		posNoise.x = randInRange(-mRandomPos.x, mRandomPos.x);
		posNoise.y = randInRange(-mRandomPos.y, mRandomPos.y);

		pos += mAxisX*posNoise.x + mAxisY*posNoise.y;

		bool isSpawned = spawnParticle(spawnData, spawnNum, spawnMax, pos, siteVel);
		if(isSpawned)
		{
			updatePredecessor(siteData, pos, siteVel);
			lastPlaced += mSpacingZ;
		}
		else
		{
			return false;
		}
	}
	return true;
}

//----------------------------------------------------------------------------//

void ParticleEmitterPressure::predictPredecessorPos(SiteData& siteData, PxReal dt)
{
	PxReal compensationHack = 2.0f/3.0f;

	siteData.velocity += dt*(mSimulationAcceleration);
	PxReal velAbs = siteData.velocity.magnitude();
	PxReal maxVel = mSimulationMaxVelocity;

	if (velAbs > maxVel)
	{
		PxReal scale = maxVel/velAbs;
		siteData.velocity *= scale;
	}

	siteData.position += dt*compensationHack*siteData.velocity;
}

//----------------------------------------------------------------------------//

void ParticleEmitterPressure::updatePredecessor(SiteData& siteData, const PxVec3& position, const PxVec3& velocity)
{
	siteData.predecessor = true;
	siteData.position = position;
	siteData.velocity = velocity;
}

//----------------------------------------------------------------------------//


text:
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

import { util } from 'aws-sdk/global';

import BigInteger from './BigInteger';

var initN = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' + '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' + 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' + 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' + 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' + '83655D23DCA3AD961C62F356208552BB9ED529077096966D' + '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' + 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' + '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' + 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' + 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' + 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' + 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' + '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';

var newPasswordRequiredChallengeUserAttributePrefix = 'userAttributes.';

/** @class */

var AuthenticationHelper = function () {
  /**
   * Constructs a new AuthenticationHelper object
   * @param {string} PoolName Cognito user pool name.
   */
  function AuthenticationHelper(PoolName) {
    _classCallCheck(this, AuthenticationHelper);

    this.N = new BigInteger(initN, 16);
    this.g = new BigInteger('2', 16);
    this.k = new BigInteger(this.hexHash('00' + this.N.toString(16) + '0' + this.g.toString(16)), 16);

    this.smallAValue = this.generateRandomSmallA();
    this.getLargeAValue(function () {});

    this.infoBits = new util.Buffer('Caldera Derived Key', 'utf8');

    this.poolName = PoolName;
  }

  /**
   * @returns {BigInteger} small A, a random number
   */

  AuthenticationHelper.prototype.getSmallAValue = function getSmallAValue() {
    return this.smallAValue;
  };

  /**
   * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
   * @returns {void}
   */

  AuthenticationHelper.prototype.getLargeAValue = function getLargeAValue(callback) {
    var _this = this;

    if (this.largeAValue) {
      callback(null, this.largeAValue);
    } else {
      this.calculateA(this.smallAValue, function (err, largeAValue) {
        if (err) {
          callback(err, null);
        }

        _this.largeAValue = largeAValue;
        callback(null, _this.largeAValue);
      });
    }
  };

  /**
   * helper function to generate a random big integer
   * @returns {BigInteger} a random value.
   * @private
   */

  AuthenticationHelper.prototype.generateRandomSmallA = function generateRandomSmallA() {
    var hexRandom = util.crypto.lib.randomBytes(128).toString('hex');

    var randomBigInt = new BigInteger(hexRandom, 16);
    var smallABigInt = randomBigInt.mod(this.N);

    return smallABigInt;
  };

  /**
   * helper function to generate a random string
   * @returns {string} a random value.
   * @private
   */

  AuthenticationHelper.prototype.generateRandomString = function generateRandomString() {
    return util.crypto.lib.randomBytes(40).toString('base64');
  };

  /**
   * @returns {string} Generated random value included in password hash.
   */

  AuthenticationHelper.prototype.getRandomPassword = function getRandomPassword() {
    return this.randomPassword;
  };

  /**
   * @returns {string} Generated random value included in devices hash.
   */

  AuthenticationHelper.prototype.getSaltDevices = function getSaltDevices() {
    return this.SaltToHashDevices;
  };

  /**
   * @returns {string} Value used to verify devices.
   */

  AuthenticationHelper.prototype.getVerifierDevices = function getVerifierDevices() {
    return this.verifierDevices;
  };

  /**
   * Generate salts and compute verifier.
   * @param {string} deviceGroupKey Devices to generate verifier for.
   * @param {string} username User to generate verifier for.
   * @param {nodeCallback<null>} callback Called with (err, null)
   * @returns {void}
   */

  AuthenticationHelper.prototype.generateHashDevice = function generateHashDevice(deviceGroupKey, username, callback) {
    var _this2 = this;

    this.randomPassword = this.generateRandomString();
    var combinedString = '' + deviceGroupKey + username + ':' + this.randomPassword;
    var hashedString = this.hash(combinedString);

    var hexRandom = util.crypto.lib.randomBytes(16).toString('hex');
    this.SaltToHashDevices = this.padHex(new BigInteger(hexRandom, 16));

    this.g.modPow(new BigInteger(this.hexHash(this.SaltToHashDevices + hashedString), 16), this.N, function (err, verifierDevicesNotPadded) {
      if (err) {
        callback(err, null);
      }

      _this2.verifierDevices = _this2.padHex(verifierDevicesNotPadded);
      callback(null, null);
    });
  };

  /**
   * Calculate the client's public value A = g^a%N
   * with the generated random number a
   * @param {BigInteger} a Randomly generated small A.
   * @param {nodeCallback<BigInteger>} callback Called with (err, largeAValue)
   * @returns {void}
   * @private
   */

  AuthenticationHelper.prototype.calculateA = function calculateA(a, callback) {
    var _this3 = this;

    this.g.modPow(a, this.N, function (err, A) {
      if (err) {
        callback(err, null);
      }

      if (A.mod(_this3.N).equals(BigInteger.ZERO)) {
        callback(new Error('Illegal paramater. A mod N cannot be 0.'), null);
      }

      callback(null, A);
    });
  };

  /**
   * Calculate the client's value U which is the hash of A and B
   * @param {BigInteger} A Large A value.
   * @param {BigInteger} B Server B value.
   * @returns {BigInteger} Computed U value.
   * @private
   */

  AuthenticationHelper.prototype.calculateU = function calculateU(A, B) {
    this.UHexHash = this.hexHash(this.padHex(A) + this.padHex(B));
    var finalU = new BigInteger(this.UHexHash, 16);

    return finalU;
  };

  /**
   * Calculate a hash from a bitArray
   * @param {Buffer} buf Value to hash.
   * @returns {String} Hex-encoded hash.
   * @private
   */

  AuthenticationHelper.prototype.hash = function hash(buf) {
    var hashHex = util.crypto.sha256(buf, 'hex');
    return new Array(64 - hashHex.length).join('0') + hashHex;
  };

  /**
   * Calculate a hash from a hex string
   * @param {String} hexStr Value to hash.
   * @returns {String} Hex-encoded hash.
   * @private
   */

  AuthenticationHelper.prototype.hexHash = function hexHash(hexStr) {
    return this.hash(new util.Buffer(hexStr, 'hex'));
  };

  /**
   * Standard hkdf algorithm
   * @param {Buffer} ikm Input key material.
   * @param {Buffer} salt Salt value.
   * @returns {Buffer} Strong key material.
   * @private
   */

  AuthenticationHelper.prototype.computehkdf = function computehkdf(ikm, salt) {
    var prk = util.crypto.hmac(salt, ikm, 'buffer', 'sha256');
    var infoBitsUpdate = util.buffer.concat([this.infoBits, new util.Buffer(String.fromCharCode(1), 'utf8')]);
    var hmac = util.crypto.hmac(prk, infoBitsUpdate, 'buffer', 'sha256');
    return hmac.slice(0, 16);
  };

  /**
   * Calculates the final hkdf based on computed S value, and computed U value and the key
   * @param {String} username Username.
   * @param {String} password Password.
   * @param {BigInteger} serverBValue Server B value.
   * @param {BigInteger} salt Generated salt.
   * @param {nodeCallback<Buffer>} callback Called with (err, hkdfValue)
   * @returns {void}
   */

  AuthenticationHelper.prototype.getPasswordAuthenticationKey = function getPasswordAuthenticationKey(username, password, serverBValue, salt, callback) {
    var _this4 = this;

    if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) {
      throw new Error('B cannot be zero.');
    }

    this.UValue = this.calculateU(this.largeAValue, serverBValue);

    if (this.UValue.equals(BigInteger.ZERO)) {
      throw new Error('U cannot be zero.');
    }

    var usernamePassword = '' + this.poolName + username + ':' + password;
    var usernamePasswordHash = this.hash(usernamePassword);

    var xValue = new BigInteger(this.hexHash(this.padHex(salt) + usernamePasswordHash), 16);
    this.calculateS(xValue, serverBValue, function (err, sValue) {
      if (err) {
        callback(err, null);
      }

      var hkdf = _this4.computehkdf(new util.Buffer(_this4.padHex(sValue), 'hex'), new util.Buffer(_this4.padHex(_this4.UValue.toString(16)), 'hex'));

      callback(null, hkdf);
    });
  };

  /**
   * Calculates the S value used in getPasswordAuthenticationKey
   * @param {BigInteger} xValue Salted password hash value.
   * @param {BigInteger} serverBValue Server B value.
   * @param {nodeCallback<string>} callback Called on success or error.
   * @returns {void}
   */

  AuthenticationHelper.prototype.calculateS = function calculateS(xValue, serverBValue, callback) {
    var _this5 = this;

    this.g.modPow(xValue, this.N, function (err, gModPowXN) {
      if (err) {
        callback(err, null);
      }

      var intValue2 = serverBValue.subtract(_this5.k.multiply(gModPowXN));
      intValue2.modPow(_this5.smallAValue.add(_this5.UValue.multiply(xValue)), _this5.N, function (err2, result) {
        if (err2) {
          callback(err2, null);
        }

        callback(null, result.mod(_this5.N));
      });
    });
  };

  /**
  * Return constant newPasswordRequiredChallengeUserAttributePrefix
  * @return {newPasswordRequiredChallengeUserAttributePrefix} constant prefix value
  */

  AuthenticationHelper.prototype.getNewPasswordRequiredChallengeUserAttributePrefix = function getNewPasswordRequiredChallengeUserAttributePrefix() {
    return newPasswordRequiredChallengeUserAttributePrefix;
  };

  /**
   * Converts a BigInteger (or hex string) to hex format padded with zeroes for hashing
   * @param {BigInteger|String} bigInt Number or string to pad.
   * @returns {String} Padded hex string.
   */

  AuthenticationHelper.prototype.padHex = function padHex(bigInt) {
    var hashStr = bigInt.toString(16);
    if (hashStr.length % 2 === 1) {
      hashStr = '0' + hashStr;
    } else if ('89ABCDEFabcdef'.indexOf(hashStr[0]) !== -1) {
      hashStr = '00' + hashStr;
    }
    return hashStr;
  };

  return AuthenticationHelper;
}();

export default AuthenticationHelper;


text:
local core = md5_core;

----------------------------------------------------------------------------
-- @param k String with original message.
-- @return String with the md5 hash value converted to hexadecimal digits

function core.sumhexa (k)
  k = core.sum(k)
  return (string.gsub(k, ".", function (c)
           return string.format("%02x", string.byte(c))
         end))
end

return core


text:
using System;

namespace TS.FluentSiteMap.Builders
{
    /// <summary>
    /// A <see cref="DecoratingNodeBuilder"/> class
    /// that configures the node to get its URL from a named MVC controller.
    /// </summary>
    public class ControllerNodeBuilder
        : DecoratingNodeBuilder
    {
        private readonly string _controllerName;

        /// <summary>
        /// Initializes a new instance of the <see cref="ControllerNodeBuilder"/> class.
        /// </summary>
        /// <param name="inner">
        /// The inner <see cref="INodeBuilder"/> instance being decorated.
        /// </param>
        /// <param name="controllerName">
        /// The name of the MVC controller.
        /// </param>
        public ControllerNodeBuilder(INodeBuilder inner, string controllerName)
            : base(inner)
        {
            if (controllerName == null) throw new ArgumentNullException("controllerName");

            _controllerName = controllerName;
        }

        /// <summary>
        /// Overrides the <see cref="DecoratingNodeBuilder.OnBuild"/> method,
        /// setting the <see cref="BuilderContext"/> metadata value.
        /// </summary>
        protected override void OnBuild(Node node, BuilderContext context)
        {
            context.SetMetadata(UrlFromMvcNodeBuilder.ControllerKey, _controllerName);
        }
    }
}


text:
#include <PiPei.h>

#include <Library/DebugLib.h>
#include <Library/PeiServicesTablePointerLib.h>

// PPI Functions

// PeiInstallPpi
/** This service is the first one provided by the PEI Foundation.  This
    function installs an interface in the PEI PPI database by GUID.  The
    purpose of the service is to publish an interface that other parties can
    use to call additional PEIMs.

  @param[in] PpiList  A pointer to the list of interfaces that the caller shall
                      install.

  @retval EFI_SUCCESS            The interface was successfully installed.
  @retval EFI_INVALID_PARAMETER  The PpiList pointer is NULL or Any of the PEI
                                 PPI descriptors in the list do not have the
                                 EFI_PEI_PPI_DESCRIPTOR_PPI bit set in the
                                 Flags field.
  @retval EFI_OUT_OF_RESOURCES   There is no additional space in the PPI
                                 database.
**/
EFI_STATUS
PeiInstallPpi (
  IN CONST EFI_PEI_PPI_DESCRIPTOR  *PpiList
  )
{
  EFI_STATUS             Status;

  UINTN                  Index;
  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (PpiList != NULL);

  for (Index = 0;
        (PpiList[Index].Flags & EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) == 0;
          ++Index) {
    ASSERT ((PpiList[Index].Flags & EFI_PEI_PPI_DESCRIPTOR_PPI) != 0);
  }

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->InstallPpi (PeiServices, PpiList);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiReInstallPpi
/** This function reinstalls an interface in the PEI PPI database by GUID.  The
    purpose of the service is to publish an interface that other parties can
    use to replace a same-named interface in the protocol database with a
    different interface.

  @param[in] OldPpi  A pointer to the former PPI in the database.
  @param[in] NewPpi  A pointer to the new interfaces that the caller shall
                     install.

  @retval EFI_SUCCESS            The interface was successfully installed.
  @retval EFI_INVALID_PARAMETER  The PpiList pointer is NULL or Any of the PEI
                                 PPI descriptors in the list do not have the
                                 EFI_PEI_PPI_DESCRIPTOR_PPI bit set in the
                                 Flags field.
  @retval EFI_OUT_OF_RESOURCES   There is no additional space in the PPI
                                 database.
  @retval EFI_NOT_FOUND          The PPI for which the reinstallation was
                                 requested has not been installed.
**/
EFI_STATUS
PeiReInstallPpi (
  IN CONST EFI_PEI_PPI_DESCRIPTOR  *OldPpi,
  IN CONST EFI_PEI_PPI_DESCRIPTOR  *NewPpi
  )
{
  EFI_STATUS             Status;

  UINTN                  Index;
  UINTN                  Index2;
  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (OldPpi != NULL);

  for (Index = 0;
        (OldPpi[Index].Flags & EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) == 0;
          ++Index) {
  ASSERT ((OldPpi[Index].Flags & EFI_PEI_PPI_DESCRIPTOR_PPI) != 0);
    }

  for (Index2 = 0;
        (OldPpi[Index2].Flags & EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) == 0;
          ++Index2) {
    ASSERT ((OldPpi[Index2].Flags & EFI_PEI_PPI_DESCRIPTOR_PPI) != 0);
  }

  ASSERT (Index == Index2);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->ReInstallPpi (PeiServices, OldPpi, NewPpi);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiLocatePpi
/** This function locates an interface in the PEI PPI database by GUID.

  @param[in]      Guid           A pointer to the GUID whose corresponding
                                 interface needs to be found.
  @param[in]      Instance       The N-th instance of the interface that is
                                 required.
  @param[in, out] PpiDescriptor  A pointer to instance of the
                                 EFI_PEI_PPI_DESCRIPTOR.
  @param[in, out] Ppi            A pointer to the instance of the interface.

  @retval EFI_SUCCESS    The interface was successfully returned.
  @retval EFI_NOT_FOUND  The PPI descriptor is not found in the database.
**/
EFI_STATUS
PeiLocatePpi (
  IN     CONST EFI_GUID          *Guid,
  IN     UINTN                   Instance,
  IN OUT EFI_PEI_PPI_DESCRIPTOR  **PpiDescriptor, OPTIONAL
  IN OUT VOID                    **Ppi
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (Guid != NULL);
  ASSERT (Ppi != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->LocatePpi (
                                  PeiServices,
                                  Guid,
                                  Instance,
                                  PpiDescriptor,
                                  Ppi
                                  );

  if (Status != EFI_NOT_FOUND) {
    ASSERT_EFI_ERROR (Status);
  }

  return Status;
}

// PeiNotifyPpi
/** This function installs a notification service to be called back when a
    given interface is installed or reinstalled.  The purpose of the service
    is to publish an interface that other parties can use to call additional
    PPIs that may materialize later.

  @param[in] NotifyList   A pointer to the list of notification interfaces that
                          the caller shall install.

  @retval EFI_SUCCESS            The interface was successfully installed.
  @retval EFI_INVALID_PARAMETER  The PpiList pointer is NULL, or any of the PEI
                                 PPI descriptors in the list do not have the
                                 EFI_PEI_PPI_DESCRIPTOR_PPI bit set in the
                                 Flags field.
  @retval EFI_OUT_OF_RESOURCES   There is no additional space in the PPI
                                 database.
**/
EFI_STATUS
PeiNotifyPpi (
  IN CONST EFI_PEI_NOTIFY_DESCRIPTOR  *NotifyList
  )
{
  EFI_STATUS             Status;

  UINTN                  Index;
  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (NotifyList != NULL);

  for (Index = 0;
        (NotifyList[Index].Flags & EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) == 0;
          ++Index) {
    ASSERT ((NotifyList[Index].Flags & EFI_PEI_PPI_DESCRIPTOR_PPI) != 0);
  }

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->NotifyPpi (PeiServices, NotifyList);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// Boot Mode Functions

// PeiGetBootMode
/** This function returns the present value of the boot mode.

  @param[out] BootMode     A pointer to contain the value of the boot mode.

  @retval EFI_SUCCESS  The boot mode returned successfully.
**/
EFI_STATUS
PeiGetBootMode (
  OUT EFI_BOOT_MODE  *BootMode
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (BootMode != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->GetBootMode (PeiServices, BootMode);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiSetBootMode
/** This function sets the value of the boot mode.

  @param[in] BootMode     The value of the boot mode to set.

  @retval EFI_SUCCESS  The boot mode returned successfully.
**/
EFI_STATUS
PeiSetBootMode (
  IN EFI_BOOT_MODE  BootMode
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->SetBootMode (PeiServices, BootMode);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// HOB Functions

// PeiGetHobList
/** This function returns the pointer to the list of Hand-Off Blocks (HOBs) in
    memory.

  @param[out] HobList      A pointer to the list of HOBs that the PEI
                           Foundation will initialize

  @retval EFI_SUCCESS            The list was successfully returned.
  @retval EFI_NOT_AVAILABLE_YET  The HOB list is not yet published.
**/
EFI_STATUS
PeiGetHobList (
  OUT VOID  **HobList
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (HobList != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->GetHobList (PeiServices, HobList);

  return Status;
}

// PeiCreateHob
/** This service, published by the PEI Foundation, abstracts the creation of a
    Hand-Off Block's (HOB's) headers.

  @param[in]      Type    The type of HOB to be installed.
  @param[in]      Length  The length of the HOB to be added.
  @param[in, out] Hob     The address of a pointer that will contain the HOB
                          header.

  @retval EFI_SUCCESS           The HOB was successfully created.
  @retval EFI_OUT_OF_RESOURCES  There is no additional space for HOB creation.
**/
EFI_STATUS
PeiCreateHob (
  IN     UINT16  Type,
  IN     UINT16  Length,
  IN OUT VOID    **Hob
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (Length > 0);
  ASSERT (Hob != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->CreateHob (PeiServices, Type, Length, Hob);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// Firmware Volume Functions

// FfsFindNextVolume
/** The purpose of the service is to abstract the capability of the PEI
    Foundation to discover instances of firmware volumes in the system.

  This service enables PEIMs to discover additional firmware volumes.  The PEI
  Foundation uses this service to abstract the locations and formats of various
  firmware volumes.  These volumes include the Boot Firmware Volume and any
  other volumes exposed by EFI_PEI_FV_PPI.  The service returns a volume handle
  of type EFI_PEI_FV_HANDLE, which must be unique within the system.

  @param[in]  Instance      This instance of the firmware volume to find.
                            The value 0 is the Boot Firmware Volume (BFV).
  @param[out] VolumeHandle  On exit, points to the next volumn handle or NULL
                            if it does not exist.

  @retval EFI_SUCCESS            The volume was found.
  @retval EFI_NOT_FOUND          The volume was not found.
  @retval EFI_INVALID_PARAMETER  VolumeHandle is NULL.
**/
EFI_STATUS
FfsFindNextVolume (
  IN  UINTN              Instance,
  OUT EFI_PEI_FV_HANDLE  *VolumeHandle
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (VolumeHandle != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsFindNextVolume (
                                  PeiServices,
                                  Instance,
                                  VolumeHandle
                                  );

  if (Status != EFI_NOT_FOUND) {
    ASSERT_EFI_ERROR (Status);
  }

  return Status;
}

// PeiFfsFindNextFile
/** Searches for the next matching file in the firmware volume.

  This service enables PEIMs to discover firmware files within a specified
  volume.  To find the first instance of a firmware file, pass a FileHandle
  value of NULL into the service.  The service returns a file handle of type
  EFI_PEI_FILE_HANDLE, which must be unique within the system.

  @param[in]     SearchType  A filter to find files only of this type.
  @param[in]     FvHandle    Handle of firmware volume in which to search.
  @param[in,out] FileHandle  On entry, points to the current handle from which
                             to begin searching or NULL to start at the
                             beginning of the firmware volume.  On exit,
                             points the file handle of the next file in the
                             volume or NULL if there are no more files.

  @retval EFI_SUCCESS    The file was found.
  @retval EFI_NOT_FOUND  The file was not found.
  @retval EFI_NOT_FOUND  The header checksum was not zero.
**/
EFI_STATUS
PeiFfsFindNextFile (
  IN     EFI_FV_FILETYPE          SearchType,
  IN     CONST EFI_PEI_FV_HANDLE  FvHandle,
  IN OUT EFI_PEI_FILE_HANDLE      *FileHandle
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FvHandle != NULL);
  ASSERT (FileHandle != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsFindNextFile (
                                  PeiServices,
                                  SearchType,
                                  FvHandle,
                                  FileHandle
                                  );

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiFfsFindSectionData
/** Searches for the next matching section within the specified file.

  This service enables PEI modules to discover the first section of a given
  type within a valid file.  This service will search within encapsulation
  sections (compression and GUIDed) as well.  It will search inside of a GUIDed
  section or a compressed section, but may not, for example, search a GUIDed
  section inside a GUIDes section.  This service will not search within
  compression sections or GUIDed sections that require extraction if memory is
  not present.

  @param[in]  SectionType  The value of the section type to find.
  @param[in]  FileHandle   Handle of the firmware file to search.
  @param[out] SectionData  A pointer to the discovered section, if successful.

  @retval EFI_SUCCESS    The section was found.
  @retval EFI_NOT_FOUND  The section was not found.
**/
EFI_STATUS
PeiFfsFindSectionData (
  IN  EFI_SECTION_TYPE     SectionType,
  IN  EFI_PEI_FILE_HANDLE  FileHandle,
  OUT VOID                 **SectionData
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FileHandle != NULL);
  ASSERT (SectionData != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsFindSectionData (
                                  PeiServices,
                                  SectionType,
                                  FileHandle,
                                  SectionData
                                  );

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PEI Memory Functions

/** This function registers the found memory configuration with the PEI
    Foundation.

  @param[in] MemoryBegin   The value of a region of installed memory.
  @param[in] MemoryLength  The corresponding length of a region of installed
                           memory.

  @retval EFI_SUCCESS            The region was successfully installed in a
                                 HOB.
  @retval EFI_INVALID_PARAMETER  MemoryBegin and MemoryLength are illegal for
                                 this system.
  @retval EFI_OUT_OF_RESOURCES   There is no additional space for HOB creation.
**/
EFI_STATUS
PeiInstallPeiMemory (
  IN EFI_PHYSICAL_ADDRESS  MemoryBegin,
  IN UINT64                MemoryLength
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (MemoryBegin > 0);
  ASSERT (MemoryLength > 0);
  ASSERT ((MemoryLength - 1) <= (MAX_ADDRESS - MemoryBegin));

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->InstallPeiMemory (
                                  PeiServices,
                                  MemoryBegin,
                                  MemoryLength
                                  );

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiAllocatePages
/** The purpose of the service is to publish an interface that allows PEIMs to
    allocate memory ranges that are managed by the PEI Foundation.

  @param[in]  MemoryType   The type of memory to allocate.
  @param[in]  Pages        The number of contiguous 4 KB pages to allocate.
  @param[out] Memory       A pointer to a physical address.  On output, the
                           address is set to the base of the page range that
                           was allocated.

  @retval EFI_SUCCESS            The memory range was successfully allocated.
  @retval EFI_OUT_OF_RESOURCES   The pages could not be allocated.
  @retval EFI_INVALID_PARAMETER  The type is not equal to EfiLoaderCode,
                                 EfiLoaderData, EfiRuntimeServicesCode,
                                 EfiRuntimeServicesData, EfiBootServicesCode,
                                 EfiBootServicesData, EfiACPIReclaimMemory,
                                 EfiReservedMemoryType, or EfiACPIMemoryNVS.
**/
EFI_STATUS
PeiAllocatePages (
  IN  EFI_MEMORY_TYPE       MemoryType,
  IN  UINTN                 Pages,
  OUT EFI_PHYSICAL_ADDRESS  *Memory
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT ((MemoryType == EfiLoaderCode)
       || (MemoryType == EfiLoaderData)
       || (MemoryType == EfiRuntimeServicesCode)
       || (MemoryType == EfiRuntimeServicesData)
       || (MemoryType == EfiBootServicesCode)
       || (MemoryType == EfiBootServicesData)
       || (MemoryType == EfiACPIReclaimMemory)
       || (MemoryType == EfiReservedMemoryType)
       || (MemoryType == EfiACPIMemoryNVS));

  ASSERT (Pages > 0);
  ASSERT (Memory != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->AllocatePages (
                                  PeiServices,
                                  MemoryType,
                                  Pages,
                                  Memory
                                  );

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiAllocatePool
/** The purpose of this service is to publish an interface that allows PEIMs to
    allocate memory ranges that are managed by the PEI Foundation.

  @param[in]  Size         The number of bytes to allocate from the pool.
  @param[out] Buffer       If the call succeeds, a pointer to a pointer to the
                           allocated buffer; undefined otherwise.

  @retval EFI_SUCCESS           The allocation was successful.
  @retval EFI_OUT_OF_RESOURCES  There is not enough heap to allocate the
                                requested size.
**/
EFI_STATUS
PeiAllocatePool (
  IN  UINTN  Size,
  OUT VOID   **Buffer
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (Size > 0);
  ASSERT (Buffer != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->AllocatePool (PeiServices, Size, Buffer);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiCopyMem
/** This service copies the contents of one buffer to another buffer.

  @param[in] Destination  The pointer to the destination buffer of the memory
                          copy.
  @param[in] Source       The pointer to the source buffer of the memory copy.
  @param[in] Length       The number of bytes to copy from Source to
                          Destination.
**/
VOID
PeiCopyMem (
  IN VOID   *Destination,
  IN VOID   *Source,
  IN UINTN  Length
  )
{
  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (Destination != NULL);
  ASSERT (Source != NULL);
  ASSERT (Length > 0);

  PeiServices = GetPeiServicesTablePointer ();

  (*PeiServices)->CopyMem (Destination, Source, Length);
}

// PeiSetMem
/** The service fills a buffer with a specified value.

  @param[in] Buffer  The pointer to the buffer to fill.
  @param[in] Size    The number of bytes in Buffer to fill.
  @param[in] Value   The value to fill Buffer with.
**/
VOID
PeiSetMem (
  IN VOID   *Buffer,
  IN UINTN  Size,
  IN UINT8  Value
  )
{
  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (Buffer != NULL);
  ASSERT (Size > 0);
  ASSERT ((Size - 1) <= (MAX_ADDRESS - (UINTN)Buffer));

  PeiServices = GetPeiServicesTablePointer ();

  (*PeiServices)->SetMem (Buffer, Size, Value);
}

// Status Code

/** This service publishes an interface that allows PEIMs to report status
    codes.

  ReportStatusCode() is called by PEIMs that wish to report status information
  on their progress.  The principal use model is for a PEIM to emit one of the
  standard 32-bit error codes.  This will allow a platform owner to ascertain
  the state of the system, especially under conditions where the full consoles
  might not have been installed.

  @param[in] Type         Indicates the type of status code being reported.
  @param[in] Value        Describes the current status of a hardware or
                          software entity. This includes information about the
                          class and subclass that is used to classify the
                          entity as well as an operation.  For progress codes,
                          the operation is the current activity.  For error
                          codes, it is the exception.  For debug codes, it is
                          not defined at this time.
  @param[in] Instance     The enumeration of a hardware or software entity
                          within the system. A system may contain multiple
                          entities that match a class/subclass
                          pairing. The instance differentiates between them.
                          An instance of 0 indicates that instance information
                          is unavailable, not meaningful, or not relevant.
                          Valid instance numbers start with 1.
  @param[in] CallerId     This optional parameter may be used to identify the
                          caller.
                          This parameter allows the status code driver to apply
                          different rules to different callers.
  @param[in] Data         This optional parameter may be used to pass
                          additional data.

  @retval EFI_SUCCESS            The function completed successfully.
  @retval EFI_NOT_AVAILABLE_YET  No progress code provider has installed an
                                 interface in the system.
**/
EFI_STATUS
PeiReportStatusCode (
  IN EFI_STATUS_CODE_TYPE        Type,
  IN EFI_STATUS_CODE_VALUE       Value,
  IN UINT32                      Instance,
  IN CONST EFI_GUID              *CallerId, OPTIONAL
  IN CONST EFI_STATUS_CODE_DATA  *Data OPTIONAL
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->ReportStatusCode (
                                  PeiServices,
                                  Type,
                                  Value,
                                  Instance,
                                  CallerId,
                                  Data
                                  );

  return Status;
}

// Reset

// PeiResetSystem
/** Resets the entire platform.

  This service resets the entire platform, including all processors and
  devices, and reboots the system.  This service will never return
  EFI_SUCCESS.

  @retval EFI_NOT_AVAILABLE_YET  The service has not been installed yet.
**/
EFI_STATUS
PeiResetSystem (
  VOID
  )
{
  CONST EFI_PEI_SERVICES **PeiServices;

  PeiServices = GetPeiServicesTablePointer ();

  return(*PeiServices)->ResetSystem (PeiServices);
}

// Future Installed Services

// FfsFindFileByName
/** Find a file within a volume by its name.

  This service searches for files with a specific name, within
  either the specified firmware volume or all firmware volumes.
  The service returns a file handle of type EFI_PEI_FILE_HANDLE,
  which must be unique within the system.

  @param FileName       A pointer to the name of the file to
                        find within the firmware volume.
  @param VolumeHandle   The firmware volume to search.
  @param FileHandle     Upon exit, points to the found file's
                        handle or NULL if it could not be found.

  @retval EFI_SUCCESS             The file was found.
  @retval EFI_NOT_FOUND           The file was not found.
  @retval EFI_INVALID_PARAMETER   VolumeHandle or FileHandle or
                                  FileName was NULL.
**/
EFI_STATUS
FfsFindFileByName (
  IN  CONST  EFI_GUID      *FileName,
  IN  EFI_PEI_FV_HANDLE    VolumeHandle,
  OUT EFI_PEI_FILE_HANDLE  *FileHandle
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FileName != NULL);
  ASSERT (VolumeHandle != NULL);
  ASSERT (FileHandle != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsFindFileByName (
                                  FileName,
                                  VolumeHandle,
                                  FileHandle
                                  );

  if (Status != EFI_NOT_FOUND) {
    ASSERT_EFI_ERROR (Status);
  }

  return Status;
}

// PeiFfsGetFileInfo
/** Returns information about a specific file.

  This function returns information about a specific file, including its file
  name, type, attributes, starting address and size.  If the firmware volume is
  not memory mapped, then the Buffer member will be NULL.

  @param[in]  FileHandle  The handle of the file.
  @param[out] FileInfo    Upon exit, points to the file's information.

  @retval EFI_SUCCESS            File information was returned.
  @retval EFI_INVALID_PARAMETER  FileHandle does not represent a valid file.
  @retval EFI_INVALID_PARAMETER  FileInfo is NULL.
**/
EFI_STATUS
PeiFfsGetFileInfo (
  IN  EFI_PEI_FILE_HANDLE  FileHandle,
  OUT EFI_FV_FILE_INFO     *FileInfo
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FileHandle != NULL);
  ASSERT (FileInfo != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsGetFileInfo (FileHandle, FileInfo);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiFfsGetVolumeInfo
/** Returns information about the specified volume.

  This function returns information about a specific firmware volume, including
  its name, type, attributes, starting address and size.

  @param[in]  VolumeHandle  Handle of the volume.
  @param[out] VolumeInfo    Upon exit, points to the volume's information.

  @retval EFI_SUCCESS            The volume information returned.
  @retval EFI_INVALID_PARAMETER  If VolumeHandle does not represent a valid
                                 volume.
  @retval EFI_INVALID_PARAMETER  If VolumeHandle is NULL.
  @retval EFI_INVALID_PARAMETER  The volume designated by the VolumeHandle is
                                 not available.
**/
EFI_STATUS
PeiFfsGetVolumeInfo (
  IN  EFI_PEI_FV_HANDLE  VolumeHandle,
  OUT EFI_FV_INFO        *VolumeInfo
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (VolumeHandle != NULL);
  ASSERT (VolumeInfo != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsGetVolumeInfo (VolumeHandle, VolumeInfo);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiRegisterForShadow
/** Register a PEIM so that it will be shadowed and called again.

  This service registers a file handle so that after memory is available, the
  PEIM will be re-loaded into permanent memory and re-initialized.  The PEIM
  registered this way will always be initialized twice.  The first time, this
  function call will return EFI_SUCCESS.  The second time, this function call
  will return EFI_ALREADY_STARTED.  Depending on the order in which PEIMs are
  dispatched, the PEIM making this call may be initialized after permanent
  memory is installed, even the first time.

  @param[in] FileHandle  PEIM's file handle. Must be the currently executing
                         PEIM.

  @retval EFI_SUCCESS          The PEIM was successfully registered for
                               shadowing.
  @retval EFI_ALREADY_STARTED  The PEIM was previously registered for
                               shadowing.
  @retval EFI_NOT_FOUND        The FileHandle does not refer to a valid file
                               handle.
**/
EFI_STATUS
PeiRegisterForShadow (
  IN EFI_PEI_FILE_HANDLE  FileHandle
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FileHandle != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->RegisterForShadow (FileHandle);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// PeiFfsFindSectionData3
/** Searches for the next matching section within the specified file.

  This service enables PEI modules to discover the section of a given type
  within a valid file.  This service will search within encapsulation sections
  (compression and GUIDed) as well.  It will search inside of a GUIDed section
  or a compressed section, but may not, for example, search a GUIDed section
  inside a GUIDes section.  This service will not search within compression
  sections or GUIDed sections that require extraction if memory is not present.

  @param[in]  SectionType           The value of the section type to find.
  @param[in]  SectionInstance       Section instance to find.
  @param[in]  FileHandle            Handle of the firmware file to search.
  @param[out] SectionData           A pointer to the discovered section, if
                                    successful.
  @param[out] AuthenticationStatus  A pointer to the authentication status for
                                    this section.

  @retval EFI_SUCCESS      The section was found.
  @retval EFI_NOT_FOUND    The section was not found.
**/
EFI_STATUS
PeiFfsFindSectionData3 (
  IN  EFI_SECTION_TYPE     SectionType,
  IN  UINTN                SectionInstance,
  IN  EFI_PEI_FILE_HANDLE  FileHandle,
  OUT VOID                 **SectionData,
  OUT UINT32               *AuthenticationStatus
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FileHandle != NULL);
  ASSERT (SectionData != NULL);
  ASSERT (AuthenticationStatus != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FindSectionData3 (
                                  PeiServices,
                                  SectionType,
                                  SectionInstance,
                                  FileHandle,
                                  SectionData,
                                  AuthenticationStatus
                                  );

  return Status;
}

// PeiFfsGetFileInfo2
/** Returns information about a specific file.

  This function returns information about a specific file, including its file
  name, type, attributes, starting address, size and authentication status.  If
  the firmware volume is not memory mapped, then the Buffer member will be
  NULL.

  @param[in]  FileHandle  The handle of the file.
  @param[out] FileInfo    Upon exit, points to the file's information.

  @retval EFI_SUCCESS            File information was returned.
  @retval EFI_INVALID_PARAMETER  FileHandle does not represent a valid file.
  @retval EFI_INVALID_PARAMETER  FileInfo is NULL.
**/
EFI_STATUS
PeiFfsGetFileInfo2 (
  IN  EFI_PEI_FILE_HANDLE  FileHandle,
  OUT EFI_FV_FILE_INFO2    *FileInfo
  )
{
  EFI_STATUS             Status;

  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT (FileHandle != NULL);
  ASSERT (FileInfo != NULL);

  PeiServices = GetPeiServicesTablePointer ();
  Status      = (*PeiServices)->FfsGetFileInfo2 (FileHandle, FileInfo);

  ASSERT_EFI_ERROR (Status);

  return Status;
}

// ResetSystem2
/** Resets the entire platform.

  @param[in] ResetType    The type of reset to perform.
  @param[in] ResetStatus  The status code for the reset.
  @param[in] DataSize     The size, in bytes, of WatchdogData.
  @param[in] ResetData    For a ResetType of EfiResetCold, EfiResetWarm, or
                          EfiResetShutdown the data buffer starts with a
                          Null-terminated string, optionally followed by
                          additional binary data. The string is a description
                          that the caller may use to further indicate the
                          reason for the system reset.  ResetData is only valid
                          if ResetStatus is something other than EFI_SUCCESS
                          unless the ResetType is EfiResetPlatformSpecific
                          where a minimum amount of ResetData is always
                          required.
**/
VOID
PeiResetSystem2 (
  IN EFI_RESET_TYPE  ResetType,
  IN EFI_STATUS      ResetStatus,
  IN UINTN           DataSize,
  IN VOID            *ResetData OPTIONAL
  )
{
  CONST EFI_PEI_SERVICES **PeiServices;

  ASSERT ((ResetType >= EfiResetCold)
       && (ResetType <= EfiResetPlatformSpecific));
  ASSERT (((((ResetType == EfiResetPlatformSpecific)
          || (ResetStatus != EFI_SUCCESS)) ? 1 : 0)
            ^ ((ResetData == NULL) ? 1 : 0)) != 0);

  ASSERT ((((DataSize > 0) ? 1 : 0) ^ ((ResetData == NULL) ? 1 : 0)) != 0);

  PeiServices = GetPeiServicesTablePointer ();

  (*PeiServices)->ResetSystem2 (ResetType, ResetStatus, DataSize, ResetData);
}


text:
title: JSONP
menu:
  side:
    parent: recipes
    weight: 6
---

JSONP is a method that allows cross-domain server calls. You can read more about it at the JSON versus JSONP Tutorial.

### Server

`server.go`

{{< embed "jsonp/server.go" >}}

### Client

`index.html`

{{< embed "jsonp/public/index.html" >}}

### Maintainers

- [willf](https://github.com/willf)

### [Source Code](https://github.com/labstack/echo/blob/master/recipes/jsonp)


text:
module Axlsx
  # Package is responsible for managing all the bits and peices that Open Office XML requires to make a valid
  # xlsx document including valdation and serialization.
  class Package

    # provides access to the app doc properties for this package
    # see App
    attr_reader :app

    # provides access to the core doc properties for the package
    # see Core
    attr_reader :core

    # Initializes your package
    #
    # @param [Hash] options A hash that you can use to specify the author and workbook for this package.
    # @option options [String] :author The author of the document
    # @option options [Boolean] :use_shared_strings This is passed to the workbook to specify that shared strings should be used when serializing the package.
    # @example Package.new :author => 'you!', :workbook => Workbook.new
    def initialize(options={})
      @workbook = nil
      @core, @app  =  Core.new, App.new
      @core.creator = options[:author] || @core.creator
      options.each do |o|
        self.send("#{o[0]}=", o[1]) if self.respond_to? "#{o[0]}="
      end
      yield self if block_given?
    end

    # Shortcut to specify that the workbook should use autowidth
    # @see Workbook#use_autowidth
    def use_autowidth=(v)
      Axlsx::validate_boolean(v);
      workbook.use_autowidth = v
    end

    # Shortcut to specify that the workbook should use shared strings
    # @see Workbook#use_shared_strings
    def use_shared_strings=(v)
      Axlsx::validate_boolean(v);
      workbook.use_shared_strings = v
    end

    # Shortcut to determine if the workbook is configured to use shared strings
    # @see Workbook#use_shared_strings
    def use_shared_strings
      workbook.use_shared_strings
    end

    # The workbook this package will serialize or validate.
    # @return [Workbook] If no workbook instance has been assigned with this package a new Workbook instance is returned.
    # @raise ArgumentError if workbook parameter is not a Workbook instance.
    # @note As there are multiple ways to instantiate a workbook for the package,
    #   here are a few examples:
    #     # assign directly during package instanciation
    #     wb = Package.new(:workbook => Workbook.new).workbook
    #
    #     # get a fresh workbook automatically from the package
    #     wb = Pacakge.new().workbook
    #     #     # set the workbook after creating the package
    #     wb = Package.new().workbook = Workbook.new
    def workbook
      @workbook || @workbook = Workbook.new
      yield @workbook if block_given?
      @workbook
    end

    #def self.parse(input, confirm_valid = false)
    #  p = Package.new
    #  z = Zip::ZipFile.open(input)
    #  p.workbook = Workbook.parse z.get_entry(WORKBOOK_PN)
    #  p
    #end

    # @see workbook
    def workbook=(workbook) DataTypeValidator.validate "Package.workbook", Workbook, workbook; @workbook = workbook; end

    # Serialize your workbook to disk as an xlsx document.
    #
    # @param [String] output The name of the file you want to serialize your package to
    # @param [Boolean] confirm_valid Validate the package prior to serialization.
    # @return [Boolean] False if confirm_valid and validation errors exist. True if the package was serialized
    # @note A tremendous amount of effort has gone into ensuring that you cannot create invalid xlsx documents.
    #   confirm_valid should be used in the rare case that you cannot open the serialized file.
    # @see Package#validate
    # @example
    #   # This is how easy it is to create a valid xlsx file. Of course you might want to add a sheet or two, and maybe some data, styles and charts.
    #   # Take a look at the README for an example of how to do it!
    #
    #   #serialize to a file
    #   p = Axlsx::Package.new
    #   # ......add cool stuff to your workbook......
    #   p.serialize("example.xlsx")
    #
    #   # Serialize to a stream
    #   s = p.to_stream()
    #   File.open('example_streamed.xlsx', 'w') { |f| f.write(s.read) }
    def serialize(output, confirm_valid=false)
      return false unless !confirm_valid || self.validate.empty?
      Zip::File.open.open(output) do |zip|
        write_parts(zip)
      end
      true
    end

    # Serialize your workbook to a StringIO instance
    # @param [Boolean] confirm_valid Validate the package prior to serialization.
    # @return [StringIO|Boolean] False if confirm_valid and validation errors exist. rewound string IO if not.
    def to_stream(confirm_valid=false)
      return false unless !confirm_valid || self.validate.empty?
      zip = write_parts(Zip::File.open.new("streamed", true))
      stream = zip.close_buffer
      stream.rewind
      stream
    end

    # Encrypt the package into a CFB using the password provided
    # This is not ready yet
    def encrypt(file_name, password)
      return false
      # moc = MsOffCrypto.new(file_name, password)
      # moc.save
    end

    # Validate all parts of the package against xsd schema.
    # @return [Array] An array of all validation errors found.
    # @note This gem includes all schema from OfficeOpenXML-XMLSchema-Transitional.zip and OpenPackagingConventions-XMLSchema.zip
    #   as per ECMA-376, Third edition. opc schema require an internet connection to import remote schema from dublin core for dc,
    #   dcterms and xml namespaces. Those remote schema are included in this gem, and the original files have been altered to
    #   refer to the local versions.
    #
    #   If by chance you are able to creat a package that does not validate it indicates that the internal
    #   validation is not robust enough and needs to be improved. Please report your errors to the gem author.
    # @see http://www.ecma-international.org/publications/standards/Ecma-376.htm
    # @example
    #  # The following will output any error messages found in serialization.
    #  p = Axlsx::Package.new
    #  # ... code to create sheets, charts, styles etc.
    #  p.validate.each { |error| puts error.message }
    def validate
      errors = []
      parts.each do |part|
        errors.concat validate_single_doc(part[:schema], part[:doc]) unless part[:schema].nil?
      end
      errors
    end

    private

    # Writes the package parts to a zip archive.
    # @param [Zip::ZipOutputStream] zip
    # @return [Zip::ZipOutputStream]
    def write_parts(zip)
      p = parts
        p.each do |part|
          unless part[:doc].nil?
            zip.put_next_entry(part[:entry]);
            entry = ['1.9.2', '1.9.3'].include?(RUBY_VERSION) ? part[:doc].force_encoding('BINARY') : part[:doc]
            zip.puts(entry)
          end
          unless part[:path].nil?
            zip.put_next_entry(part[:entry]);
            # binread for 1.9.3
            zip.write IO.respond_to?(:binread) ? IO.binread(part[:path]) : IO.read(part[:path])
          end
        end
      zip
    end

    # The parts of a package
    # @return [Array] An array of hashes that define the entry, document and schema for each part of the package.
    # @private
    def parts
      @parts = [
       {:entry => RELS_PN, :doc => relationships.to_xml_string, :schema => RELS_XSD},
       {:entry => "xl/#{STYLES_PN}", :doc => workbook.styles.to_xml_string, :schema => SML_XSD},
       {:entry => CORE_PN, :doc => @core.to_xml_string, :schema => CORE_XSD},
       {:entry => APP_PN, :doc => @app.to_xml_string, :schema => APP_XSD},
       {:entry => WORKBOOK_RELS_PN, :doc => workbook.relationships.to_xml_string, :schema => RELS_XSD},
       {:entry => CONTENT_TYPES_PN, :doc => content_types.to_xml_string, :schema => CONTENT_TYPES_XSD},
       {:entry => WORKBOOK_PN, :doc => workbook.to_xml_string, :schema => SML_XSD}
      ]

      workbook.drawings.each do |drawing|
        @parts << {:entry => "xl/#{drawing.rels_pn}", :doc => drawing.relationships.to_xml_string, :schema => RELS_XSD}
        @parts << {:entry => "xl/#{drawing.pn}", :doc => drawing.to_xml_string, :schema => DRAWING_XSD}
      end

      workbook.tables.each do |table|
        @parts << {:entry => "xl/#{table.pn}", :doc => table.to_xml_string, :schema => SML_XSD}
      end

      workbook.comments.each do|comment|
        if comment.size > 0
          @parts << { :entry => "xl/#{comment.pn}", :doc => comment.to_xml_string, :schema => SML_XSD }
          @parts << { :entry => "xl/#{comment.vml_drawing.pn}", :doc => comment.vml_drawing.to_xml_string, :schema => nil }
        end
      end

      workbook.charts.each do |chart|
        @parts << {:entry => "xl/#{chart.pn}", :doc => chart.to_xml_string, :schema => DRAWING_XSD}
      end

      workbook.images.each do |image|
        @parts << {:entry => "xl/#{image.pn}", :path => image.image_src}
      end

      if use_shared_strings
        @parts << {:entry => "xl/#{SHARED_STRINGS_PN}", :doc => workbook.shared_strings.to_xml_string, :schema => SML_XSD}
      end

      workbook.worksheets.each do |sheet|
        @parts << {:entry => "xl/#{sheet.rels_pn}", :doc => sheet.relationships.to_xml_string, :schema => RELS_XSD}
        @parts << {:entry => "xl/#{sheet.pn}", :doc => sheet.to_xml_string, :schema => SML_XSD}
      end
      @parts
    end

    # Performs xsd validation for a signle document
    #
    # @param [String] schema path to the xsd schema to be used in validation.
    # @param [String] doc The xml text to be validated
    # @return [Array] An array of all validation errors encountered.
    # @private
    def validate_single_doc(schema, doc)
      schema = Nokogiri::XML::Schema(File.open(schema))
      doc = Nokogiri::XML(doc)
      errors = []
      schema.validate(doc).each do |error|
        errors << error
      end
      errors
    end

    # Appends override objects for drawings, charts, and sheets as they exist in your workbook to the default content types.
    # @return [ContentType]
    # @private
    def content_types
      c_types = base_content_types

      workbook.drawings.each do |drawing|
        c_types << Axlsx::Override.new(:PartName => "/xl/#{drawing.pn}",
                                       :ContentType => DRAWING_CT)
      end

      workbook.charts.each do |chart|
        c_types << Axlsx::Override.new(:PartName => "/xl/#{chart.pn}",
                                       :ContentType => CHART_CT)
      end

      workbook.tables.each do |table|
        c_types << Axlsx::Override.new(:PartName => "/xl/#{table.pn}",
                                       :ContentType => TABLE_CT)
      end

      workbook.comments.each do |comment|
        if comment.size > 0
        c_types << Axlsx::Override.new(:PartName => "/xl/#{comment.pn}",
                                       :ContentType => COMMENT_CT)
        end
      end

      if workbook.comments.size > 0
        c_types << Axlsx::Default.new(:Extension => "vml", :ContentType => VML_DRAWING_CT)
      end

      workbook.worksheets.each do |sheet|
        c_types << Axlsx::Override.new(:PartName => "/xl/#{sheet.pn}",
                                         :ContentType => WORKSHEET_CT)
      end
      exts = workbook.images.map { |image| image.extname }
      exts.uniq.each do |ext|
        ct = if  ['jpeg', 'jpg'].include?(ext)
               JPEG_CT
             elsif ext == 'gif'
               GIF_CT
             elsif ext == 'png'
               PNG_CT
             end
        c_types << Axlsx::Default.new(:ContentType => ct, :Extension => ext )
      end
      if use_shared_strings
        c_types << Axlsx::Override.new(:PartName => "/xl/#{SHARED_STRINGS_PN}",
                                       :ContentType => SHARED_STRINGS_CT)
      end
      c_types
    end

    # Creates the minimum content types for generating a valid xlsx document.
    # @return [ContentType]
    # @private
    def base_content_types
      c_types = ContentType.new()
      c_types <<  Default.new(:ContentType => RELS_CT, :Extension => RELS_EX)
      c_types <<  Default.new(:Extension => XML_EX, :ContentType => XML_CT)
      c_types << Override.new(:PartName => "/#{APP_PN}", :ContentType => APP_CT)
      c_types << Override.new(:PartName => "/#{CORE_PN}", :ContentType => CORE_CT)
      c_types << Override.new(:PartName => "/xl/#{STYLES_PN}", :ContentType => STYLES_CT)
      c_types << Axlsx::Override.new(:PartName => "/#{WORKBOOK_PN}", :ContentType => WORKBOOK_CT)
      c_types.lock
      c_types
    end

    # Creates the relationships required for a valid xlsx document
    # @return [Relationships]
    # @private
    def relationships
      rels = Axlsx::Relationships.new
      rels << Relationship.new(WORKBOOK_R, WORKBOOK_PN)
      rels << Relationship.new(CORE_R, CORE_PN)
      rels << Relationship.new(APP_R, APP_PN)
      rels.lock
      rels
    end
  end
end