summaryrefslogtreecommitdiff
path: root/Source/Core/Core/Boot/Boot_ELF.cpp
blob: 9130fafdfc105be3c21fec79c987c2446eb0a87f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2008 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.

#include <memory>

#include "Common/FileUtil.h"
#include "Common/Swap.h"
#include "Core/Boot/Boot.h"
#include "Core/Boot/ElfReader.h"
#include "Core/HLE/HLE.h"
#include "Core/PowerPC/PowerPC.h"

bool CBoot::IsElfWii(const std::string& filename)
{
  /* We already check if filename existed before we called this function, so
     there is no need for another check, just read the file right away */

  size_t filesize = File::GetSize(filename);
  auto elf = std::make_unique<u8[]>(filesize);

  {
    File::IOFile f(filename, "rb");
    f.ReadBytes(elf.get(), filesize);
  }

  // Use the same method as the DOL loader uses: search for mfspr from HID4,
  // which should only be used in Wii ELFs.
  //
  // Likely to have some false positives/negatives, patches implementing a
  // better heuristic are welcome.

  // Swap these once, instead of swapping every word in the file.
  u32 HID4_pattern = Common::swap32(0x7c13fba6);
  u32 HID4_mask = Common::swap32(0xfc1fffff);
  ElfReader reader(elf.get());

  for (int i = 0; i < reader.GetNumSegments(); ++i)
  {
    if (reader.IsCodeSegment(i))
    {
      u32* code = (u32*)reader.GetSegmentPtr(i);
      for (u32 j = 0; j < reader.GetSegmentSize(i) / sizeof(u32); ++j)
      {
        if ((code[j] & HID4_mask) == HID4_pattern)
          return true;
      }
    }
  }

  return false;
}

bool CBoot::Boot_ELF(const std::string& filename)
{
  // Read ELF from file
  size_t filesize = File::GetSize(filename);
  auto elf = std::make_unique<u8[]>(filesize);

  {
    File::IOFile f(filename, "rb");
    f.ReadBytes(elf.get(), filesize);
  }

  // Load ELF into GameCube Memory
  ElfReader reader(elf.get());
  if (!reader.LoadIntoMemory())
    return false;

  const bool is_wii = IsElfWii(filename);
  if (is_wii)
    HID4.SBE = 1;
  SetupBAT(is_wii);

  if (!reader.LoadSymbols())
  {
    if (LoadMapFromFilename())
      HLE::PatchFunctions();
  }
  else
  {
    HLE::PatchFunctions();
  }

  PC = reader.GetEntryPoint();

  return true;
}