KernOS
utilities.h
Go to the documentation of this file.
1 #ifndef KERNOS_UTILITIES_H
2 #define KERNOS_UTILITIES_H
3 
4 #include <common.h>
5 #include <kprintf.h>
6 
7 size_t Strlen(const char *Str);
8 
9 namespace
10 {
11  inline void cli() // disable maskable interrupt
12  {
13  asm volatile (
14  "cli"
15  : // no output
16  : // no input
17  : "memory"
18  );
19  }
20 
21  inline void sti() // enable maskable interrupt
22  {
23  asm volatile (
24  "sti"
25  : // no output
26  : // no input
27  : "memory" // memory barrier
28  );
29 
30  }
31 
32  inline uint32_t FlagsRegister()
33  {
34  uint32_t Flags;
35  asm volatile (
36  "pushf\n"
37  "pop %0\n"
38  : "=rm"(Flags) // output
39  : // no input
40  :"memory" // memory barrier
41  );
42  return Flags;
43  }
44 
45  inline void out8(uint16_t Port, uint8_t Value)
46  {
47  asm volatile (
48  "outb %0, %1"
49  : // No output
50  : "a"(Value), // Input 0: "a" constraint is to place Value in eax before asm command
51  "Nd"(Port) // 1: "Nd" constraint is to place Port as one byte literal (without using register)
52  );
53  }
54 
55  inline uint8_t in8(uint16_t Port)
56  {
57  uint8_t Value;
58 
59  asm volatile (
60  "inb %1, %0"
61  : "=a"(Value) // Output 0: write byte to Value
62  : "Nd"(Port) // Input 1: "Nd" constraint is to place Port as one byte literal (without using register)
63  );
64 
65  return Value;
66  }
67 
68  [[noreturn]] inline void Hang()
69  {
70  asm volatile (
71  "cli\n" // disable interrupt
72  "hlt\n" // halt processor when interrupt occurs, only non-maskable interrupt, NMI possible after cli
73  );
74 
75  for (;;) { // to prevent [[noreturn]] warning, and in case NMI occur
76  }
77  }
78 
79  template<uint8_t N>
80  inline constexpr uint32_t DWord()
81  {
82  return (1 << N);
83  }
84 
85  #define GHETTO_GET_CR(x) uint32_t Local_##x; \
86  asm volatile \
87  ( \
88  "mov %%"#x", %%eax\n" \
89  "mov %%eax, %0\n" \
90  : "=m"(Local_##x) \
91  : \
92  : "%eax" \
93  );
94 
95  inline uint32_t ReadCR0()
96  {
97  GHETTO_GET_CR(cr0)
98  return Local_cr0;
99  }
100 
101  inline uint32_t ReadCR2()
102  {
103  GHETTO_GET_CR(cr2)
104  return Local_cr2;
105  }
106 
107  inline uint32_t ReadCR3()
108  {
109  GHETTO_GET_CR(cr3)
110  return Local_cr3;
111  }
112 
113  inline uint32_t ReadCR4()
114  {
115  GHETTO_GET_CR(cr4)
116  return Local_cr4;
117  }
118 
119  inline void kassert (bool Condition, const char *Str = nullptr)
120  {
121  if (!Condition) {
122  if (Str)
123  kprintf(Str);
124  Hang();
125  }
126  }
127 
128  [[noreturn]] inline void kpanic (const char *Str = nullptr)
129  {
130  kprintf(Str);
131  Hang();
132  }
133 } // unnamed namespace
134 
135 #endif //KERNOS_UTILITIES_H
#define GHETTO_GET_CR(x)
Definition: utilities.h:85
void kprintf(const char *Str)
Prints string to display.
Definition: kprintf.cpp:13
size_t Strlen(const char *Str)
Count number of characters in string.
Definition: utilities.cpp:7