<commit_before>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2020 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "amd_isa.h"
#include "common/common.h"
#include "common/formatting.h"
#include "core/plugins.h"
#include "official/RGA/Common/AmdDxGsaCompile.h"
#include "official/RGA/elf/elf32.h"
#include "amd_isa_devices.h"

#if ENABLED(RDOC_X64)
#define DLL_NAME "atidxx64.dll"
#else
#define DLL_NAME "atidxx32.dll"
#endif

namespace GCNISA
{
extern rdcstr pluginPath;

static HMODULE GetAMDModule()
{
  // first try in the plugin locations
  HMODULE module = LoadLibraryA(LocatePluginFile(GCNISA::pluginPath, DLL_NAME).c_str());

  // if that failed then try checking for it just in the default search path
  if(module == NULL)
    module = LoadLibraryA(DLL_NAME);

  return module;
}

void SafelyCompile(PfnAmdDxGsaCompileShader compileShader, AmdDxGsaCompileShaderInput &in,
                   AmdDxGsaCompileShaderOutput &out)
{
  __try
  {
    compileShader(&in, &out);
  }
  __except(EXCEPTION_EXECUTE_HANDLER)
  {
    out.pShaderBinary = NULL;
    out.shaderBinarySize = 0;
  }
}

rdcstr DisassembleDXBC(const bytebuf &shaderBytes, const rdcstr &target)
{
  HMODULE mod = GetAMDModule();

  if(mod == NULL)
    return "; Error loading " DLL_NAME R"(.

; Currently )" DLL_NAME R"( from AMD's driver package is required for GCN disassembly and it cannot be
; distributed with RenderDoc.

; To see instructions on how to download and configure it on your system, go to:
; https://github.com/baldurk/renderdoc/wiki/GCN-ISA)";

  // if shaderBytes is empty we're testing support, so return empty string - indicating no error
  // initialising
  if(shaderBytes.empty() || target == "")
    return "";

  PfnAmdDxGsaCompileShader compileShader =
      (PfnAmdDxGsaCompileShader)GetProcAddress(mod, "AmdDxGsaCompileShader");
  PfnAmdDxGsaFreeCompiledShader freeShader =
      (PfnAmdDxGsaFreeCompiledShader)GetProcAddress(mod, "AmdDxGsaFreeCompiledShader");

  AmdDxGsaCompileShaderInput in = {};
  AmdDxGsaCompileShaderOutput out = {};

  AmdDxGsaCompileOption opts[1] = {};

  in.inputType = GsaInputDxAsmBin;
  in.numCompileOptions = 0;
  in.pCompileOptions = opts;

  for(int i = 0; i < asicCount; i++)
  {
    const asic &a = asicInfo[i];
    if(target == a.name)
    {
      in.chipFamily = a.chipFamily;
      in.chipRevision = a.chipRevision;
      break;
    }
  }

  bool amdil = false;
  if(target == "AMDIL")
  {
    in.chipFamily = asicInfo[0].chipFamily;
    in.chipRevision = asicInfo[0].chipRevision;
    amdil = true;
  }

  if(in.chipFamily == 0)
    return "; Invalid ISA Target specified";

  // we do a little mini parse of the DXBC file, just enough to get the shader code out. This is
  // because we're getting called from outside the D3D backend where the shader bytes are opaque.

  const char *dxbcParseError = "; Failed to fetch D3D shader code from DXBC";

  const byte *base = shaderBytes.data();
  const uint32_t *end = (const uint32_t *)(base + shaderBytes.size());
  const uint32_t *dxbc = (const uint32_t *)base;

  if(*dxbc != MAKE_FOURCC('D', 'X', 'B', 'C'))
    return dxbcParseError;

  dxbc++;       // fourcc
  dxbc += 4;    // hash
  dxbc++;       // unknown
  dxbc++;       // fileLength

  if(dxbc >= end)
    return dxbcParseError;

  const uint32_t numChunks = *dxbc;
  dxbc++;

  rdcarray<uint32_t> chunkOffsets;
  for(uint32_t i = 0; i < numChunks; i++)
  {
    if(dxbc >= end)
      return dxbcParseError;

    chunkOffsets.push_back(*dxbc);
    dxbc++;
  }

  in.pShaderByteCode = NULL;
  in.byteCodeLength = 0;

  for(uint32_t offs : chunkOffsets)
  {
    dxbc = (const uint32_t *)(base + offs);

    if(dxbc + 2 >= end)
      return dxbcParseError;

    if(*dxbc == MAKE_FOURCC('S', 'H', 'E', 'X') || *dxbc == MAKE_FOURCC('S', 'H', 'D', 'R'))
    {
      dxbc++;
      in.byteCodeLength = *dxbc;
      dxbc++;
      in.pShaderByteCode = dxbc;

      if(dxbc + (in.byteCodeLength / 4) > end)
        return dxbcParseError;

      break;
    }
  }

  if(in.byteCodeLength == 0)
    return dxbcParseError;

  out.size = sizeof(out);

  SafelyCompile(compileShader, in, out);

  if(out.pShaderBinary == NULL || out.shaderBinarySize < 16)
    return "; Failed to disassemble shader";

  const uint8_t *elf = (const uint8_t *)out.pShaderBinary;

  const Elf32_Ehdr *elfHeader = (const Elf32_Ehdr *)elf;

  rdcstr ret;

  // minimal code to extract data from ELF. We assume the ELF we got back is well-formed.
  if(IS_ELF(*elfHeader) && elfHeader->e_ident[EI_CLASS] == ELFCLASS32)
  {
    const Elf32_Shdr *strtab =
        (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * elfHeader->e_shstrndx);

    const uint8_t *strtabData = elf + strtab->sh_offset;

    const AmdDxGsaCompileStats *stats = NULL;

    for(int section = 1; section < elfHeader->e_shnum; section++)
    {
      if(section == elfHeader->e_shstrndx)
        continue;

      const Elf32_Shdr *sectHeader =
          (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * section);

      const char *name = (const char *)(strtabData + sectHeader->sh_name);

      const uint8_t *data = elf + sectHeader->sh_offset;

      if(!strcmp(name, ".stats"))
      {
        stats = (const AmdDxGsaCompileStats *)data;
      }
      else if(amdil && !strcmp(name, ".amdil_disassembly"))
      {
        ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
        while(ret.back() == '\0')
          ret.pop_back();
      }
      else if(!amdil && !strcmp(name, ".disassembly"))
      {
        ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
        while(ret.back() == '\0')
          ret.pop_back();
      }
    }

    if(stats && !amdil)
    {
      ret.insert(0, StringFormat::Fmt(
                        R"(; -------- Statistics ---------------------
; SGPRs: %u out of %u used
; VGPRs: %u out of %u used
; LDS: %u out of %u bytes used
; %u bytes scratch space used
; Instructions: %u ALU, %u Control Flow, %u TFETCH

)",
                        stats->numSgprsUsed, stats->availableSgprs, stats->numVgprsUsed,
                        stats->availableVgprs, stats->usedLdsBytes, stats->availableLdsBytes,
                        stats->usedScratchBytes, stats->numAluInst, stats->numControlFlowInst,
                        stats->numTfetchInst));
    }

    ret.insert(0, StringFormat::Fmt("; Disassembly for %s\n\n", target.c_str()));
  }
  else
  {
    ret = "; Invalid ELF file generated";
  }

  freeShader(out.pShaderBinary);

  return ret;
}
};
<commit_msg>Add more error logging when GCN DXBC ISA generation fails<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2020 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "amd_isa.h"
#include "common/common.h"
#include "common/formatting.h"
#include "core/plugins.h"
#include "official/RGA/Common/AmdDxGsaCompile.h"
#include "official/RGA/elf/elf32.h"
#include "amd_isa_devices.h"

#if ENABLED(RDOC_X64)
#define DLL_NAME "atidxx64.dll"
#else
#define DLL_NAME "atidxx32.dll"
#endif

namespace GCNISA
{
extern rdcstr pluginPath;

static HMODULE GetAMDModule()
{
  // first try in the plugin locations
  HMODULE module = LoadLibraryA(LocatePluginFile(GCNISA::pluginPath, DLL_NAME).c_str());

  // if that failed then try checking for it just in the default search path
  if(module == NULL)
    module = LoadLibraryA(DLL_NAME);

  return module;
}

HRESULT SafelyCompile(PfnAmdDxGsaCompileShader compileShader, AmdDxGsaCompileShaderInput &in,
                      AmdDxGsaCompileShaderOutput &out)
{
  HRESULT ret = E_FAIL;
  __try
  {
    ret = compileShader(&in, &out);
  }
  __except(EXCEPTION_EXECUTE_HANDLER)
  {
    RDCLOG("Exception occurred while compiling shader for ISA");
    out.pShaderBinary = NULL;
    out.shaderBinarySize = 0;
  }
  return ret;
}

rdcstr DisassembleDXBC(const bytebuf &shaderBytes, const rdcstr &target)
{
  HMODULE mod = GetAMDModule();

  if(mod == NULL)
    return "; Error loading " DLL_NAME R"(.

; Currently )" DLL_NAME R"( from AMD's driver package is required for GCN disassembly and it cannot be
; distributed with RenderDoc.

; To see instructions on how to download and configure it on your system, go to:
; https://github.com/baldurk/renderdoc/wiki/GCN-ISA)";

  // if shaderBytes is empty we're testing support, so return empty string - indicating no error
  // initialising
  if(shaderBytes.empty() || target == "")
    return "";

  PfnAmdDxGsaCompileShader compileShader =
      (PfnAmdDxGsaCompileShader)GetProcAddress(mod, "AmdDxGsaCompileShader");
  PfnAmdDxGsaFreeCompiledShader freeShader =
      (PfnAmdDxGsaFreeCompiledShader)GetProcAddress(mod, "AmdDxGsaFreeCompiledShader");

  AmdDxGsaCompileShaderInput in = {};
  AmdDxGsaCompileShaderOutput out = {};

  AmdDxGsaCompileOption opts[1] = {};

  in.inputType = GsaInputDxAsmBin;
  in.numCompileOptions = 0;
  in.pCompileOptions = opts;

  for(int i = 0; i < asicCount; i++)
  {
    const asic &a = asicInfo[i];
    if(target == a.name)
    {
      in.chipFamily = a.chipFamily;
      in.chipRevision = a.chipRevision;
      break;
    }
  }

  bool amdil = false;
  if(target == "AMDIL")
  {
    in.chipFamily = asicInfo[0].chipFamily;
    in.chipRevision = asicInfo[0].chipRevision;
    amdil = true;
  }

  if(in.chipFamily == 0)
    return "; Invalid ISA Target specified";

  // we do a little mini parse of the DXBC file, just enough to get the shader code out. This is
  // because we're getting called from outside the D3D backend where the shader bytes are opaque.

  const char *dxbcParseError = "; Failed to fetch D3D shader code from DXBC";

  const byte *base = shaderBytes.data();
  const uint32_t *end = (const uint32_t *)(base + shaderBytes.size());
  const uint32_t *dxbc = (const uint32_t *)base;

  if(*dxbc != MAKE_FOURCC('D', 'X', 'B', 'C'))
    return dxbcParseError;

  dxbc++;       // fourcc
  dxbc += 4;    // hash
  dxbc++;       // unknown
  dxbc++;       // fileLength

  if(dxbc >= end)
    return dxbcParseError;

  const uint32_t numChunks = *dxbc;
  dxbc++;

  rdcarray<uint32_t> chunkOffsets;
  for(uint32_t i = 0; i < numChunks; i++)
  {
    if(dxbc >= end)
      return dxbcParseError;

    chunkOffsets.push_back(*dxbc);
    dxbc++;
  }

  in.pShaderByteCode = NULL;
  in.byteCodeLength = 0;

  for(uint32_t offs : chunkOffsets)
  {
    dxbc = (const uint32_t *)(base + offs);

    if(dxbc + 2 >= end)
      return dxbcParseError;

    if(*dxbc == MAKE_FOURCC('S', 'H', 'E', 'X') || *dxbc == MAKE_FOURCC('S', 'H', 'D', 'R'))
    {
      dxbc++;
      in.byteCodeLength = *dxbc;
      dxbc++;
      in.pShaderByteCode = dxbc;

      if(dxbc + (in.byteCodeLength / 4) > end)
        return dxbcParseError;

      break;
    }
  }

  if(in.byteCodeLength == 0)
    return dxbcParseError;

  out.size = sizeof(out);

  HRESULT hr = SafelyCompile(compileShader, in, out);

  if(out.pShaderBinary == NULL || out.shaderBinarySize < 16)
  {
    RDCLOG("Failed to disassemble shader: %p/%zu (%s)", out.pShaderBinary, out.shaderBinarySize,
           ToStr(hr).c_str());
    return "; Failed to disassemble shader";
  }

  const uint8_t *elf = (const uint8_t *)out.pShaderBinary;

  const Elf32_Ehdr *elfHeader = (const Elf32_Ehdr *)elf;

  rdcstr ret;

  // minimal code to extract data from ELF. We assume the ELF we got back is well-formed.
  if(IS_ELF(*elfHeader) && elfHeader->e_ident[EI_CLASS] == ELFCLASS32)
  {
    const Elf32_Shdr *strtab =
        (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * elfHeader->e_shstrndx);

    const uint8_t *strtabData = elf + strtab->sh_offset;

    const AmdDxGsaCompileStats *stats = NULL;

    for(int section = 1; section < elfHeader->e_shnum; section++)
    {
      if(section == elfHeader->e_shstrndx)
        continue;

      const Elf32_Shdr *sectHeader =
          (const Elf32_Shdr *)(elf + elfHeader->e_shoff + sizeof(Elf32_Shdr) * section);

      const char *name = (const char *)(strtabData + sectHeader->sh_name);

      const uint8_t *data = elf + sectHeader->sh_offset;

      if(!strcmp(name, ".stats"))
      {
        stats = (const AmdDxGsaCompileStats *)data;
      }
      else if(amdil && !strcmp(name, ".amdil_disassembly"))
      {
        ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
        while(ret.back() == '\0')
          ret.pop_back();
      }
      else if(!amdil && !strcmp(name, ".disassembly"))
      {
        ret.insert(0, (const char *)data, (size_t)sectHeader->sh_size);
        while(ret.back() == '\0')
          ret.pop_back();
      }
    }

    if(stats && !amdil)
    {
      ret.insert(0, StringFormat::Fmt(
                        R"(; -------- Statistics ---------------------
; SGPRs: %u out of %u used
; VGPRs: %u out of %u used
; LDS: %u out of %u bytes used
; %u bytes scratch space used
; Instructions: %u ALU, %u Control Flow, %u TFETCH

)",
                        stats->numSgprsUsed, stats->availableSgprs, stats->numVgprsUsed,
                        stats->availableVgprs, stats->usedLdsBytes, stats->availableLdsBytes,
                        stats->usedScratchBytes, stats->numAluInst, stats->numControlFlowInst,
                        stats->numTfetchInst));
    }

    ret.insert(0, StringFormat::Fmt("; Disassembly for %s\n\n", target.c_str()));
  }
  else
  {
    ret = "; Invalid ELF file generated";
  }

  freeShader(out.pShaderBinary);

  return ret;
}
};
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <unique_ptr.hpp>
#include <array.hpp>
#include <string.hpp>

#include "disks.hpp"
#include "ata.hpp"
#include "thor.hpp"
#include "console.hpp"

#include "fs/devfs.hpp"

namespace {

//For now, 4 is enough as only the ata driver is implemented
std::array<disks::disk_descriptor, 4> _disks;

uint64_t number_of_disks = 0;

struct partition_descriptor_t {
    uint8_t boot_flag;
    uint8_t chs_begin[3];
    uint8_t type_code;
    uint8_t chs_end[3];
    uint32_t lba_begin;
    uint32_t sectors;
} __attribute__ ((packed));

static_assert(sizeof(partition_descriptor_t) == 16, "A partition descriptor is 16 bytes long");

struct boot_record_t {
    uint8_t boot_code[446];
    partition_descriptor_t partitions[4];
    uint16_t signature;
} __attribute__ ((packed));

static_assert(sizeof(boot_record_t) == 512, "The boot record is 512 bytes long");

ata::ata_driver ata_driver_impl;
ata::ata_part_driver ata_part_driver_impl;

devfs::dev_driver* ata_driver = &ata_driver_impl;
devfs::dev_driver* ata_part_driver = &ata_part_driver_impl;
devfs::dev_driver* atapi_driver = nullptr;

} //end of anonymous namespace

void disks::detect_disks(){
    ata::detect_disks();

    char cdrom = 'a';
    char disk = 'a';

    for(uint8_t i = 0; i < ata::number_of_disks(); ++i){
        auto& descriptor = ata::drive(i);

        if(descriptor.present){
            if(descriptor.atapi){
                _disks[number_of_disks] = {number_of_disks, disks::disk_type::ATAPI, &descriptor};

                std::string name = "cd";
                name += cdrom++;

                devfs::register_device("/dev/", name, devfs::device_type::BLOCK_DEVICE, atapi_driver, &_disks[number_of_disks]);
            } else {
                _disks[number_of_disks] = {number_of_disks, disks::disk_type::ATA, &descriptor};

                std::string name = "hd";
                name += disk++;

                devfs::register_device("/dev/", name, devfs::device_type::BLOCK_DEVICE, ata_driver, &_disks[number_of_disks]);

                char part = '1';

                for(auto& partition : partitions(_disks[number_of_disks])){
                    auto part_name = name + part++;

                    devfs::register_device("/dev/", part_name, devfs::device_type::BLOCK_DEVICE, ata_part_driver, new partition_descriptor(partition));
                }
            }

            ++number_of_disks;
        }
    }
}

disks::disk_descriptor& disks::disk_by_index(uint64_t index){
    return _disks[index];
}

disks::disk_descriptor& disks::disk_by_uuid(uint64_t uuid){
    for(uint64_t i = 0; i < number_of_disks; ++i){
        if(_disks[i].uuid == uuid){
            return _disks[i];
        }
    }

    __builtin_unreachable();
}

std::unique_heap_array<disks::partition_descriptor> disks::partitions(disk_descriptor& disk){
    std::unique_ptr<boot_record_t> boot_record(new boot_record_t());

    size_t read;
    if(ata::read_sectors(*static_cast<ata::drive_descriptor*>(disk.descriptor), 0, 1, boot_record.get(), read) > 0){
        k_print_line("Read Boot Record failed");

        return {};
    } else {
        if(boot_record->signature != 0xAA55){
            k_print_line("Invalid boot record signature");

            return {};
        }

        uint64_t n = 0;
        for(int i = 0; i < 4; ++i){
            if(boot_record->partitions[i].type_code > 0){
                ++n;
            }
        }

        std::unique_heap_array<partition_descriptor> partitions(n);
        uint64_t p = 0;

        for(uint64_t i = 0; i < 4; ++i){
            if(boot_record->partitions[i].type_code > 0){
                vfs::partition_type type;
                if(boot_record->partitions[i].type_code == 0x0B || boot_record->partitions[i].type_code == 0x0C){
                    type = vfs::partition_type::FAT32;
                } else {
                    type = vfs::partition_type::UNKNOWN;
                }

                partitions[p] = {p, type, boot_record->partitions[i].lba_begin, boot_record->partitions[i].sectors, &disk};

                ++p;
            }
        }

        return partitions;
    }
}
<commit_msg>Exposes ATA information<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <unique_ptr.hpp>
#include <array.hpp>
#include <string.hpp>

#include "disks.hpp"
#include "ata.hpp"
#include "thor.hpp"
#include "console.hpp"

#include "fs/devfs.hpp"
#include "fs/sysfs.hpp"

namespace {

//For now, 4 is enough as only the ata driver is implemented
std::array<disks::disk_descriptor, 4> _disks;

uint64_t number_of_disks = 0;

struct partition_descriptor_t {
    uint8_t boot_flag;
    uint8_t chs_begin[3];
    uint8_t type_code;
    uint8_t chs_end[3];
    uint32_t lba_begin;
    uint32_t sectors;
} __attribute__ ((packed));

static_assert(sizeof(partition_descriptor_t) == 16, "A partition descriptor is 16 bytes long");

struct boot_record_t {
    uint8_t boot_code[446];
    partition_descriptor_t partitions[4];
    uint16_t signature;
} __attribute__ ((packed));

static_assert(sizeof(boot_record_t) == 512, "The boot record is 512 bytes long");

ata::ata_driver ata_driver_impl;
ata::ata_part_driver ata_part_driver_impl;

devfs::dev_driver* ata_driver = &ata_driver_impl;
devfs::dev_driver* ata_part_driver = &ata_part_driver_impl;
devfs::dev_driver* atapi_driver = nullptr;

} //end of anonymous namespace

void disks::detect_disks(){
    ata::detect_disks();

    char cdrom = 'a';
    char disk = 'a';

    for(uint8_t i = 0; i < ata::number_of_disks(); ++i){
        auto& descriptor = ata::drive(i);

        if(descriptor.present){
            std::string name;
            if(descriptor.atapi){
                _disks[number_of_disks] = {number_of_disks, disks::disk_type::ATAPI, &descriptor};

                name = "cd";
                name += cdrom++;

                devfs::register_device("/dev/", name, devfs::device_type::BLOCK_DEVICE, atapi_driver, &_disks[number_of_disks]);
            } else {
                _disks[number_of_disks] = {number_of_disks, disks::disk_type::ATA, &descriptor};

                name = "hd";
                name += disk++;

                devfs::register_device("/dev/", name, devfs::device_type::BLOCK_DEVICE, ata_driver, &_disks[number_of_disks]);

                char part = '1';

                for(auto& partition : partitions(_disks[number_of_disks])){
                    auto part_name = name + part++;

                    devfs::register_device("/dev/", part_name, devfs::device_type::BLOCK_DEVICE, ata_part_driver, new partition_descriptor(partition));
                }
            }

            std::string path = "/ata/" + name;

            sysfs::set_constant_value("/sys/", path + "/model", descriptor.model);
            sysfs::set_constant_value("/sys/", path + "/serial", descriptor.serial);
            sysfs::set_constant_value("/sys/", path + "/firmware", descriptor.firmware);

            ++number_of_disks;
        }
    }
}

disks::disk_descriptor& disks::disk_by_index(uint64_t index){
    return _disks[index];
}

disks::disk_descriptor& disks::disk_by_uuid(uint64_t uuid){
    for(uint64_t i = 0; i < number_of_disks; ++i){
        if(_disks[i].uuid == uuid){
            return _disks[i];
        }
    }

    __builtin_unreachable();
}

std::unique_heap_array<disks::partition_descriptor> disks::partitions(disk_descriptor& disk){
    std::unique_ptr<boot_record_t> boot_record(new boot_record_t());

    size_t read;
    if(ata::read_sectors(*static_cast<ata::drive_descriptor*>(disk.descriptor), 0, 1, boot_record.get(), read) > 0){
        k_print_line("Read Boot Record failed");

        return {};
    } else {
        if(boot_record->signature != 0xAA55){
            k_print_line("Invalid boot record signature");

            return {};
        }

        uint64_t n = 0;
        for(int i = 0; i < 4; ++i){
            if(boot_record->partitions[i].type_code > 0){
                ++n;
            }
        }

        std::unique_heap_array<partition_descriptor> partitions(n);
        uint64_t p = 0;

        for(uint64_t i = 0; i < 4; ++i){
            if(boot_record->partitions[i].type_code > 0){
                vfs::partition_type type;
                if(boot_record->partitions[i].type_code == 0x0B || boot_record->partitions[i].type_code == 0x0C){
                    type = vfs::partition_type::FAT32;
                } else {
                    type = vfs::partition_type::UNKNOWN;
                }

                partitions[p] = {p, type, boot_record->partitions[i].lba_begin, boot_record->partitions[i].sectors, &disk};

                ++p;
            }
        }

        return partitions;
    }
}
<|endoftext|>


<commit_before>// @(#)root/meta:$Name:  $:$Id: TToggle.cxx,v 1.3 2002/02/21 15:40:08 rdm Exp $
// Author: Piotr Golonka   30/07/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TToggle                                                              //
//                                                                      //
// This class defines toggling facility for both - object's method or   //
// variables.                                                           //
// Assume that user provides an object with a two-state field , and     //
// methods to Get/Set value of this field. This object enables to switch//
// values via this method when the only thing you know about the field  //
// is the name of the method (or method itself) which sets the field.   //
// This facility is required in context Pop-Up menu, when the only      //
// information about how to toggle a field is a name of methhod which   //
// sets it.                                                             //
// This class may be also used for toggling an integer variable,        //
// which may be important while building universal objects...           //
// When user provides a "set-method" of name SetXXX this object tries   //
// automaticaly find a matching "get-method" by lookin for a method     //
// with name GetXXX, IsXXX or HasXXX for given object.                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TClass.h"
#include "TMethod.h"
#include "TToggle.h"
#include "TDataMember.h"

ClassImp(TToggle)

//______________________________________________________________________________
TToggle::TToggle()
{
   // TToggle default constructor. You have to initialize it before using
   // by making a call to SetToggledVariable() or SetToggledObject().

   fState       =  0;
   fValue       = -1;
   fOnValue     =  1;
   fOffValue    =  0;
   fInitialized =  0;
   fObject      =  0;
   fGetter      =  0;
   fSetter      =  0;
   fTglVariable =  0;
}

//______________________________________________________________________________
void TToggle::SetToggledVariable(Int_t &var)
{
   // Initializes object for use with a variable - you pass it via reference
   // so it will be modified by Toggle.

   fTglVariable=&var;
   fValue=var;
}

//______________________________________________________________________________
Bool_t  TToggle::GetState()
{
   // Returns the state of Toggle according to its current value and
   // fOnValue ; Returns true if they match.

   if (fInitialized) {
      fGetter->Execute(fObject,fValue);
      return (fState=(fValue==fOnValue));
   }
}

//______________________________________________________________________________
void TToggle::SetState(Bool_t state)
{
   // Sets the value of toggle to fOnValue or fOffValue according to passed
   // argument.

   if (fInitialized) {
      char stringon[7];
      char stringoff[7];
      sprintf(stringon,"%li",fOnValue);
      sprintf(stringoff,"%li",fOffValue);

      fSetter->Execute(fObject, state ? stringon:stringoff);
      fState=state;
      fValue= ( state ? fOnValue : fOffValue);
   }
}

//______________________________________________________________________________
void TToggle::SetValue(Long_t val)
{
   // Sets the value of toggle and modifies its state according to whether
   // the value is equal to fOnValue.

   if (fInitialized) {
      char stringval[7];
      sprintf(stringval,"%li",val);
      fSetter->Execute(fObject, stringval);
      fState=(val==fOnValue);
      fValue= val;
   }
}

//______________________________________________________________________________
void TToggle::Toggle()
{
   // Toggles the Values and State of this object and connected data!

   if (fInitialized){
      if (fTglVariable){
         *fTglVariable = !(*fTglVariable);
         fValue=(*fTglVariable);
         fState=*fTglVariable;
      }
      if (fGetter && fSetter){
         fGetter->Execute(fObject,fValue);
         fValue=( (fValue==fOnValue) ? fOffValue:fOnValue);
         fState=(!(fValue!=fOnValue));
         char stringon[7];
         sprintf(stringon,"%li",fValue);
         fSetter->Execute(fObject, stringon);
      }
   }
}

//______________________________________________________________________________
void TToggle::SetToggledObject(TObject *obj, TMethod *anymethod)
{
   // Initializes it to toggle an object's datamember using this object's
   // method.

   fObject = obj;
   TDataMember *m = anymethod->FindDataMember();
   if (!m) {
      // try to see if the TMethod has a getter associated via the *GETTER=
      // comment string
      if (anymethod->GetterMethod()) {
         fGetter = anymethod->GetterMethod();
         fSetter = anymethod->SetterMethod();
         fInitialized = 1;
      } else
         Error("SetToggledObject", "cannot determine getter method for %s", anymethod->GetName());
   } else {
      fGetter = m->GetterMethod(obj->IsA());
      fSetter = m->SetterMethod(obj->IsA());
      fInitialized = 1;
   }
}
<commit_msg>method Bool_t GetState() was not returning a value.<commit_after>// @(#)root/meta:$Name:  $:$Id: TToggle.cxx,v 1.4 2004/03/12 00:25:59 rdm Exp $
// Author: Piotr Golonka   30/07/97

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TToggle                                                              //
//                                                                      //
// This class defines toggling facility for both - object's method or   //
// variables.                                                           //
// Assume that user provides an object with a two-state field , and     //
// methods to Get/Set value of this field. This object enables to switch//
// values via this method when the only thing you know about the field  //
// is the name of the method (or method itself) which sets the field.   //
// This facility is required in context Pop-Up menu, when the only      //
// information about how to toggle a field is a name of methhod which   //
// sets it.                                                             //
// This class may be also used for toggling an integer variable,        //
// which may be important while building universal objects...           //
// When user provides a "set-method" of name SetXXX this object tries   //
// automaticaly find a matching "get-method" by lookin for a method     //
// with name GetXXX, IsXXX or HasXXX for given object.                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TClass.h"
#include "TMethod.h"
#include "TToggle.h"
#include "TDataMember.h"

ClassImp(TToggle)

//______________________________________________________________________________
TToggle::TToggle()
{
   // TToggle default constructor. You have to initialize it before using
   // by making a call to SetToggledVariable() or SetToggledObject().

   fState       =  kFALSE;
   fValue       = -1;
   fOnValue     =  1;
   fOffValue    =  0;
   fInitialized =  0;
   fObject      =  0;
   fGetter      =  0;
   fSetter      =  0;
   fTglVariable =  0;
}

//______________________________________________________________________________
void TToggle::SetToggledVariable(Int_t &var)
{
   // Initializes object for use with a variable - you pass it via reference
   // so it will be modified by Toggle.

   fTglVariable=&var;
   fValue=var;
}

//______________________________________________________________________________
Bool_t TToggle::GetState()
{
   // Returns the state of Toggle according to its current value and
   // fOnValue, returns true if they match.

   if (fInitialized)
      fGetter->Execute(fObject, fValue);
   return (fState = (fValue == fOnValue));
}

//______________________________________________________________________________
void TToggle::SetState(Bool_t state)
{
   // Sets the value of toggle to fOnValue or fOffValue according to passed
   // argument.

   if (fInitialized) {
      char stringon[7];
      char stringoff[7];
      sprintf(stringon,"%li",fOnValue);
      sprintf(stringoff,"%li",fOffValue);

      fSetter->Execute(fObject, state ? stringon:stringoff);
      fState=state;
      fValue= ( state ? fOnValue : fOffValue);
   }
}

//______________________________________________________________________________
void TToggle::SetValue(Long_t val)
{
   // Sets the value of toggle and modifies its state according to whether
   // the value is equal to fOnValue.

   if (fInitialized) {
      char stringval[7];
      sprintf(stringval,"%li",val);
      fSetter->Execute(fObject, stringval);
      fState=(val==fOnValue);
      fValue= val;
   }
}

//______________________________________________________________________________
void TToggle::Toggle()
{
   // Toggles the Values and State of this object and connected data!

   if (fInitialized){
      if (fTglVariable){
         *fTglVariable = !(*fTglVariable);
         fValue=(*fTglVariable);
         fState=*fTglVariable;
      }
      if (fGetter && fSetter){
         fGetter->Execute(fObject,fValue);
         fValue=( (fValue==fOnValue) ? fOffValue:fOnValue);
         fState=(!(fValue!=fOnValue));
         char stringon[7];
         sprintf(stringon,"%li",fValue);
         fSetter->Execute(fObject, stringon);
      }
   }
}

//______________________________________________________________________________
void TToggle::SetToggledObject(TObject *obj, TMethod *anymethod)
{
   // Initializes it to toggle an object's datamember using this object's
   // method.

   fObject = obj;
   TDataMember *m = anymethod->FindDataMember();
   if (!m) {
      // try to see if the TMethod has a getter associated via the *GETTER=
      // comment string
      if (anymethod->GetterMethod()) {
         fGetter = anymethod->GetterMethod();
         fSetter = anymethod->SetterMethod();
         fInitialized = 1;
      } else
         Error("SetToggledObject", "cannot determine getter method for %s", anymethod->GetName());
   } else {
      fGetter = m->GetterMethod(obj->IsA());
      fSetter = m->SetterMethod(obj->IsA());
      fInitialized = 1;
   }
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "baseAST.h"
#include "files.h"
#include "misc.h"
#include "log.h"
#include "runpasses.h"
#include "stringutil.h"
#include "view.h"

bool printPasses = false;

struct PassInfo {
  void (*fn)(void);
  const char *name;
};

#define FIRST {NULL, NULL}
#define LAST {NULL, NULL}
#define RUN(x) {x, #x}
#include "passlist.h"

static void runPass(const char *passName, void (*pass)(void)) {
  static struct timeval startTimeBetweenPasses;
  static struct timeval stopTimeBetweenPasses;
  static double timeBetweenPasses = -1.0;
  static double totalTime = 0.0;
  struct timeval startTime;
  struct timeval stopTime;
  struct timezone timezone;

  if (printPasses) {
    gettimeofday(&stopTimeBetweenPasses, &timezone);
    if (timeBetweenPasses < 0.0)
      timeBetweenPasses = 0.0;
    else
      timeBetweenPasses +=
        ((double)((stopTimeBetweenPasses.tv_sec*1e6+
                   stopTimeBetweenPasses.tv_usec) -
                  (startTimeBetweenPasses.tv_sec*1e6+
                   startTimeBetweenPasses.tv_usec))) / 1e6;
  }
  if (strlen(fPrintStatistics) && strcmp(passName, "parse"))
    printStatistics("clean");
  if (printPasses) {
    fprintf(stderr, "%32s :", passName);
    fflush(stderr);
    gettimeofday(&startTime, &timezone);
  }
  (*pass)();
  if (printPasses) {
    gettimeofday(&stopTime, &timezone);
    fprintf(stderr, "%8.3f seconds\n",
            ((double)((stopTime.tv_sec*1e6+stopTime.tv_usec) -
                      (startTime.tv_sec*1e6+startTime.tv_usec))) / 1e6);
    totalTime += ((double)((stopTime.tv_sec*1e6+stopTime.tv_usec) -
                           (startTime.tv_sec*1e6+startTime.tv_usec))) / 1e6;
    if (!strcmp(passName, "makeBinary")) {
      fprintf(stderr, "%32s :%8.3f seconds\n", "time between passes",
              timeBetweenPasses);
      fprintf(stderr, "%32s :%8.3f seconds\n", "total time",
              totalTime+timeBetweenPasses);
    }
  }
  if (strlen(fPrintStatistics))
    printStatistics(passName);
  if (fdump_html) {
    html_view(passName);
  }
  if (printPasses) {
    gettimeofday(&startTimeBetweenPasses, &timezone);
  }
  cleanAst();
  verify();
}

static void dump_index_header(FILE* f) {
  fprintf(f, "\n");
  fprintf(f, "\n");
  fprintf(f, "<TITLE> Compilation Dump </TITLE>\n");
  fprintf(f, "",
         chplhome);
  fprintf(f, "<LINK REL=\"stylesheet\" HREF=\"%s/compiler/etc/www/mktree.css\">",
         chplhome);
  fprintf(f, "\n");
  fprintf(f, "
<big><big>");
  fprintf(f, "Compilation Dump

</big></big>\n");
  fprintf(f, "
\n\n");
}

static void dump_index_footer(FILE* f) {
  fprintf(f, "\n");
}

void runPasses(void) {
  if (fdump_html) {
    html_index_file = fopen(astr(log_dir, "index.html"), "w");
    dump_index_header(html_index_file);
    fprintf(html_index_file, "
");
  }
  PassInfo* pass = passlist+1;  // skip over FIRST
  while (pass->name != NULL) {
    runPass(pass->name, pass->fn);
    check_fatal_errors_encountered();
    pass++;
  }
  if (fdump_html) {
    fprintf(html_index_file, "
");
    dump_index_footer(html_index_file);
    fclose(html_index_file);
  }
  destroyAst();
}
<commit_msg>Added a compile time error message when opening the html index file for writing fails<commit_after>#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include "baseAST.h"
#include "files.h"
#include "misc.h"
#include "log.h"
#include "runpasses.h"
#include "stringutil.h"
#include "view.h"

bool printPasses = false;

struct PassInfo {
  void (*fn)(void);
  const char *name;
};

#define FIRST {NULL, NULL}
#define LAST {NULL, NULL}
#define RUN(x) {x, #x}
#include "passlist.h"

static void runPass(const char *passName, void (*pass)(void)) {
  static struct timeval startTimeBetweenPasses;
  static struct timeval stopTimeBetweenPasses;
  static double timeBetweenPasses = -1.0;
  static double totalTime = 0.0;
  struct timeval startTime;
  struct timeval stopTime;
  struct timezone timezone;

  if (printPasses) {
    gettimeofday(&stopTimeBetweenPasses, &timezone);
    if (timeBetweenPasses < 0.0)
      timeBetweenPasses = 0.0;
    else
      timeBetweenPasses +=
        ((double)((stopTimeBetweenPasses.tv_sec*1e6+
                   stopTimeBetweenPasses.tv_usec) -
                  (startTimeBetweenPasses.tv_sec*1e6+
                   startTimeBetweenPasses.tv_usec))) / 1e6;
  }
  if (strlen(fPrintStatistics) && strcmp(passName, "parse"))
    printStatistics("clean");
  if (printPasses) {
    fprintf(stderr, "%32s :", passName);
    fflush(stderr);
    gettimeofday(&startTime, &timezone);
  }
  (*pass)();
  if (printPasses) {
    gettimeofday(&stopTime, &timezone);
    fprintf(stderr, "%8.3f seconds\n",
            ((double)((stopTime.tv_sec*1e6+stopTime.tv_usec) -
                      (startTime.tv_sec*1e6+startTime.tv_usec))) / 1e6);
    totalTime += ((double)((stopTime.tv_sec*1e6+stopTime.tv_usec) -
                           (startTime.tv_sec*1e6+startTime.tv_usec))) / 1e6;
    if (!strcmp(passName, "makeBinary")) {
      fprintf(stderr, "%32s :%8.3f seconds\n", "time between passes",
              timeBetweenPasses);
      fprintf(stderr, "%32s :%8.3f seconds\n", "total time",
              totalTime+timeBetweenPasses);
    }
  }
  if (strlen(fPrintStatistics))
    printStatistics(passName);
  if (fdump_html) {
    html_view(passName);
  }
  if (printPasses) {
    gettimeofday(&startTimeBetweenPasses, &timezone);
  }
  cleanAst();
  verify();
}

static void dump_index_header(FILE* f) {
  fprintf(f, "\n");
  fprintf(f, "\n");
  fprintf(f, "<TITLE> Compilation Dump </TITLE>\n");
  fprintf(f, "",
         chplhome);
  fprintf(f, "<LINK REL=\"stylesheet\" HREF=\"%s/compiler/etc/www/mktree.css\">",
         chplhome);
  fprintf(f, "\n");
  fprintf(f, "
<big><big>");
  fprintf(f, "Compilation Dump

</big></big>\n");
  fprintf(f, "
\n\n");
}

static void dump_index_footer(FILE* f) {
  fprintf(f, "\n");
}

void runPasses(void) {
  if (fdump_html) {
    if (!(html_index_file = fopen(astr(log_dir, "index.html"), "w"))) {
      USR_FATAL("cannot open html index file \"%s\" for writing", astr(log_dir, "index.html"));
    }
    dump_index_header(html_index_file);
    fprintf(html_index_file, "
");
  }
  PassInfo* pass = passlist+1;  // skip over FIRST
  while (pass->name != NULL) {
    runPass(pass->name, pass->fn);
    check_fatal_errors_encountered();
    pass++;
  }
  if (fdump_html) {
    fprintf(html_index_file, "
");
    dump_index_footer(html_index_file);
    fclose(html_index_file);
  }
  destroyAst();
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "astutil.h"
#include "beautify.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "symscope.h"

static int max(int a, int b) {
  return (a >= b) ? a : b;
}

static void setOrder(Map<ClassType*,int>& order, int& maxOrder, ClassType* ct);

static int
getOrder(Map<ClassType*,int>& order, int& maxOrder,
         ClassType* ct, Vec<ClassType*>& visit) {
  if (visit.set_in(ct))
    return 0;
  visit.set_add(ct);
  if (order.get(ct))
    return order.get(ct);
  int i = 0;
  for_fields(field, ct) {
    if (ClassType* fct = dynamic_cast<ClassType*>(field->type)) {
      if (!visit.set_in(fct) && fct->classTag != CLASS_CLASS)
        setOrder(order, maxOrder, fct);
      i = max(i, getOrder(order, maxOrder, fct, visit));
    }
  }
  return i + (ct->classTag != CLASS_CLASS);
}

static void
setOrder(Map<ClassType*,int>& order, int& maxOrder,
         ClassType* ct) {
  if (ct->classTag == CLASS_CLASS || order.get(ct))
    return;
  int i;
  Vec<ClassType*> visit;
  i = getOrder(order, maxOrder, ct, visit);
  order.put(ct, i);
  if (i > maxOrder)
    maxOrder = i;
}

#define STRSUB(x)                               \
  *ch = '\0';                                   \
  sym->cname = stringcat(sym->cname, x, ch+1);  \
  ch = sym->cname

static void legalizeCName(Symbol* sym) {
  for (char* ch = sym->cname; *ch != '\0'; ch++) {
    switch (*ch) {
    case '>': STRSUB("_GREATER_"); break;
    case '<': STRSUB("_LESS_"); break;
    case '=': STRSUB("_EQUAL_"); break;
    case '*': STRSUB("_ASTERISK_"); break;
    case '/': STRSUB("_SLASH_"); break;
    case '%': STRSUB("_PERCENT_"); break;
    case '+': STRSUB("_PLUS_"); break;
    case '-': STRSUB("_HYPHEN_"); break;
    case '^': STRSUB("_CARET_"); break;
    case '&': STRSUB("_AMPERSAND_"); break;
    case '|': STRSUB("_BAR_"); break;
    case '!': STRSUB("_EXCLAMATION_"); break;
    case '#': STRSUB("_POUND_"); break;
    case '?': STRSUB("_QUESTION_"); break;
    case '~': STRSUB("_TILDA_"); break;
    default: break;
    }
  }
}

static void codegen_header(void) {
  ChainHashMap<char*, StringHashFns, int> cnames;
  Vec<TypeSymbol*> typeSymbols;
  Vec<FnSymbol*> fnSymbols;
  Vec<VarSymbol*> varSymbols;

  chpl_main->addPragma("rename _chpl_main");

  // reserved C words that require renaming to compile
  cnames.put("abs", 1);
  cnames.put("exit", 1);
  cnames.put("_init", 1);
  cnames.put("stdin", 1);
  cnames.put("close", 1);
  cnames.put("fwrite", 1);
  cnames.put("fread", 1);
  cnames.put("main", 1);
  cnames.put("open", 1);
  cnames.put("printf", 1);
  cnames.put("quad", 1);
  cnames.put("read", 1);
  cnames.put("sleep", 1);
  cnames.put("stderr", 1);
  cnames.put("stdout", 1);
  cnames.put("write", 1);
  cnames.put("y1", 1); // this is ridiculous...
  cnames.put("log2", 1);
  cnames.put("remove", 1);
  cnames.put("fprintf", 1);
  cnames.put("clone", 1);
  cnames.put("new", 1);
  cnames.put("register", 1);

  forv_Vec(BaseAST, ast, gAsts) {
    if (CallExpr* call = dynamic_cast<CallExpr*>(ast))
      if (FnSymbol* fn = call->isResolved())
        if (fn->hasPragma("c for loop increment"))
          call->remove();

    if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
      Symbol* sym = def->sym;

      if (sym->name == sym->cname)
        sym->cname = stringcpy(sym->name);

      if (char* pragma = sym->hasPragmaPrefix("rename"))
        sym->cname = stringcpy(pragma+7);

      if (VarSymbol* vs = dynamic_cast<VarSymbol*>(ast))
        if (vs->immediate)
          continue;

      legalizeCName(sym);

      // mangle symbol that is neither field nor formal if the symbol's
      // name has already been encountered
      if (!dynamic_cast<ArgSymbol*>(sym) &&
          !dynamic_cast<UnresolvedSymbol*>(sym) &&
          !dynamic_cast<ClassType*>(sym->parentScope->astParent) &&
          cnames.get(sym->cname))
        sym->cname = stringcat("_", sym->cname, "_", intstring(sym->id));

      cnames.put(sym->cname, 1);

      if (TypeSymbol* typeSymbol = dynamic_cast<TypeSymbol*>(sym)) {
        typeSymbols.add(typeSymbol);
      } else if (FnSymbol* fnSymbol = dynamic_cast<FnSymbol*>(sym)) {
        fnSymbols.add(fnSymbol);
      } else if (VarSymbol* varSymbol = dynamic_cast<VarSymbol*>(sym)) {
        if (varSymbol->parentScope->parent == rootScope)
          varSymbols.add(varSymbol);
      }
    }
  }

  qsort(varSymbols.v, varSymbols.n, sizeof(varSymbols.v[0]), compareSymbol);
  qsort(typeSymbols.v, typeSymbols.n, sizeof(typeSymbols.v[0]), compareSymbol);
  qsort(fnSymbols.v, fnSymbols.n, sizeof(fnSymbols.v[0]), compareSymbol);

  fileinfo header;
  openCFile(&header, "_chpl_header", "h");
  FILE* outfile = header.fptr;

  fprintf(outfile, "#include \"stdchpl.h\"\n");
  fprintf(outfile, "\n/*** Class Reference Types ***/\n\n");

  forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {
    typeSymbol->codegenPrototype(outfile);
  }

  // codegen enumerated types
  fprintf(outfile, "\n/*** Enumerated Types ***/\n\n");
  forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {
    if (dynamic_cast<EnumType*>(typeSymbol->type))
      typeSymbol->codegenDef(outfile);
  }

  // order records/unions topologically
  //   (int, int) before (int, (int, int))
  Map<ClassType*,int> order;
  int maxOrder = 0;
  forv_Vec(TypeSymbol, ts, typeSymbols) {
    if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))
      setOrder(order, maxOrder, ct);
  }

  // debug
//   for (int i = 0; i < order.n; i++) {
//     if (order.v[i].key && order.v[i].value) {
//       printf("%d: %s\n", order.v[i].value, order.v[i].key->symbol->name);
//     }
//   }
//   printf("%d\n", maxOrder);

  // codegen records/unions in topological order
  fprintf(outfile, "\n/*** Records and Unions (Hierarchically) ***/\n\n");
  for (int i = 1; i <= maxOrder; i++) {
    forv_Vec(TypeSymbol, ts, typeSymbols) {
      if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))
        if (order.get(ct) == i)
          ts->codegenDef(outfile);
    }
  }

  // codegen remaining types
  fprintf(outfile, "/*** Classes ***/\n\n");
  forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {
    if (ClassType* ct = dynamic_cast<ClassType*>(typeSymbol->type))
      if (ct->classTag != CLASS_CLASS)
        continue;
    if (dynamic_cast<EnumType*>(typeSymbol->type))
      continue;
    typeSymbol->codegenDef(outfile);
  }

  fprintf(outfile, "/*** Function Prototypes ***/\n\n");
  forv_Vec(FnSymbol, fnSymbol, fnSymbols) {
    fnSymbol->codegenPrototype(outfile);
  }

  fprintf(outfile, "\n/*** Global Variables ***/\n\n");
  forv_Vec(VarSymbol, varSymbol, varSymbols) {
    varSymbol->codegenDef(outfile);
  }
  closeCFile(&header);
  beautify(&header);
}

static void
codegen_cid2size(FILE* outfile) {
  fprintf(outfile, "size_t cid2size(_int64 cid) {\n");
  fprintf(outfile, "size_t size;\n");
  fprintf(outfile, "switch(cid) {\n");
  forv_Vec(TypeSymbol, typeSym, gTypes) {
    if (ClassType* ct = dynamic_cast<ClassType*>(typeSym->type)) {
      if (ct->classTag == CLASS_CLASS) {
        fprintf(outfile, "case %d:\n", ct->id);
        fprintf(outfile, "size = sizeof(_");
        ct->symbol->codegen(outfile);
        fprintf(outfile, ");\n");
        fprintf(outfile, "break;\n");
      }
    }
  }
  fprintf(outfile, "default:\n");
  fprintf(outfile, "halt(\"Bad cid in cid2size\", 1, \"\");\n");
  fprintf(outfile, "break;\n");
  fprintf(outfile, "}\n");
  fprintf(outfile, "return size;\n");
  fprintf(outfile, "}\n");
}

static void
codegen_config(FILE* outfile) {
  fprintf(outfile, "void CreateConfigVarTable(void) {\n");
  fprintf(outfile, "initConfigVarTable();\n");

  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
      VarSymbol* var = dynamic_cast<VarSymbol*>(def->sym);
      if (var && var->varClass == VAR_CONFIG) {
        fprintf(outfile, "installConfigVar(\"%s\", \"", var->name);
        fprintf(outfile, var->type->symbol->name);
        fprintf(outfile, "\", \"%s\");\n", var->getModule()->name);
      }
    }
  }

  fprintf(outfile, "if (askedToParseArgs()) {\n");
  fprintf(outfile, "  parseConfigArgs();\n");
  fprintf(outfile, "}\n");

  fprintf(outfile, "if (askedToPrintHelpMessage()) {\n");
  fprintf(outfile, "  printHelpTable();\n");
  fprintf(outfile, "  printConfigVarTable();\n");
  fprintf(outfile, "}\n");

  fprintf(outfile, "}\n");
}

void codegen(void) {
  if (no_codegen)
    return;

  fileinfo mainfile;
  openCFile(&mainfile, "_main", "c");
  fprintf(mainfile.fptr, "#include \"_chpl_header.h\"\n");

  codegen_makefile(&mainfile);

  codegen_header();

  codegen_config(mainfile.fptr);

  forv_Vec(ModuleSymbol, currentModule, allModules) {
    mysystem(stringcat("# codegen-ing module", currentModule->name),
             "generating comment for --print-commands option");

    fileinfo modulefile;
    openCFile(&modulefile, currentModule->name, "c");
    currentModule->codegenDef(modulefile.fptr);
    closeCFile(&modulefile);
    fprintf(mainfile.fptr, "#include \"%s%s\"\n", currentModule->name, ".c");
    beautify(&modulefile);
  }

  codegen_cid2size(mainfile.fptr);
  closeCFile(&mainfile);
  beautify(&mainfile);
  makeBinary();
}
<commit_msg>Fix two nightly testing regressions.  The cid2size function was calling "halt" as the default case.  The definition of "halt" can change depending on the input.  Instead, call "_printError".<commit_after>#include <stdio.h>
#include "astutil.h"
#include "beautify.h"
#include "driver.h"
#include "expr.h"
#include "files.h"
#include "mysystem.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "symscope.h"

static int max(int a, int b) {
  return (a >= b) ? a : b;
}

static void setOrder(Map<ClassType*,int>& order, int& maxOrder, ClassType* ct);

static int
getOrder(Map<ClassType*,int>& order, int& maxOrder,
         ClassType* ct, Vec<ClassType*>& visit) {
  if (visit.set_in(ct))
    return 0;
  visit.set_add(ct);
  if (order.get(ct))
    return order.get(ct);
  int i = 0;
  for_fields(field, ct) {
    if (ClassType* fct = dynamic_cast<ClassType*>(field->type)) {
      if (!visit.set_in(fct) && fct->classTag != CLASS_CLASS)
        setOrder(order, maxOrder, fct);
      i = max(i, getOrder(order, maxOrder, fct, visit));
    }
  }
  return i + (ct->classTag != CLASS_CLASS);
}

static void
setOrder(Map<ClassType*,int>& order, int& maxOrder,
         ClassType* ct) {
  if (ct->classTag == CLASS_CLASS || order.get(ct))
    return;
  int i;
  Vec<ClassType*> visit;
  i = getOrder(order, maxOrder, ct, visit);
  order.put(ct, i);
  if (i > maxOrder)
    maxOrder = i;
}

#define STRSUB(x)                               \
  *ch = '\0';                                   \
  sym->cname = stringcat(sym->cname, x, ch+1);  \
  ch = sym->cname

static void legalizeCName(Symbol* sym) {
  for (char* ch = sym->cname; *ch != '\0'; ch++) {
    switch (*ch) {
    case '>': STRSUB("_GREATER_"); break;
    case '<': STRSUB("_LESS_"); break;
    case '=': STRSUB("_EQUAL_"); break;
    case '*': STRSUB("_ASTERISK_"); break;
    case '/': STRSUB("_SLASH_"); break;
    case '%': STRSUB("_PERCENT_"); break;
    case '+': STRSUB("_PLUS_"); break;
    case '-': STRSUB("_HYPHEN_"); break;
    case '^': STRSUB("_CARET_"); break;
    case '&': STRSUB("_AMPERSAND_"); break;
    case '|': STRSUB("_BAR_"); break;
    case '!': STRSUB("_EXCLAMATION_"); break;
    case '#': STRSUB("_POUND_"); break;
    case '?': STRSUB("_QUESTION_"); break;
    case '~': STRSUB("_TILDA_"); break;
    default: break;
    }
  }
}

static void codegen_header(void) {
  ChainHashMap<char*, StringHashFns, int> cnames;
  Vec<TypeSymbol*> typeSymbols;
  Vec<FnSymbol*> fnSymbols;
  Vec<VarSymbol*> varSymbols;

  chpl_main->addPragma("rename _chpl_main");

  // reserved C words that require renaming to compile
  cnames.put("abs", 1);
  cnames.put("exit", 1);
  cnames.put("_init", 1);
  cnames.put("stdin", 1);
  cnames.put("close", 1);
  cnames.put("fwrite", 1);
  cnames.put("fread", 1);
  cnames.put("main", 1);
  cnames.put("open", 1);
  cnames.put("printf", 1);
  cnames.put("quad", 1);
  cnames.put("read", 1);
  cnames.put("sleep", 1);
  cnames.put("stderr", 1);
  cnames.put("stdout", 1);
  cnames.put("write", 1);
  cnames.put("y1", 1); // this is ridiculous...
  cnames.put("log2", 1);
  cnames.put("remove", 1);
  cnames.put("fprintf", 1);
  cnames.put("clone", 1);
  cnames.put("new", 1);
  cnames.put("register", 1);

  forv_Vec(BaseAST, ast, gAsts) {
    if (CallExpr* call = dynamic_cast<CallExpr*>(ast))
      if (FnSymbol* fn = call->isResolved())
        if (fn->hasPragma("c for loop increment"))
          call->remove();

    if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
      Symbol* sym = def->sym;

      if (sym->name == sym->cname)
        sym->cname = stringcpy(sym->name);

      if (char* pragma = sym->hasPragmaPrefix("rename"))
        sym->cname = stringcpy(pragma+7);

      if (VarSymbol* vs = dynamic_cast<VarSymbol*>(ast))
        if (vs->immediate)
          continue;

      legalizeCName(sym);

      // mangle symbol that is neither field nor formal if the symbol's
      // name has already been encountered
      if (!dynamic_cast<ArgSymbol*>(sym) &&
          !dynamic_cast<UnresolvedSymbol*>(sym) &&
          !dynamic_cast<ClassType*>(sym->parentScope->astParent) &&
          cnames.get(sym->cname))
        sym->cname = stringcat("_", sym->cname, "_", intstring(sym->id));

      cnames.put(sym->cname, 1);

      if (TypeSymbol* typeSymbol = dynamic_cast<TypeSymbol*>(sym)) {
        typeSymbols.add(typeSymbol);
      } else if (FnSymbol* fnSymbol = dynamic_cast<FnSymbol*>(sym)) {
        fnSymbols.add(fnSymbol);
      } else if (VarSymbol* varSymbol = dynamic_cast<VarSymbol*>(sym)) {
        if (varSymbol->parentScope->parent == rootScope)
          varSymbols.add(varSymbol);
      }
    }
  }

  qsort(varSymbols.v, varSymbols.n, sizeof(varSymbols.v[0]), compareSymbol);
  qsort(typeSymbols.v, typeSymbols.n, sizeof(typeSymbols.v[0]), compareSymbol);
  qsort(fnSymbols.v, fnSymbols.n, sizeof(fnSymbols.v[0]), compareSymbol);

  fileinfo header;
  openCFile(&header, "_chpl_header", "h");
  FILE* outfile = header.fptr;

  fprintf(outfile, "#include \"stdchpl.h\"\n");
  fprintf(outfile, "\n/*** Class Reference Types ***/\n\n");

  forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {
    typeSymbol->codegenPrototype(outfile);
  }

  // codegen enumerated types
  fprintf(outfile, "\n/*** Enumerated Types ***/\n\n");
  forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {
    if (dynamic_cast<EnumType*>(typeSymbol->type))
      typeSymbol->codegenDef(outfile);
  }

  // order records/unions topologically
  //   (int, int) before (int, (int, int))
  Map<ClassType*,int> order;
  int maxOrder = 0;
  forv_Vec(TypeSymbol, ts, typeSymbols) {
    if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))
      setOrder(order, maxOrder, ct);
  }

  // debug
//   for (int i = 0; i < order.n; i++) {
//     if (order.v[i].key && order.v[i].value) {
//       printf("%d: %s\n", order.v[i].value, order.v[i].key->symbol->name);
//     }
//   }
//   printf("%d\n", maxOrder);

  // codegen records/unions in topological order
  fprintf(outfile, "\n/*** Records and Unions (Hierarchically) ***/\n\n");
  for (int i = 1; i <= maxOrder; i++) {
    forv_Vec(TypeSymbol, ts, typeSymbols) {
      if (ClassType* ct = dynamic_cast<ClassType*>(ts->type))
        if (order.get(ct) == i)
          ts->codegenDef(outfile);
    }
  }

  // codegen remaining types
  fprintf(outfile, "/*** Classes ***/\n\n");
  forv_Vec(TypeSymbol, typeSymbol, typeSymbols) {
    if (ClassType* ct = dynamic_cast<ClassType*>(typeSymbol->type))
      if (ct->classTag != CLASS_CLASS)
        continue;
    if (dynamic_cast<EnumType*>(typeSymbol->type))
      continue;
    typeSymbol->codegenDef(outfile);
  }

  fprintf(outfile, "/*** Function Prototypes ***/\n\n");
  forv_Vec(FnSymbol, fnSymbol, fnSymbols) {
    fnSymbol->codegenPrototype(outfile);
  }

  fprintf(outfile, "\n/*** Global Variables ***/\n\n");
  forv_Vec(VarSymbol, varSymbol, varSymbols) {
    varSymbol->codegenDef(outfile);
  }
  closeCFile(&header);
  beautify(&header);
}

static void
codegen_cid2size(FILE* outfile) {
  fprintf(outfile, "size_t cid2size(_int64 cid) {\n");
  fprintf(outfile, "size_t size;\n");
  fprintf(outfile, "switch(cid) {\n");
  forv_Vec(TypeSymbol, typeSym, gTypes) {
    if (ClassType* ct = dynamic_cast<ClassType*>(typeSym->type)) {
      if (ct->classTag == CLASS_CLASS) {
        fprintf(outfile, "case %d:\n", ct->id);
        fprintf(outfile, "size = sizeof(_");
        ct->symbol->codegen(outfile);
        fprintf(outfile, ");\n");
        fprintf(outfile, "break;\n");
      }
    }
  }
  fprintf(outfile, "default:\n");
  fprintf(outfile, "_printError(\"Bad cid in cid2size\", 0, 0);\n");
  fprintf(outfile, "break;\n");
  fprintf(outfile, "}\n");
  fprintf(outfile, "return size;\n");
  fprintf(outfile, "}\n");
}

static void
codegen_config(FILE* outfile) {
  fprintf(outfile, "void CreateConfigVarTable(void) {\n");
  fprintf(outfile, "initConfigVarTable();\n");

  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) {
      VarSymbol* var = dynamic_cast<VarSymbol*>(def->sym);
      if (var && var->varClass == VAR_CONFIG) {
        fprintf(outfile, "installConfigVar(\"%s\", \"", var->name);
        fprintf(outfile, var->type->symbol->name);
        fprintf(outfile, "\", \"%s\");\n", var->getModule()->name);
      }
    }
  }

  fprintf(outfile, "if (askedToParseArgs()) {\n");
  fprintf(outfile, "  parseConfigArgs();\n");
  fprintf(outfile, "}\n");

  fprintf(outfile, "if (askedToPrintHelpMessage()) {\n");
  fprintf(outfile, "  printHelpTable();\n");
  fprintf(outfile, "  printConfigVarTable();\n");
  fprintf(outfile, "}\n");

  fprintf(outfile, "}\n");
}

void codegen(void) {
  if (no_codegen)
    return;

  fileinfo mainfile;
  openCFile(&mainfile, "_main", "c");
  fprintf(mainfile.fptr, "#include \"_chpl_header.h\"\n");

  codegen_makefile(&mainfile);

  codegen_header();

  codegen_config(mainfile.fptr);

  forv_Vec(ModuleSymbol, currentModule, allModules) {
    mysystem(stringcat("# codegen-ing module", currentModule->name),
             "generating comment for --print-commands option");

    fileinfo modulefile;
    openCFile(&modulefile, currentModule->name, "c");
    currentModule->codegenDef(modulefile.fptr);
    closeCFile(&modulefile);
    fprintf(mainfile.fptr, "#include \"%s%s\"\n", currentModule->name, ".c");
    beautify(&modulefile);
  }

  codegen_cid2size(mainfile.fptr);
  closeCFile(&mainfile);
  beautify(&mainfile);
  makeBinary();
}
<|endoftext|>


<commit_before>#include "command_line_efl.h"

#include <string>
#include <cstring>
#include <sys/types.h>
#include <unistd.h>

#include "content/public/common/content_switches.h"
#include "content/public/common/content_client.h"
#include "cc/base/switches.h"
#include "ui/events/event_switches.h"
#include "extensions/common/switches.h"
#include "ui/gl/gl_switches.h"
#include "url/gurl.h"

int CommandLineEfl::argc_ = 0;
char** CommandLineEfl::argv_ = NULL;
CommandLineEfl::ArgumentVector CommandLineEfl::original_arguments_;

void CommandLineEfl::Init(int argc, char *argv[]) {
  CommandLine::Init(argc, argv);
  argc_ = argc;
  argv_ = argv;

  // Unfortunately chromium modifies application's argument vector.
  // during initialization. This means that chromium after initialization
  // argv will only contain one valid entry, argv[0]. To be able to use
  // user provided arguments after initialization we need to make a copy
  // of them.
  // See: chromium/src/content/common/set_process_title_linux.cc
  for (int i = 0; i < argc; ++i)
    original_arguments_.push_back(std::string(argv[i]));
}

content::MainFunctionParams CommandLineEfl::GetDefaultPortParams() {
  CommandLine* p_command_line = CommandLine::ForCurrentProcess();

  p_command_line->AppendSwitch(switches::kNoSandbox);
  p_command_line->AppendSwitch(switches::kDisablePlugins);
  p_command_line->AppendSwitch(switches::kInProcessGPU);

  p_command_line->AppendSwitch(switches::kUseMobileUserAgent);
  p_command_line->AppendSwitch(switches::kEnableViewportMeta);
#if defined(OS_TIZEN)
  p_command_line->AppendSwitch(switches::kEnableOverscrollNotifications);
  p_command_line->AppendSwitch(switches::kTouchEvents);
  p_command_line->AppendSwitch(switches::kEnablePinch);
  p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationEGLName);
  p_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);
  p_command_line->AppendSwitch(switches::kEnableSpatialNavigation);

  // FIXME(Kapil) Will be removed after permission handling implementation.
  p_command_line->AppendSwitch(switches::kDisableWebSecurity);
#else
  p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationDesktopName);
  p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);
#endif

  p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);
  p_command_line->AppendSwitch(switches::kDisableImplSidePainting);

  //if we use software path we dont need to have next switches
#if defined(OS_TIZEN)
  if (!p_command_line->HasSwitch(switches::kUseSWRenderingPath))
#endif
  {
#warning "[M37] Investigae removed command line switches, are they still needed, do they have a replacement?"
    //p_command_line->AppendSwitch(switches::kForceCompositingMode);
  // [M37] Note: The commit "Temporarily disable zero copy as it causes browser crash during regression"
  // is to deprecate kEnableMapImage option.
  // But it was already deprecated during fixing M37 build as no command line option with such name (see above comment)
  // TODO: remove this commit if it turn out the option is unnecessary
  //Disabling temporarily, as it causes browser crash ID:335 in regression
    //p_command_line->AppendSwitch(cc::switches::kEnableMapImage);
    //p_command_line->AppendSwitch(cc::switches::kEnableImplSidePainting);
    p_command_line->AppendSwitch(switches::kEnableThreadedCompositing);
    p_command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
  }

#warning "[M37] Investigae removed command line switches, are they still needed, do they have a replacement?"
  //p_command_line->AppendSwitch(switches::kAllowWebUICompositing);

  // XXX: Skia benchmarking should be only used for testing,
  // when enabled the following warning is printed to stderr:
  // "Enabling unsafe Skia benchmarking extension."
  // p_command_line->AppendSwitch(switches::kEnableSkiaBenchmarking);

  AppendUserArgs(*p_command_line);

  return content::MainFunctionParams(*p_command_line);
}

void CommandLineEfl::AppendProcessSpecificArgs(CommandLine& command_line) {
  std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType);

  if (process_type == switches::kRendererProcess) {
    command_line.AppendSwitch(switches::kDisablePlugins);
  }
  AppendUserArgs(command_line);
}

void CommandLineEfl::AppendUserArgs(CommandLine& command_line) {
  for (ArgumentVector::const_iterator it = original_arguments_.begin();
       it != original_arguments_.end(); ++it) {
    command_line.AppendSwitch(*it);
  }
}
<commit_msg>Enabling support of viewport meta tag.<commit_after>#include "command_line_efl.h"

#include <string>
#include <cstring>
#include <sys/types.h>
#include <unistd.h>

#include "content/public/common/content_switches.h"
#include "content/public/common/content_client.h"
#include "cc/base/switches.h"
#include "ui/events/event_switches.h"
#include "extensions/common/switches.h"
#include "ui/gl/gl_switches.h"
#include "url/gurl.h"

int CommandLineEfl::argc_ = 0;
char** CommandLineEfl::argv_ = NULL;
CommandLineEfl::ArgumentVector CommandLineEfl::original_arguments_;

void CommandLineEfl::Init(int argc, char *argv[]) {
  CommandLine::Init(argc, argv);
  argc_ = argc;
  argv_ = argv;

  // Unfortunately chromium modifies application's argument vector.
  // during initialization. This means that chromium after initialization
  // argv will only contain one valid entry, argv[0]. To be able to use
  // user provided arguments after initialization we need to make a copy
  // of them.
  // See: chromium/src/content/common/set_process_title_linux.cc
  for (int i = 0; i < argc; ++i)
    original_arguments_.push_back(std::string(argv[i]));
}

content::MainFunctionParams CommandLineEfl::GetDefaultPortParams() {
  CommandLine* p_command_line = CommandLine::ForCurrentProcess();

  p_command_line->AppendSwitch(switches::kNoSandbox);
  p_command_line->AppendSwitch(switches::kDisablePlugins);
  p_command_line->AppendSwitch(switches::kInProcessGPU);

  p_command_line->AppendSwitch(switches::kUseMobileUserAgent);
  p_command_line->AppendSwitch(switches::kEnableViewportMeta);
#if defined(OS_TIZEN)
  p_command_line->AppendSwitch(switches::kEnableOverscrollNotifications);
  p_command_line->AppendSwitch(switches::kTouchEvents);
  p_command_line->AppendSwitch(switches::kEnablePinch);
  p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationEGLName);
  p_command_line->AppendSwitch(switches::kEnableGestureTapHighlight);
  p_command_line->AppendSwitch(switches::kEnableSpatialNavigation);
  p_command_line->AppendSwitch(switches::kMainFrameResizesAreOrientationChanges);

  // FIXME(Kapil) Will be removed after permission handling implementation.
  p_command_line->AppendSwitch(switches::kDisableWebSecurity);
#else
  p_command_line->AppendSwitchASCII(switches::kUseGL, gfx::kGLImplementationDesktopName);
  p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);
#endif

  p_command_line->AppendSwitch(switches::kDisableDelegatedRenderer);
  p_command_line->AppendSwitch(switches::kDisableImplSidePainting);

  //if we use software path we dont need to have next switches
#if defined(OS_TIZEN)
  if (!p_command_line->HasSwitch(switches::kUseSWRenderingPath))
#endif
  {
#warning "[M37] Investigae removed command line switches, are they still needed, do they have a replacement?"
    //p_command_line->AppendSwitch(switches::kForceCompositingMode);
  // [M37] Note: The commit "Temporarily disable zero copy as it causes browser crash during regression"
  // is to deprecate kEnableMapImage option.
  // But it was already deprecated during fixing M37 build as no command line option with such name (see above comment)
  // TODO: remove this commit if it turn out the option is unnecessary
  //Disabling temporarily, as it causes browser crash ID:335 in regression
    //p_command_line->AppendSwitch(cc::switches::kEnableMapImage);
    //p_command_line->AppendSwitch(cc::switches::kEnableImplSidePainting);
    p_command_line->AppendSwitch(switches::kEnableThreadedCompositing);
    p_command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
  }

#warning "[M37] Investigae removed command line switches, are they still needed, do they have a replacement?"
  //p_command_line->AppendSwitch(switches::kAllowWebUICompositing);

  // XXX: Skia benchmarking should be only used for testing,
  // when enabled the following warning is printed to stderr:
  // "Enabling unsafe Skia benchmarking extension."
  // p_command_line->AppendSwitch(switches::kEnableSkiaBenchmarking);

  AppendUserArgs(*p_command_line);

  return content::MainFunctionParams(*p_command_line);
}

void CommandLineEfl::AppendProcessSpecificArgs(CommandLine& command_line) {
  std::string process_type = command_line.GetSwitchValueASCII(switches::kProcessType);

  if (process_type == switches::kRendererProcess) {
    command_line.AppendSwitch(switches::kDisablePlugins);
  }
  AppendUserArgs(command_line);
}

void CommandLineEfl::AppendUserArgs(CommandLine& command_line) {
  for (ArgumentVector::const_iterator it = original_arguments_.begin();
       it != original_arguments_.end(); ++it) {
    command_line.AppendSwitch(*it);
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_Memory_AnyVariantValue_inl_
#define _Stroika_Foundation_Memory_AnyVariantValue_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../Debug/Assertions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Memory {

            struct  AnyVariantValue::IRep_ {
                virtual ~IRep_ () {}
                virtual const type_info&    GetType () const    =   0;
            };

            template    <typename T>
            struct  AnyVariantValue::TIRep_ : public IRep_ {
                T   fValue;
                TIRep_ (const T& from):
                    fValue (from)
                {}
                virtual const type_info&    GetType () const override
                {
                    return typeid (T);
                }
            };

            /*
             ********************************************************************************
             ******************************* AnyVariantValue ********************************
             ********************************************************************************
             */
            inline  AnyVariantValue::AnyVariantValue (AnyVariantValue&& from)
                : fVal_ (move (from.fVal_))
            {
            }
            template    <typename   T>
            inline  AnyVariantValue::AnyVariantValue (T val)
                : fVal_ (make_shared<TIRep_<T>> (val))
            {
            }
            inline  const type_info&  AnyVariantValue::GetType () const
            {
                if (fVal_.get () == nullptr) {
                    return typeid (void);
                }
                return fVal_->GetType ();
            }
            inline  bool    AnyVariantValue::empty () const
            {
                return fVal_.get () == nullptr;
            }
            inline  void    AnyVariantValue::clear ()
            {
                fVal_.reset ();
            }
            template    <typename   RETURNTYPE>
            inline  RETURNTYPE  AnyVariantValue::As () const
            {
                Require (typeid (RETURNTYPE) == GetType ());
                Require (typeid (RETURNTYPE) != typeid (void));
                AssertNotNull (fVal_.get ());
                // Could use dynamic_cast but this should be equally safe (cuz of assert above) and more
                // efficient
                const TIRep_<RETURNTYPE>*   t   =   reinterpret_cast<TIRep_<RETURNTYPE>*> (fVal_.get ());
                return t->fValue;
            }
            template    <typename   RETURNTYPE>
            inline  Optional<RETURNTYPE>  AnyVariantValue::IfAs () const
            {
                return empty () ? Optional<RETURNTYPE> : As<RETURNTYPE> ();
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Memory_AnyVariantValue_inl_*/
<commit_msg>fixed typo<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_Memory_AnyVariantValue_inl_
#define _Stroika_Foundation_Memory_AnyVariantValue_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    "../Debug/Assertions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Memory {

            struct  AnyVariantValue::IRep_ {
                virtual ~IRep_ () {}
                virtual const type_info&    GetType () const    =   0;
            };

            template    <typename T>
            struct  AnyVariantValue::TIRep_ : public IRep_ {
                T   fValue;
                TIRep_ (const T& from):
                    fValue (from)
                {}
                virtual const type_info&    GetType () const override
                {
                    return typeid (T);
                }
            };

            /*
             ********************************************************************************
             ******************************* AnyVariantValue ********************************
             ********************************************************************************
             */
            inline  AnyVariantValue::AnyVariantValue (AnyVariantValue&& from)
                : fVal_ (move (from.fVal_))
            {
            }
            template    <typename   T>
            inline  AnyVariantValue::AnyVariantValue (T val)
                : fVal_ (make_shared<TIRep_<T>> (val))
            {
            }
            inline  const type_info&  AnyVariantValue::GetType () const
            {
                if (fVal_.get () == nullptr) {
                    return typeid (void);
                }
                return fVal_->GetType ();
            }
            inline  bool    AnyVariantValue::empty () const
            {
                return fVal_.get () == nullptr;
            }
            inline  void    AnyVariantValue::clear ()
            {
                fVal_.reset ();
            }
            template    <typename   RETURNTYPE>
            inline  RETURNTYPE  AnyVariantValue::As () const
            {
                Require (typeid (RETURNTYPE) == GetType ());
                Require (typeid (RETURNTYPE) != typeid (void));
                AssertNotNull (fVal_.get ());
                // Could use dynamic_cast but this should be equally safe (cuz of assert above) and more
                // efficient
                const TIRep_<RETURNTYPE>*   t   =   reinterpret_cast<TIRep_<RETURNTYPE>*> (fVal_.get ());
                return t->fValue;
            }
            template    <typename   RETURNTYPE>
            inline  Optional<RETURNTYPE>  AnyVariantValue::IfAs () const
            {
                return empty () ? Optional<RETURNTYPE> {} : As<RETURNTYPE> ();
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Memory_AnyVariantValue_inl_*/
<|endoftext|>