Osdev: Até onde dá para usar c++
Estou desenvolvendo um kernel chamado FKernel.
Para uso desktop em código x86_64.
E lendo sobre algumas linguagens como Rust, C, C++, Zig …
Decidi fazer uma combinação de:
- Linguagens de Programação:
- C
- C++
- Linguagem de montagem:
- Nasm
Obviamente alguns podem estranhar já que eu propositalmente ignorei Rust, e aquelas que são considerados “memory-safe”.
Porque não usar linguagens memory-safe?
Pro Tip: Não existe linguagem memory-safe em baixo nível. Para programar um kernel ou similar, você vai depender do unsafe então nem tenta.
Se for para ter que lidar com sintaxes estranhas para programar um kernel, eu prefiro seguir no bom e velho C/C++.
Também não quero fazer um overflow de logs de um compilador super-nanny para chegar a um subset daquilo que eu queria no meu código.
E porque C++?
Muito tempo atrás Linus Torvalds havia tentado escrever um kernel com a versão de sua época.
C++ leads to really, really bad design choices. You invariably start using the STL, boost, and other total and utter crap…
Ok, podemos concordar em algumas partes mas, isso não seria inevitavelmente ruim.
Sim, C++ tem um monte de coisa, mas fugiria do ponto principal que é C++ dá contratos que structs sozinhas dificilmente conseguem.
Pegue um exemplo do SerenityOS
static ErrorOr<NonnullOwnPtr<KBuffer>> try_create_with_size(StringView name,
size_t size,
Memory::Region::Access access = Memory::Region::Access::ReadWrite,
AllocationStrategy strategy = AllocationStrategy::Reserve){
auto rounded_size = TRY(Memory::page_round_up(size));
auto region = TRY(MM.allocate_kernel_region(rounded_size, name, access, strategy));
return TRY(adopt_nonnull_own_or_enomem(new (nothrow) KBuffer { size, move(region) }));
}
Consegue entender o que esse código faz? Todo esse contrato engloba em poucas linhas
Essa função try_create_with_size serve para criar um buffer de memória no kernel de um tamanho específico e lidar com possíveis erros de forma segura.
Para termos o equivalente exato em C garantindo a mesma segurança seria necessária escrever dessa forma.
int try_create_with_size(const char* name,
size_t size,
MemoryAccess access,
AllocationStrategy strategy,
KBuffer** out_buffer) {
if (!out_buffer) return -1;
size_t rounded_size;
int rc = page_round_up(size, &rounded_size);
if (rc != 0) return rc;
MemoryRegion* region;
rc = allocate_kernel_region(rounded_size, name, access, strategy, ®ion);
if (rc != 0) return rc;
KBuffer* buffer = malloc(sizeof(KBuffer));
if (!buffer) {
free(region->addr);
free(region);
return -ENOMEM;
}
buffer->size = size;
buffer->region = region;
*out_buffer = buffer;
return 0; // sucesso
}
Ok, tivemos uma disparidade no tamanho, mas isso não significa nada no geral.
Meu ponto defendido é que precisamos fazer muito mais código, que vai ser muito mais performático mas que vai resultar em um resultado muito menos seguro, e muito menos reusável no geral.
Não ironicamente, muitos empresas incluindo a própria Apple usam o C++ em seus kernels.
Mas não precisa ser o c++ inteiro e sim um subset chamado embedded c++.
Implementação do IOKit
/*
* Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#ifndef _IOKIT_IONVRAMCONTROLLER_H
#define _IOKIT_IONVRAMCONTROLLER_H
#include <IOKit/IOService.h>
class IONVRAMController : public IOService
{
OSDeclareAbstractStructors(IONVRAMController);
public:
virtual void registerService(IOOptionBits options = 0) APPLE_KEXT_OVERRIDE;
virtual void sync(void);
virtual IOReturn select(uint32_t bank);
virtual IOReturn eraseBank(void);
virtual IOReturn read(IOByteCount offset, UInt8 *buffer,
IOByteCount length) = 0;
virtual IOReturn write(IOByteCount offset, UInt8 *buffer,
IOByteCount length) = 0;
};
#endif /* !_IOKIT_IONVRAMCONTROLLER_H */
Quem diria.
Se fossemos falar do C++ antes da versão 17, eu até concordaria mas após a versão 17 muita coisa mudou.
E veja que o IOKit é implementado na forma Embedded C++.
Mas, e como em tudo há um mas, há em real,o ponto da STL que invariavelmente você vai acabar usando ou não.
Realmente preciso do STL?
No fringir dos ovos há um outro superset de C++ chamado c++ ortodoxo jamais o use, sério.
Uma das soluções que o FKernel e o SerenityOS fazem é criar sua própria STL.
O SerenityOS com sua Abstraction Kit. E o FKernel com seu LibFK.
Usar uma STL não é de todo mal, há diversos efeitos, como otimização em cascata.
Genericos e todo resto.
E no fim?
No fim, depende de você.
Se você está desenvolvendo um app para desktop.
Eu sugeriria:
Para baixo nível certamente eu sugeriria:
Mas em kernel estou muito mais satisfeito com minha escolha do que usar C puro.
Não que eu não use C obviamente, por baixo dos panos da LibFK eu implementei uma LibC bem simples com funções que eu teria que usar dentro do FKernel para algumas funções da LibFK.
Mas enfim, se uma linguagem que você prefere usar por algum motivo de design ou simplesmente por ser a que você sabe, simplesmente use.
Desde que não seja usar algo interpretado para fazer baixo nível, tá valendo tudo.