From fd72f658c0f97504cb93ebb0c1310c351d9cdb22 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 21 Nov 2019 14:40:12 -0500 Subject: [PATCH 1/9] Fix SQL command when creating magiskdb --- native/jni/core/db.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/jni/core/db.cpp b/native/jni/core/db.cpp index ce3479f7b..c644e0b7e 100644 --- a/native/jni/core/db.cpp +++ b/native/jni/core/db.cpp @@ -138,7 +138,7 @@ static char *open_and_init_db(sqlite3 *&db) { upgrade = true; } if (ver < 10) { - sqlite3_exec(db, "DROP TABLE logs", nullptr, nullptr, &err); + sqlite3_exec(db, "DROP TABLE IF EXISTS logs", nullptr, nullptr, &err); err_ret(err); ver = 10; upgrade = true; From bffdedddb4446088004b8e0af6649988498baf9a Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Thu, 21 Nov 2019 17:43:31 -0500 Subject: [PATCH 2/9] Fix fwrite/fread params --- native/jni/utils/cpio.cpp | 4 ++-- native/jni/utils/include/stream.h | 2 -- native/jni/utils/stream.cpp | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/native/jni/utils/cpio.cpp b/native/jni/utils/cpio.cpp index 76e4ccb5e..a62754f58 100644 --- a/native/jni/utils/cpio.cpp +++ b/native/jni/utils/cpio.cpp @@ -109,7 +109,7 @@ bool cpio::exists(const char *name) { return entries.count(name) != 0; } -#define do_out(buf, len) pos += fwrite(buf, len, 1, out); +#define do_out(buf, len) pos += fwrite(buf, 1, len, out); #define out_align() do_out(zeros, align_off(pos, 4)) void cpio::dump(FILE *out) { size_t pos = 0; @@ -142,7 +142,7 @@ void cpio::dump(FILE *out) { } // Write trailer sprintf(header, "070701%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x", - inode++, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 11, 0); + inode++, 0755, 0, 0, 1, 0, 0, 0, 0, 0, 0, 11, 0); do_out(header, 110); do_out("TRAILER!!!\0", 11); out_align(); diff --git a/native/jni/utils/include/stream.h b/native/jni/utils/include/stream.h index eaed8a144..b46d91d6e 100644 --- a/native/jni/utils/include/stream.h +++ b/native/jni/utils/include/stream.h @@ -4,8 +4,6 @@ #include #include -// #include - class stream; FILE *open_stream(stream *strm); diff --git a/native/jni/utils/stream.cpp b/native/jni/utils/stream.cpp index 607b4d026..a28734589 100644 --- a/native/jni/utils/stream.cpp +++ b/native/jni/utils/stream.cpp @@ -51,11 +51,11 @@ int stream::close() { } int filter_stream::read(void *buf, size_t len) { - return fread(buf, len, 1, fp); + return fread(buf, 1, len, fp); } int filter_stream::write(const void *buf, size_t len) { - return fwrite(buf, len, 1, fp); + return fwrite(buf, 1, len, fp); } int filter_stream::close() { From 474cc7d56dbabe97efc983478e4342aca6d3fde6 Mon Sep 17 00:00:00 2001 From: Lennoard Date: Wed, 20 Nov 2019 15:34:16 -0300 Subject: [PATCH 3/9] Updated pt-BR strings (based on current values/strings.xml) --- app/src/main/res/values-pt-rBR/strings.xml | 130 +++++++++++++-------- 1 file changed, 83 insertions(+), 47 deletions(-) diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 2ed94706b..7ec7cd11d 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -8,23 +8,26 @@ Registro Configurações Instalar + Versão não suportada do Magisk + Esta versão do Magisk Manager não suporta versões do Magisk menores que %1$s.\n\nO aplicativo se comportará como se nenhum Magisk estivesse instalado, por favor, atualize o Magisk o mais rápido possível. Magisk não está instalado - Verificando por atualizações… - Canal de Atualização Inválido - Verificar SafetyNet - Verificando status de SafetyNet… - SafetyNet Verificado Com Sucesso - Erro de SafetyNet API + Procurando por atualizações… + Canal de Atualizações Inválido + Toque para iniciar a verificação do SafetyNet + Verificando o status do SafetyNet… + SafetyNet verificado com sucesso + Erro na API do SafetyNet A resposta é inválida - Magisk atualizado - Gerenciador Magisk atualizado + Magisk está atualizado + Magisk Manager está atualizado Configurações Avançadas Manter encriptação forçada Manter AVB 2.0/dm-verity + Modo Recuperação Instalado: %1$s - Último: %1$s + Mais recente: %1$s Desinstalar Desinstalar o Magisk Todos os módulos serão desativados/removidos. O acesso Root será removido, e seus dados provavelmente serão criptografados se já não estiverem. @@ -62,45 +65,70 @@ Registro de mudanças + + Atualizações do Magisk + Notificações de Progresso + Download completo + Erro ao baixar o aquivo + Mostrar na pasta + Mostrar arquivo + Atualização do Magisk Disponível! + Atualização do Magisk Manager Disponível! + + + Toque para baixar e instalar + Apenas baixar o zip + Instalação direta (Recomendado) + Instalar no Slot Inativo (Após o OTA) + Seu dispositivo será FORÇADO a inicializar no slot inativo atual após uma reinicialização!\nSó use esta opção após a conclusão do OTA.\nContinuar? + Selecione o Método + Configuração Adicional + Selecionar e Patchear um Arquivo + Selecione uma imagem raw (*.img) ou um arquivo tar do ODIN (*.tar) + Reiniciando em 5 segundos… + Instalar %1$s - Instalar %1$s agora? + Você quer instalar %1$s agora? Baixar Reiniciar - Nova Atualização do Magisk Disponível! - Reinicie para aplicar as configurações + Reinicie para aplicar as mudanças Notas de lançamento - Cache de repositório limpo - Nova Atualização do Magisk Manager Disponível! - Toque para baixar e instalar - DTBO foi emendado! - Magisk Manager emendou dtbo.img, reinicie - Atualizações do Magisk - Flasheando - Ocultando Magisk Manager… - Falha ao ocultar Magisk Manager… - Baixar Zip Apenas - Instalação Direta (Recomendado) - Instalar no Slot Inativo (Após OTA) - Selecionar Método + Cache do repositório limpo + DTBO foi patcheado! + Magisk Manager foi patcheado para o dtbo.img. Por favor, reinicie. + Flasheando… + Pronto! + Falha + Ocultando o Magisk Manager… + Falha ao ocultar o Magisk Manager. + Nenhum aplicativo encontrado para abrir o link + Aviso Completar Desinstalação Restaurar Imagens - Restauração concluída! - Backup original não existe! + Restaurando… + Restauração completa! + Backup stock não existe! Baixar Código Proprietário - Magisk Manager é FOSS, que não contém o código proprietário da API SafetyNet da Google.\n\nPermitir ao Magisk Manager baixar uma extensão (que contém a GoogleApiClient) para a verificação SafetyNet? - Erro ao baixar arquivo + Magisk Manager é um software livre e de código aberto (FOSS) e não contém código proprietário da API SafetyNet do Google.\n\Permitir o Magisk Manager baixar uma extensão (contém GoogleApiClient) para verificações do SafetyNet? + Configuração falhou + Requer configuração adicional + Seu dispositivo precisa de uma configuração adicional para que o Magisk funcione corretamente. Ele fará o download do zip de instalação do Magisk. Deseja continuar agora? + Executando a configuração do ambiente… + Autenticar Geral Tema Escuro - Ativar tema escuro - Limpar Cache de Repositório - Limpar as informações no cache para repositórios onlines, força o app a reatualizar online + Ativar o tema escuro + Caminho de download + Arquivos serão salvos em %1$s + Limpar cache do repositório + Limpar as informações em cache para repositórios online. Isso força o aplicativo a atualizar online Ocultar Magisk Manager - Reempacotar Magisk Manager com nome de pacote aleatório + Reempacotar o Magisk Manager com nome de pacote e nome do app aleatórios Restaurar Magisk Manager - Restaurar Magisk Manager com pacote original + Restaurar o Magisk Manager com o nome de pacote e nome do app originais Idioma (Padrão do Sistema) Configurações de Atualizações @@ -117,9 +145,13 @@ Hosts sem sistema Suporte de hosts sem sistema para apps de Adblock - Apps e ADB - Apps apenas - ADB apenas + Digite o nome do app desejado + Novo nome + O aplicativo será reempacotado para esse nome + Formato inválido + Aplicativos e ADB + Somente aplicativos + Somente ADB Desativado 10 segundos 15 segundos @@ -132,8 +164,11 @@ Tempo Limite de Solicitação Notificação de Superusuário %1$d segundos - Reautenticar após atualizar - Reautenticar permissões de superusuário após um app atualizar + Reautenticar após uma atualização + Reautenticar permissões de superusuário após a atualização de um aplicativo + Habilitar autenticação biométrica + Usar autenticação biométrica para permitir solicitações de superusuário + Dispositivo não suportado ou nenhuma configuração biométrica está ativada Modo de Multiusuário Proprietário do Dispositivo Apenas @@ -143,18 +178,19 @@ Apenas proprietário pode gerenciar acesso root e receber expedições de solicitações Cada usuário tem suas próprias regras root separadas - Montar Modo de Espaço de Nome - Espaço de Nome Global - Espaço de Nome Herdado - Espaço de Nome Isolado - Todas as sessões root usam montagem de espaço de nome global - As sessões root herdarão espaço de nome de seu solicitante - Cada sessão root terá seu próprio espaço de nome isolado + Modo de montar o namespace + Namespace Global + Herdar Namespace + Namespace isolado + Todas as sessões de root usam a montagem de namespace global + As sessões de root herdarão o namespace do seu solicitante + Cada sessão root terá seu próprio namespace isolado + Erro ao criar pasta. Ele deve estar acessível no diretório raiz do armazenamento e não deve ser um arquivo. Solicitação de Superusuário Negar - Solicitar + Perguntar Conceder Concede acesso total ao seu dispositivo.\nNegue se você não tem certeza! Sempre From 5bee1c56a9630352d022a8307457bbd0d43630de Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Fri, 22 Nov 2019 03:01:49 -0500 Subject: [PATCH 4/9] Properly use RAII to reduce complication --- native/jni/magiskboot/bootimg.cpp | 7 +- native/jni/magiskboot/compress.cpp | 107 +++++++++++------------------ native/jni/utils/include/stream.h | 4 +- native/jni/utils/stream.cpp | 13 +--- 4 files changed, 48 insertions(+), 83 deletions(-) diff --git a/native/jni/magiskboot/bootimg.cpp b/native/jni/magiskboot/bootimg.cpp index 1e8d3bffe..279a6a008 100644 --- a/native/jni/magiskboot/bootimg.cpp +++ b/native/jni/magiskboot/bootimg.cpp @@ -28,9 +28,10 @@ static void decompress(format_t type, int fd, const void *in, size_t size) { static int64_t compress(format_t type, int fd, const void *in, size_t size) { auto prev = lseek(fd, 0, SEEK_CUR); - unique_ptr ptr(get_encoder(type, open_stream(fd))); - ptr->write(in, size); - ptr->close(); + { + unique_ptr ptr(get_encoder(type, open_stream(fd))); + ptr->write(in, size); + } auto now = lseek(fd, 0, SEEK_CUR); return now - prev; } diff --git a/native/jni/magiskboot/compress.cpp b/native/jni/magiskboot/compress.cpp index 0694766ba..232dfbbe8 100644 --- a/native/jni/magiskboot/compress.cpp +++ b/native/jni/magiskboot/compress.cpp @@ -22,7 +22,6 @@ using namespace std; #define bwrite filter_stream::write -#define bclose filter_stream::close constexpr size_t CHUNK = 0x40000; constexpr size_t LZ4_UNCOMPRESSED = 0x800000; @@ -35,26 +34,26 @@ public: int read(void *buf, size_t len) final { return stream::read(buf, len); } - - int close() final { - finish(); - return bclose(); - } - -protected: - // If finish is overridden, destroy should be called in the destructor - virtual void finish() {} - void destroy() { if (fp) finish(); } }; class gz_strm : public cpr_stream { public: - ~gz_strm() override { destroy(); } - int write(const void *buf, size_t len) override { return len ? write(buf, len, Z_NO_FLUSH) : 0; } + ~gz_strm() override { + write(nullptr, 0, Z_FINISH); + switch(mode) { + case DECODE: + inflateEnd(&strm); + break; + case ENCODE: + deflateEnd(&strm); + break; + } + } + protected: enum mode_t { DECODE, @@ -72,18 +71,6 @@ protected: } } - void finish() override { - write(nullptr, 0, Z_FINISH); - switch(mode) { - case DECODE: - inflateEnd(&strm); - break; - case ENCODE: - deflateEnd(&strm); - break; - } - } - private: z_stream strm; uint8_t outbuf[CHUNK]; @@ -125,12 +112,22 @@ public: class bz_strm : public cpr_stream { public: - ~bz_strm() override { destroy(); } - int write(const void *buf, size_t len) override { return len ? write(buf, len, BZ_RUN) : 0; } + ~bz_strm() override { + switch(mode) { + case DECODE: + BZ2_bzDecompressEnd(&strm); + break; + case ENCODE: + write(nullptr, 0, BZ_FINISH); + BZ2_bzCompressEnd(&strm); + break; + } + } + protected: enum mode_t { DECODE, @@ -148,18 +145,6 @@ protected: } } - void finish() override { - switch(mode) { - case DECODE: - BZ2_bzDecompressEnd(&strm); - break; - case ENCODE: - write(nullptr, 0, BZ_FINISH); - BZ2_bzCompressEnd(&strm); - break; - } - } - private: bz_stream strm; char outbuf[CHUNK]; @@ -201,12 +186,15 @@ public: class lzma_strm : public cpr_stream { public: - ~lzma_strm() override { destroy(); } - int write(const void *buf, size_t len) override { return len ? write(buf, len, LZMA_RUN) : 0; } + ~lzma_strm() override { + write(nullptr, 0, LZMA_FINISH); + lzma_end(&strm); + } + protected: enum mode_t { DECODE, @@ -238,11 +226,6 @@ protected: } } - void finish() override { - write(nullptr, 0, LZMA_FINISH); - lzma_end(&strm); - } - private: lzma_stream strm; uint8_t outbuf[CHUNK]; @@ -266,17 +249,17 @@ private: class lzma_decoder : public lzma_strm { public: - lzma_decoder(FILE *fp) : lzma_strm(DECODE, fp) {} + explicit lzma_decoder(FILE *fp) : lzma_strm(DECODE, fp) {} }; class xz_encoder : public lzma_strm { public: - xz_encoder(FILE *fp) : lzma_strm(ENCODE_XZ, fp) {} + explicit xz_encoder(FILE *fp) : lzma_strm(ENCODE_XZ, fp) {} }; class lzma_encoder : public lzma_strm { public: - lzma_encoder(FILE *fp) : lzma_strm(ENCODE_LZMA, fp) {} + explicit lzma_encoder(FILE *fp) : lzma_strm(ENCODE_LZMA, fp) {} }; class LZ4F_decoder : public cpr_stream { @@ -340,12 +323,6 @@ public: LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); } - ~LZ4F_encoder() override { - destroy(); - LZ4F_freeCompressionContext(ctx); - delete[] outbuf; - } - int write(const void *buf, size_t len) override { auto ret = len; if (!outbuf) @@ -368,10 +345,11 @@ public: return ret; } -protected: - void finish() override { + ~LZ4F_encoder() override { size_t len = LZ4F_compressEnd(ctx, outbuf, outCapacity, nullptr); bwrite(outbuf, len); + LZ4F_freeCompressionContext(ctx); + delete[] outbuf; } private: @@ -466,12 +444,6 @@ public: : cpr_stream(fp), outbuf(new char[LZ4_COMPRESSED]), buf(new char[LZ4_UNCOMPRESSED]), init(false), buf_off(0), in_total(0) {} - ~LZ4_encoder() override { - destroy(); - delete[] outbuf; - delete[] buf; - } - int write(const void *in, size_t size) override { if (!init) { bwrite("\x02\x21\x4c\x18", 4); @@ -510,14 +482,15 @@ public: return true; } -protected: - void finish() override { + ~LZ4_encoder() override { if (buf_off) { int write = LZ4_compress_HC(buf, outbuf, buf_off, LZ4_COMPRESSED, 9); bwrite(&write, sizeof(write)); bwrite(outbuf, write); } bwrite(&in_total, sizeof(in_total)); + delete[] outbuf; + delete[] buf; } private: @@ -608,7 +581,7 @@ void decompress(char *infile, const char *outfile) { LOGE("Decompression error!\n"); } - strm->close(); + strm.reset(nullptr); fclose(in_fp); if (rm_in) @@ -651,7 +624,7 @@ void compress(const char *method, const char *infile, const char *outfile) { LOGE("Compression error!\n"); }; - strm->close(); + strm.reset(nullptr); fclose(in_fp); if (rm_in) diff --git a/native/jni/utils/include/stream.h b/native/jni/utils/include/stream.h index b46d91d6e..3013a0c7b 100644 --- a/native/jni/utils/include/stream.h +++ b/native/jni/utils/include/stream.h @@ -18,7 +18,6 @@ public: virtual int read(void *buf, size_t len); virtual int write(const void *buf, size_t len); virtual off_t seek(off_t off, int whence); - virtual int close(); virtual ~stream() = default; }; @@ -26,11 +25,10 @@ public: class filter_stream : public stream { public: filter_stream(FILE *fp) : fp(fp) {} - ~filter_stream() override { if (fp) close(); } + ~filter_stream() override; int read(void *buf, size_t len) override; int write(const void *buf, size_t len) override; - int close() override; void set_base(FILE *f); template diff --git a/native/jni/utils/stream.cpp b/native/jni/utils/stream.cpp index a28734589..28af1e73a 100644 --- a/native/jni/utils/stream.cpp +++ b/native/jni/utils/stream.cpp @@ -19,9 +19,8 @@ static fpos_t strm_seek(void *v, fpos_t off, int whence) { static int strm_close(void *v) { auto strm = reinterpret_cast(v); - int ret = strm->close(); delete strm; - return ret; + return 0; } FILE *open_stream(stream *strm) { @@ -46,8 +45,8 @@ off_t stream::seek(off_t off, int whence) { return -1; } -int stream::close() { - return 0; +filter_stream::~filter_stream() { + if (fp) fclose(fp); } int filter_stream::read(void *buf, size_t len) { @@ -58,12 +57,6 @@ int filter_stream::write(const void *buf, size_t len) { return fwrite(buf, 1, len, fp); } -int filter_stream::close() { - int ret = fclose(fp); - fp = nullptr; - return ret; -} - void filter_stream::set_base(FILE *f) { if (fp) fclose(fp); fp = f; From 01253f050ad3e220f74478f3f1088d97a5737294 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Sat, 23 Nov 2019 04:57:52 -0500 Subject: [PATCH 5/9] Use smart pointers --- native/jni/magiskboot/bootimg.cpp | 8 +-- native/jni/magiskboot/compress.cpp | 75 ++++++++++++++-------------- native/jni/magiskboot/compress.h | 7 ++- native/jni/magiskboot/ramdisk.cpp | 11 ++-- native/jni/magiskpolicy/policydb.cpp | 19 +++---- native/jni/utils/files.h | 5 ++ native/jni/utils/include/stream.h | 23 +++++---- native/jni/utils/stream.cpp | 20 +++----- 8 files changed, 87 insertions(+), 81 deletions(-) diff --git a/native/jni/magiskboot/bootimg.cpp b/native/jni/magiskboot/bootimg.cpp index 279a6a008..93745bb88 100644 --- a/native/jni/magiskboot/bootimg.cpp +++ b/native/jni/magiskboot/bootimg.cpp @@ -22,15 +22,15 @@ uint32_t dyn_img_hdr::j32 = 0; uint64_t dyn_img_hdr::j64 = 0; static void decompress(format_t type, int fd, const void *in, size_t size) { - unique_ptr ptr(get_decoder(type, open_stream(fd))); + auto ptr = get_decoder(type, make_stream(fd)); ptr->write(in, size); } -static int64_t compress(format_t type, int fd, const void *in, size_t size) { +static off_t compress(format_t type, int fd, const void *in, size_t size) { auto prev = lseek(fd, 0, SEEK_CUR); { - unique_ptr ptr(get_encoder(type, open_stream(fd))); - ptr->write(in, size); + auto strm = get_encoder(type, make_stream(fd)); + strm->write(in, size); } auto now = lseek(fd, 0, SEEK_CUR); return now - prev; diff --git a/native/jni/magiskboot/compress.cpp b/native/jni/magiskboot/compress.cpp index 232dfbbe8..8059aa3d1 100644 --- a/native/jni/magiskboot/compress.cpp +++ b/native/jni/magiskboot/compress.cpp @@ -29,11 +29,8 @@ constexpr size_t LZ4_COMPRESSED = LZ4_COMPRESSBOUND(LZ4_UNCOMPRESSED); class cpr_stream : public filter_stream { public: - explicit cpr_stream(FILE *fp) : filter_stream(fp) {} - - int read(void *buf, size_t len) final { - return stream::read(buf, len); - } + using filter_stream::filter_stream; + using stream::read; }; class gz_strm : public cpr_stream { @@ -60,7 +57,7 @@ protected: ENCODE } mode; - gz_strm(mode_t mode, FILE *fp) : cpr_stream(fp), mode(mode) { + gz_strm(mode_t mode, sFILE &&fp) : cpr_stream(std::move(fp)), mode(mode) { switch(mode) { case DECODE: inflateInit2(&strm, 15 | 16); @@ -102,12 +99,12 @@ private: class gz_decoder : public gz_strm { public: - explicit gz_decoder(FILE *fp) : gz_strm(DECODE, fp) {}; + explicit gz_decoder(sFILE &&fp) : gz_strm(DECODE, std::move(fp)) {}; }; class gz_encoder : public gz_strm { public: - explicit gz_encoder(FILE *fp) : gz_strm(ENCODE, fp) {}; + explicit gz_encoder(sFILE &&fp) : gz_strm(ENCODE, std::move(fp)) {}; }; class bz_strm : public cpr_stream { @@ -134,7 +131,7 @@ protected: ENCODE } mode; - bz_strm(mode_t mode, FILE *fp) : cpr_stream(fp), mode(mode) { + bz_strm(mode_t mode, sFILE &&fp) : cpr_stream(std::move(fp)), mode(mode) { switch(mode) { case DECODE: BZ2_bzDecompressInit(&strm, 0, 0); @@ -176,12 +173,12 @@ private: class bz_decoder : public bz_strm { public: - explicit bz_decoder(FILE *fp) : bz_strm(DECODE, fp) {}; + explicit bz_decoder(sFILE &&fp) : bz_strm(DECODE, std::move(fp)) {}; }; class bz_encoder : public bz_strm { public: - explicit bz_encoder(FILE *fp) : bz_strm(ENCODE, fp) {}; + explicit bz_encoder(sFILE &&fp) : bz_strm(ENCODE, std::move(fp)) {}; }; class lzma_strm : public cpr_stream { @@ -202,7 +199,8 @@ protected: ENCODE_LZMA } mode; - lzma_strm(mode_t mode, FILE *fp) : cpr_stream(fp), mode(mode), strm(LZMA_STREAM_INIT) { + lzma_strm(mode_t mode, sFILE &&fp) + : cpr_stream(std::move(fp)), mode(mode), strm(LZMA_STREAM_INIT) { lzma_options_lzma opt; // Initialize preset @@ -249,22 +247,22 @@ private: class lzma_decoder : public lzma_strm { public: - explicit lzma_decoder(FILE *fp) : lzma_strm(DECODE, fp) {} + explicit lzma_decoder(sFILE &&fp) : lzma_strm(DECODE, std::move(fp)) {} }; class xz_encoder : public lzma_strm { public: - explicit xz_encoder(FILE *fp) : lzma_strm(ENCODE_XZ, fp) {} + explicit xz_encoder(sFILE &&fp) : lzma_strm(ENCODE_XZ, std::move(fp)) {} }; class lzma_encoder : public lzma_strm { public: - explicit lzma_encoder(FILE *fp) : lzma_strm(ENCODE_LZMA, fp) {} + explicit lzma_encoder(sFILE &&fp) : lzma_strm(ENCODE_LZMA, std::move(fp)) {} }; class LZ4F_decoder : public cpr_stream { public: - explicit LZ4F_decoder(FILE *fp) : cpr_stream(fp), outbuf(nullptr) { + explicit LZ4F_decoder(sFILE &&fp) : cpr_stream(std::move(fp)), outbuf(nullptr) { LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION); } @@ -319,7 +317,8 @@ private: class LZ4F_encoder : public cpr_stream { public: - explicit LZ4F_encoder(FILE *fp) : cpr_stream(fp), outbuf(nullptr), outCapacity(0) { + explicit LZ4F_encoder(sFILE &&fp) + : cpr_stream(std::move(fp)), outbuf(nullptr), outCapacity(0) { LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); } @@ -379,9 +378,9 @@ private: class LZ4_decoder : public cpr_stream { public: - explicit LZ4_decoder(FILE *fp) - : cpr_stream(fp), out_buf(new char[LZ4_UNCOMPRESSED]), buffer(new char[LZ4_COMPRESSED]), - init(false), block_sz(0), buf_off(0) {} + explicit LZ4_decoder(sFILE &&fp) + : cpr_stream(std::move(fp)), out_buf(new char[LZ4_UNCOMPRESSED]), + buffer(new char[LZ4_COMPRESSED]), init(false), block_sz(0), buf_off(0) {} ~LZ4_decoder() override { delete[] out_buf; @@ -440,8 +439,8 @@ private: class LZ4_encoder : public cpr_stream { public: - explicit LZ4_encoder(FILE *fp) - : cpr_stream(fp), outbuf(new char[LZ4_COMPRESSED]), buf(new char[LZ4_UNCOMPRESSED]), + explicit LZ4_encoder(sFILE &&fp) + : cpr_stream(std::move(fp)), outbuf(new char[LZ4_COMPRESSED]), buf(new char[LZ4_UNCOMPRESSED]), init(false), buf_off(0), in_total(0) {} int write(const void *in, size_t size) override { @@ -501,38 +500,38 @@ private: unsigned in_total; }; -filter_stream *get_encoder(format_t type, FILE *fp) { +stream_ptr get_encoder(format_t type, sFILE &&fp) { switch (type) { case XZ: - return new xz_encoder(fp); + return make_unique(std::move(fp)); case LZMA: - return new lzma_encoder(fp); + return make_unique(std::move(fp)); case BZIP2: - return new bz_encoder(fp); + return make_unique(std::move(fp)); case LZ4: - return new LZ4F_encoder(fp); + return make_unique(std::move(fp)); case LZ4_LEGACY: - return new LZ4_encoder(fp); + return make_unique(std::move(fp)); case GZIP: default: - return new gz_encoder(fp); + return make_unique(std::move(fp)); } } -filter_stream *get_decoder(format_t type, FILE *fp) { +stream_ptr get_decoder(format_t type, sFILE &&fp) { switch (type) { case XZ: case LZMA: - return new lzma_decoder(fp); + return make_unique(std::move(fp)); case BZIP2: - return new bz_decoder(fp); + return make_unique(std::move(fp)); case LZ4: - return new LZ4F_decoder(fp); + return make_unique(std::move(fp)); case LZ4_LEGACY: - return new LZ4_decoder(fp); + return make_unique(std::move(fp)); case GZIP: default: - return new gz_decoder(fp); + return make_unique(std::move(fp)); } } @@ -541,7 +540,7 @@ void decompress(char *infile, const char *outfile) { bool rm_in = false; FILE *in_fp = in_std ? stdin : xfopen(infile, "re"); - unique_ptr strm; + stream_ptr strm; char buf[4096]; size_t len; @@ -574,7 +573,7 @@ void decompress(char *infile, const char *outfile) { } FILE *out_fp = outfile == "-"sv ? stdout : xfopen(outfile, "we"); - strm.reset(get_decoder(type, out_fp)); + strm = get_decoder(type, make_sFILE(out_fp)); if (ext) *ext = '.'; } if (strm->write(buf, len) < 0) @@ -615,7 +614,7 @@ void compress(const char *method, const char *infile, const char *outfile) { out_fp = outfile == "-"sv ? stdout : xfopen(outfile, "we"); } - unique_ptr strm(get_encoder(it->second, out_fp)); + auto strm = get_encoder(it->second, make_sFILE(out_fp)); char buf[4096]; size_t len; diff --git a/native/jni/magiskboot/compress.h b/native/jni/magiskboot/compress.h index d3c92e999..bb162455f 100644 --- a/native/jni/magiskboot/compress.h +++ b/native/jni/magiskboot/compress.h @@ -4,7 +4,10 @@ #include "format.h" -filter_stream *get_encoder(format_t type, FILE *fp = nullptr); -filter_stream *get_decoder(format_t type, FILE *fp = nullptr); +stream_ptr get_encoder(format_t type, sFILE &&fp); + +stream_ptr get_decoder(format_t type, sFILE &&fp); + void compress(const char *method, const char *infile, const char *outfile); + void decompress(char *infile, const char *outfile); diff --git a/native/jni/magiskboot/ramdisk.cpp b/native/jni/magiskboot/ramdisk.cpp index faabde059..798292409 100644 --- a/native/jni/magiskboot/ramdisk.cpp +++ b/native/jni/magiskboot/ramdisk.cpp @@ -244,8 +244,8 @@ void magisk_cpio::compress() { uint8_t *data; size_t len; - FILE *fp = open_stream(get_encoder(XZ, open_stream(data, len))); - dump(fp); + auto strm = make_stream(get_encoder(XZ, make_stream(data, len))); + dump(strm.release()); entries.clear(); entries.insert(std::move(init)); @@ -263,9 +263,10 @@ void magisk_cpio::decompress() { char *data; size_t len; - auto strm = get_decoder(XZ, open_stream(data, len)); - strm->write(it->second->data, it->second->filesize); - delete strm; + { + auto strm = get_decoder(XZ, make_stream(data, len)); + strm->write(it->second->data, it->second->filesize); + } entries.erase(it); load_cpio(data, len); diff --git a/native/jni/magiskpolicy/policydb.cpp b/native/jni/magiskpolicy/policydb.cpp index 717ddf5c3..723fd3876 100644 --- a/native/jni/magiskpolicy/policydb.cpp +++ b/native/jni/magiskpolicy/policydb.cpp @@ -174,19 +174,20 @@ int compile_split_cil() { } int dump_policydb(const char *file) { - struct policy_file pf; - policy_file_init(&pf); - uint8_t *data; size_t len; - pf.type = PF_USE_STDIO; - pf.fp = open_stream(data, len); - if (policydb_write(magisk_policydb, &pf)) { - LOGE("Fail to create policy image\n"); - return 1; + { + auto fp = make_stream(data, len); + struct policy_file pf; + policy_file_init(&pf); + pf.type = PF_USE_STDIO; + pf.fp = fp.get(); + if (policydb_write(magisk_policydb, &pf)) { + LOGE("Fail to create policy image\n"); + return 1; + } } - fclose(pf.fp); int fd = xopen(file, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) diff --git a/native/jni/utils/files.h b/native/jni/utils/files.h index e23fba6b1..dd44ea630 100644 --- a/native/jni/utils/files.h +++ b/native/jni/utils/files.h @@ -6,6 +6,11 @@ #define do_align(p, a) (((p) + (a) - 1) / (a) * (a)) #define align_off(p, a) (do_align(p, a) - (p)) +using sFILE = std::unique_ptr; +static inline sFILE make_sFILE(FILE *fp = nullptr) { + return sFILE(fp, fclose); +} + struct file_attr { struct stat st; char con[128]; diff --git a/native/jni/utils/include/stream.h b/native/jni/utils/include/stream.h index 3013a0c7b..ff855c8af 100644 --- a/native/jni/utils/include/stream.h +++ b/native/jni/utils/include/stream.h @@ -1,16 +1,19 @@ #pragma once -#include #include #include +#include "../files.h" + class stream; -FILE *open_stream(stream *strm); +using stream_ptr = std::unique_ptr; + +sFILE make_stream(stream_ptr &&strm); template -FILE *open_stream(Args &&... args) { - return open_stream(new T(args...)); +sFILE make_stream(Args &&... args) { + return make_stream(stream_ptr(new T(std::forward(args)...))); } class stream { @@ -24,20 +27,20 @@ public: // Delegates all operations to the base FILE pointer class filter_stream : public stream { public: - filter_stream(FILE *fp) : fp(fp) {} - ~filter_stream() override; + filter_stream() = default; + filter_stream(sFILE &&fp) : fp(std::move(fp)) {} int read(void *buf, size_t len) override; int write(const void *buf, size_t len) override; - void set_base(FILE *f); + void set_base(sFILE &&f); template void set_base(Args&&... args) { - set_base(open_stream(args...)); + set_base(make_stream(std::forward(args)...)); } protected: - FILE *fp; + sFILE fp; }; // Handy interface for classes that need custom seek logic @@ -65,7 +68,7 @@ private: size_t _cap = 0; void resize(size_t new_pos, bool zero = false); - size_t end_pos() override { return _len; } + size_t end_pos() final { return _len; } }; // File stream but does not close the file descriptor at any time diff --git a/native/jni/utils/stream.cpp b/native/jni/utils/stream.cpp index 28af1e73a..a0b687578 100644 --- a/native/jni/utils/stream.cpp +++ b/native/jni/utils/stream.cpp @@ -23,10 +23,9 @@ static int strm_close(void *v) { return 0; } -FILE *open_stream(stream *strm) { - FILE *fp = funopen(strm, strm_read, strm_write, strm_seek, strm_close); - // Disable buffering - setbuf(fp, nullptr); +sFILE make_stream(stream_ptr &&strm) { + sFILE fp(funopen(strm.release(), strm_read, strm_write, strm_seek, strm_close), fclose); + setbuf(fp.get(), nullptr); return fp; } @@ -45,21 +44,16 @@ off_t stream::seek(off_t off, int whence) { return -1; } -filter_stream::~filter_stream() { - if (fp) fclose(fp); -} - int filter_stream::read(void *buf, size_t len) { - return fread(buf, 1, len, fp); + return fread(buf, 1, len, fp.get()); } int filter_stream::write(const void *buf, size_t len) { - return fwrite(buf, 1, len, fp); + return fwrite(buf, 1, len, fp.get()); } -void filter_stream::set_base(FILE *f) { - if (fp) fclose(fp); - fp = f; +void filter_stream::set_base(sFILE &&f) { + fp = std::move(f); } off_t seekable_stream::seek_pos(off_t off, int whence) { From 34bb18448c3720560c37aef118655f32649f32b9 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Sat, 23 Nov 2019 17:18:55 -0500 Subject: [PATCH 6/9] Fix compile errors --- native/jni/magiskpolicy/rules.cpp | 2 +- native/jni/utils/files.h | 3 ++- native/jni/utils/include/stream.h | 3 +-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/native/jni/magiskpolicy/rules.cpp b/native/jni/magiskpolicy/rules.cpp index 6ea22e408..ffbc83bfc 100644 --- a/native/jni/magiskpolicy/rules.cpp +++ b/native/jni/magiskpolicy/rules.cpp @@ -196,7 +196,7 @@ void sepol_magisk_rules() { // Allow update_engine/addon.d-v2 to run permissive on all ROMs sepol_permissive("update_engine"); -#ifdef MAGISK_DEBUG +#if 0 // Remove all dontaudit in debug mode strip_dontaudit(); #endif diff --git a/native/jni/utils/files.h b/native/jni/utils/files.h index dd44ea630..26880258b 100644 --- a/native/jni/utils/files.h +++ b/native/jni/utils/files.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -42,7 +43,7 @@ void parse_prop_file(const char *file, const std::function void *__mmap(const char *filename, size_t *size, bool rw); void frm_rf(int dirfd, std::initializer_list excl = std::initializer_list()); void clone_dir(int src, int dest, bool overwrite = true); -void parse_mnt(const char *file, const std::function &fn); +void parse_mnt(const char *file, const std::function &fn); template void full_read(const char *filename, T &buf, size_t &size) { diff --git a/native/jni/utils/include/stream.h b/native/jni/utils/include/stream.h index ff855c8af..a07097fce 100644 --- a/native/jni/utils/include/stream.h +++ b/native/jni/utils/include/stream.h @@ -27,8 +27,7 @@ public: // Delegates all operations to the base FILE pointer class filter_stream : public stream { public: - filter_stream() = default; - filter_stream(sFILE &&fp) : fp(std::move(fp)) {} + filter_stream(sFILE &&fp = make_sFILE()) : fp(std::move(fp)) {} int read(void *buf, size_t len) override; int write(const void *buf, size_t len) override; From e373e596612eedf8b6321f0abc3ef09d8468460c Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Mon, 25 Nov 2019 19:07:06 -0500 Subject: [PATCH 7/9] Make sure file descriptors are setup properly --- native/jni/core/daemon.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/native/jni/core/daemon.cpp b/native/jni/core/daemon.cpp index 49a22a419..d923b1671 100644 --- a/native/jni/core/daemon.cpp +++ b/native/jni/core/daemon.cpp @@ -100,6 +100,18 @@ static void *request_handler(void *args) { static void main_daemon() { android_logging(); + + int fd = xopen("/dev/null", O_WRONLY); + xdup2(fd, STDOUT_FILENO); + xdup2(fd, STDERR_FILENO); + if (fd > STDERR_FILENO) + close(fd); + fd = xopen("/dev/zero", O_RDONLY); + xdup2(fd, STDIN_FILENO); + if (fd > STDERR_FILENO) + close(fd); + close(fd); + setsid(); setcon("u:r:" SEPOL_PROC_DOMAIN ":s0"); restore_rootcon(); @@ -112,14 +124,6 @@ static void main_daemon() { }, true); } - int fd = xopen("/dev/null", O_RDWR | O_CLOEXEC); - xdup2(fd, STDOUT_FILENO); - xdup2(fd, STDERR_FILENO); - close(fd); - fd = xopen("/dev/zero", O_RDWR | O_CLOEXEC); - xdup2(fd, STDIN_FILENO); - close(fd); - LOGI(SHOW_VER(Magisk) " daemon started\n"); // Get server stat From 276535dad615e0ff085c5e1be72ea673bfb3dd68 Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Mon, 25 Nov 2019 19:09:02 -0500 Subject: [PATCH 8/9] Fix incorrect kmsg path /proc/kmsg -> /dev/kmsg --- native/jni/init/init.cpp | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/native/jni/init/init.cpp b/native/jni/init/init.cpp index e6f632a2b..90d38cd32 100644 --- a/native/jni/init/init.cpp +++ b/native/jni/init/init.cpp @@ -38,23 +38,22 @@ static int vprintk(const char *fmt, va_list ap) { } void setup_klog() { // Shut down first 3 fds - int null; + int fd; if (access("/dev/null", W_OK) == 0) { - null = xopen("/dev/null", O_RDWR | O_CLOEXEC); + fd = xopen("/dev/null", O_RDWR | O_CLOEXEC); } else { mknod("/null", S_IFCHR | 0666, makedev(1, 3)); - null = xopen("/null", O_RDWR | O_CLOEXEC); + fd = xopen("/null", O_RDWR | O_CLOEXEC); unlink("/null"); } - xdup3(null, STDIN_FILENO, O_CLOEXEC); - xdup3(null, STDOUT_FILENO, O_CLOEXEC); - xdup3(null, STDERR_FILENO, O_CLOEXEC); - if (null > STDERR_FILENO) - close(null); + xdup3(fd, STDIN_FILENO, O_CLOEXEC); + xdup3(fd, STDOUT_FILENO, O_CLOEXEC); + xdup3(fd, STDERR_FILENO, O_CLOEXEC); + if (fd > STDERR_FILENO) + close(fd); - int fd; - if (access("/proc/kmsg", W_OK) == 0) { - fd = xopen("/proc/kmsg", O_WRONLY | O_CLOEXEC); + if (access("/dev/kmsg", W_OK) == 0) { + fd = xopen("/dev/kmsg", O_WRONLY | O_CLOEXEC); } else { mknod("/kmsg", S_IFCHR | 0666, makedev(1, 11)); fd = xopen("/kmsg", O_WRONLY | O_CLOEXEC); From 72edbfc4559161df2c3edad846c51b797401177d Mon Sep 17 00:00:00 2001 From: topjohnwu Date: Mon, 25 Nov 2019 19:09:54 -0500 Subject: [PATCH 9/9] Some platforms do not like null Bundles --- app/src/main/java/com/topjohnwu/magisk/utils/SuHandler.kt | 2 +- shared/src/main/java/com/topjohnwu/magisk/FileProvider.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/topjohnwu/magisk/utils/SuHandler.kt b/app/src/main/java/com/topjohnwu/magisk/utils/SuHandler.kt index 58c22bb42..c009b2445 100644 --- a/app/src/main/java/com/topjohnwu/magisk/utils/SuHandler.kt +++ b/app/src/main/java/com/topjohnwu/magisk/utils/SuHandler.kt @@ -28,7 +28,7 @@ object SuHandler : ProviderCallHandler { override fun call(context: Context, method: String, arg: String?, extras: Bundle?): Bundle? { invoke(context.wrap(), method, extras) - return null + return Bundle.EMPTY } operator fun invoke(context: Context, action: String?, data: Bundle?) { diff --git a/shared/src/main/java/com/topjohnwu/magisk/FileProvider.java b/shared/src/main/java/com/topjohnwu/magisk/FileProvider.java index 45c123b9d..820dcad22 100644 --- a/shared/src/main/java/com/topjohnwu/magisk/FileProvider.java +++ b/shared/src/main/java/com/topjohnwu/magisk/FileProvider.java @@ -154,7 +154,7 @@ public class FileProvider extends ContentProvider { public Bundle call(String method, String arg, Bundle extras) { if (callHandler != null) return callHandler.call(getContext(), method, arg, extras); - return null; + return Bundle.EMPTY; } @Override