Writing a toy OS in C #

image

Introduction


Hello, habrasociety! I don’t know if this topic will be useful to anyone, but I hope that you will learn something new here. The purpose of this article is to acquaint habrayuzers with the COSMOS project and show how you can implement your own OS tailored to your needs. Who cares - I ask for a cat.

Meet COSMOS

Here's what Wikipedia tells us:
Cosmos is a back acronym for C # Open Source Managed Operating System (rus. "Managed open source operating system in C #"). Cosmos does not currently seek to become a full-fledged operating system, but rather a set of tools that allow other developers to easily and simply create their own operating systems, or, as one of the project managers said, act as a “Lego-type operating system”. It also functions as an abstraction layer, hiding a significant part of the work of internal hardware.
Cosmos is a constructor that allows you to completely distract from low-level programming and write in pure C #.

What do we need?

First of all, we need Microsoft Visual Studio 2010, preferably Pro. If you are using the Express version, you will need to install Microsoft Visual Studio Shell. Download all this stuff:

We also need to download and install the Cosmos User Kit itself . In addition, we need any virtual machine to test our operating system. Personally, I use QEMU and Virtual Box.

Start coding


Uncover Visual Studio, click "Create a project ..." and we see a window like this:
Select Cosmos C # Library and click OK, after that a window with
standard code
using System;
using System.Collections.Generic;
using System.Text;
using Sys = Cosmos.System;
namespace CSharpKernel1
{
    public class Kernel : Sys.Kernel
    {
        protected override void BeforeRun()
        {
            Console.WriteLine("Cosmos booted successfully. Type a line of text to get it echoed back.");
        }
        protected override void Run()
        {
            Console.Write("Input: ");
            var input = Console.ReadLine();
            Console.Write("Text typed: ");
            Console.WriteLine(input);
        }
    }
}
Here we will write the logic of our operating system. For your OS to work correctly, you need to select the Release configuration in each project! Otherwise, it simply will not work.
We do not need a standard code, so feel free to cut it! Now, let's get down to writing code directly. I almost forgot to mention that the code can use any objects of the .NET Framework libraries that Cosmos supports (either by translating the object into machine code, or each of its parts). It can also call any library built into Cosmos. To get started, let's figure out the Kernel class.
Kernel
using System;
using System.Collections.Generic;
using System.Text;
using Sys = Cosmos.System;
namespace CSharpKernel1
{
    public class Kernel : Sys.Kernel
    {
        protected override void BeforeRun() /*Этот метод вызывается самым первым и выполняется только один раз. Его удобно использовать для инициализации компонентов. */
        {
            Console.ForegroundColor = ConsoleColor.Green; 
            //Цвет текста - зеленый
            Console.WriteLine("Welcome to HabrOS! Type \"help\" and then press \"ENTER\" to get some help.");
            //Выводим на экран приветствие
            Console.ForegroundColor = ConsoleColor.White;
            //Цвет текста - белый, как и по умолчанию. ВНИМАНИЕ! Метод Console.ResetColor() НЕ будет работать!
        }
        protected override void Run() //Данный метод вызывается постоянно, в нем мы разместим логику.
        {
        }
    }
}

This, so to speak, is the framework of our OS. Now let's add the CommandPrompt class to the project, which will be responsible for entering and executing commands.
CommandPrompt
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ScorpionOS
{
    class CommandPrompt
    {
        public static void Read() { //Этот метод будет считывать с клавиатуры вводимый юзером текст
            Console.Write("->");
            String ln = Console.ReadLine(); //Считываем введенный текст и записываем его в переменную ln
            switch (ln)
            {
                case "help": //Помощь
                    Console.ForegroundColor = ConsoleColor.Cyan; //Цвет текста - бирюзовый
                    Console.WriteLine("To run a program, type name of program and press enter.");
                    Console.WriteLine("The following commands are available:");
                    Console.WriteLine("help - get help\nabout - information about the operating system\nshutdown - power off the computer\nreboot - reboot the computer");
                    Console.ForegroundColor = ConsoleColor.White; //Не забываем вернуть стандартный цвет
                    break;
                case "about": //Об ОС
                    Console.WriteLine("HabrOS ver. 0.01 beta.");
                    break;
                case "shutdown": //Выключение компьютера
                    Cosmos.Sys.Plugs.Deboot.ShutDown();
                    break;
                case "reboot": //Перезагрузка
                    Cosmos.Sys.Plugs.Deboot.Reboot();
                    break;
                default: //Любая другая введенная строка
                    Console.ForegroundColor = ConsoleColor.Red; //Думаю, здесь уже все понятно
                    Console.WriteLine("ERROR: Command not found");
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
            }
        }
    }
}

For this class to work correctly, we need to add a link to the Cosmos.Sys.Plugs.dll library. It is located here: C: \ cosmosUserKit_install_folder \\ Build \ VSIP.
Well, just a little remains: we add a call to the CommandPrompt.Read () method to the Run () method of the Kernel class:
Run ()
protected override void Run()
        {
            CommandPrompt.Read(); //Считываем введенные с клавиатуры данные
        }

That's all. We have implemented the simplest OS commands, now it remains only to compile our project and run it on a virtual machine.
To do this, click Build-> Build Solution, save our project and open Visual Studio 2010 Shell.
We click on create a project and see this window: Create a Cosmos Project, and in the References add a link to the .dll - the file resulting from the construction of the project. This dll is located in the folder of our first project \ bin \ debug. IMPORTANT! If you do not have VMWarePlayer or Workstation installed, then open the project properties and select ISO Image, as shown below:image
After that, we also click to build the solution, wait, since the construction takes a relatively long time, and after successful construction, close Visual Studio Shell, without forgetting to save the project. As a result, in the folder of the second project \ bin \ debug we find the .iso file. It can be written to disk or to a USB flash drive and load our OS on real hardware. You can run our OS in a virtual machine and enjoy the result :)

Total


That's all! I hope you learn something new by reading this article. I will try to answer all your questions in the comments if something is not clear.

Also popular now: