pmt: initial 2.8.0 update

This commit is contained in:
2024-09-10 06:17:41 +03:00
parent ec5a2b97b9
commit 595f3b00b3
49 changed files with 2470 additions and 1793 deletions

114
jni/Debug.cpp Executable file
View File

@@ -0,0 +1,114 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_STRINGKEYS
#include <PartitionManager/PartitionManager.h>
using namespace PartitionManager;
/* it's prints standart logs */
void Functions::DisplayLog(LogLevel status, const char* _Nullable fmt, ...)
{
va_list args;
va_start(args, fmt);
switch (status)
{
case LOG_LEVEL_ERROR:
if (!Booleans::SilentEnabled)
{
fprintf(stderr, "%s: ", Strings::ExecutingName.c_str());
vfprintf(stderr, fmt, args);
}
exit(1);
break;
case LOG_LEVEL_WARN:
if (!Booleans::SilentEnabled)
{
fprintf(stdout, "%s: ", Display::UsingDispString->warn);
vfprintf(stdout, fmt, args);
}
break;
case LOG_LEVEL_FATAL:
if (!Booleans::SilentEnabled)
{
fprintf(stderr, "%s: ", Display::UsingDispString->fatal);
vfprintf(stderr, fmt, args);
}
abort();
break;
case LOG_LEVEL_DEBUG:
if (!Booleans::SilentEnabled)
vfprintf(stdout, fmt, args);
break;
}
va_end(args);
}
/* it's prints verbose logs */
void Functions::DisplayVerboseLog(LogLevel status, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
switch (status)
{
case LOG_LEVEL_ERROR:
if (Booleans::VerboseMode)
{
fprintf(stderr, "E:[stderr]: ");
vfprintf(stderr, fmt, args);
}
break;
case LOG_LEVEL_WARN:
if (Booleans::VerboseMode)
{
fprintf(stdout, "W:[stdout]: ");
vfprintf(stdout, fmt, args);
}
break;
case LOG_LEVEL_FATAL:
if (Booleans::VerboseMode)
{
fprintf(stderr, "F:[stderr]: ");
vfprintf(stderr, fmt, args);
abort();
}
break;
case LOG_LEVEL_DEBUG:
if (Booleans::VerboseMode)
{
fprintf(stdout, "D:[stdout]: ");
vfprintf(stdout, fmt, args);
}
break;
}
va_end(args);
}
/**
* Last error is taken from strerror by taking
* the contents of errno or taking a special entry
*/
char* strqerror(int errno_macro) { return strerror(errno_macro); }
/* end of code */

View File

@@ -16,15 +16,10 @@
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define INC_STAT
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#include <PartitionManager/PartitionManager.h>
/**
* The target file is controlled by the stat function.
@@ -32,48 +27,28 @@ extern "C" {
* If it is never found, it returns 1 value.
* If he finds 0 value is returned.
* If the desired type is not in -1 value is returned.
* If the search type is unknown, 3 value is returned
*/
int get_stat(const char* _Nonnull filepath, const char* _Nonnull stype)
int PartitionManager::Functions::GetState(const string& filepath, const string& stype)
{
static struct stat get_stat;
static struct stat GetStat;
if (stat(filepath, &get_stat) != 0)
VLOGD("GetStat: checking `%s' with 'stat <sys/stat.h>'...\n", filepath.c_str());
if (stat(filepath.c_str(), &GetStat) != 0)
return 1;
if (strcmp(stype, "dir") == 0)
{
if (S_ISDIR(get_stat.st_mode))
return 0;
else
return -1;
}
else if (strcmp(stype, "file") == 0)
{
if (S_ISREG(get_stat.st_mode))
return 0;
else
return -1;
}
else if (strcmp(stype, "blk") == 0)
{
if (S_ISBLK(get_stat.st_mode))
return 0;
else
return -1;
}
else if (strcmp(stype, "link") == 0)
{
if (S_ISLNK(get_stat.st_mode))
return 0;
else
return -1;
}
if (stype == "dir")
return (S_ISDIR(GetStat.st_mode)) ? 0 : -1;
else if (stype == "file")
return (S_ISREG(GetStat.st_mode)) ? 0 : -1;
else if (stype == "blk")
return (S_ISBLK(GetStat.st_mode)) ? 0 : -1;
else if (stype == "link")
return (S_ISLNK(GetStat.st_mode)) ? 0 : -1;
else
return 3;
return 2;
}
#ifdef __cplusplus
}
#endif
/* end of code */

65
jni/Help.cpp Executable file
View File

@@ -0,0 +1,65 @@
/* By YZBruh */
/*
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_STRINGKEYS
#define HELP
#include <PartitionManager/PartitionManager.h>
#include <PartitionManager/HelpFn.h>
using namespace PartitionManager;
struct langdb_docs* Display::UsingDocDispString = nullptr;
static void
prepare_langconf_docs(void)
{
if (Strings::CurrentLanguage == "en")
Display::UsingDocDispString = &Display::LangDocEn;
else if (Strings::CurrentLanguage == "tr")
Display::UsingDocDispString = &Display::LangDocTr;
}
void Functions::DisplayHelp(void)
{
VLOGD("DisplayHelp: Loading language for help messages... Calling prepare_langconf_docs() <local function>...\n");
prepare_langconf_docs();
VLOGD("DisplayHelp: Printing...\n");
LOGD("%s: %s %s\n", Display::UsingDocDispString->usage_docstr, Strings::ExecutingName.c_str(), Display::UsingDocDispString->docs_strs_l1);
LOGD(" %s: %s %s\n", Display::UsingDocDispString->or_str, Strings::ExecutingName.c_str(), Display::UsingDocDispString->docs_strs_l2);
LOGD(" %s: %s %s\n\n", Display::UsingDocDispString->or_str, Strings::ExecutingName.c_str(), Display::UsingDocDispString->docs_strs_l3);
LOGD("%s: \n", Display::UsingDocDispString->docs_strs_l4);
LOGD(" -l, --logical %s\n", Display::UsingDocDispString->docs_strs_l5);
LOGD(" -c, --context %s\n", Display::UsingDocDispString->docs_strs_l6);
LOGD(" -p, --list %s\n", Display::UsingDocDispString->docs_strs_l7);
LOGD(" -s, --silent %s\n", Display::UsingDocDispString->docs_strs_l8);
LOGD(" -f, --force %s\n", Display::UsingDocDispString->docs_strs_l9);
LOGD(" -V, --verbose %s\n", Display::UsingDocDispString->docs_strs_l10);
LOGD(" -S, --set-lang %s\n", Display::UsingDocDispString->docs_strs_l11);
LOGD(" -v, --version %s\n", Display::UsingDocDispString->docs_strs_l12);
LOGD(" --help %s\n\n", Display::UsingDocDispString->docs_strs_l13);
LOGD("%s:\n", Display::UsingDocDispString->docs_strs_l14);
LOGD(" %s backup boot_a -c /dev/block/platform/bootdevice/by-name\n", Strings::ExecutingName.c_str());
LOGD(" %s flash boot_a /sdcard/twrp/boot.img -c /dev/block/platform/bootdevice/by-name\n", Strings::ExecutingName.c_str());
LOGD(" %s format system_a ext4 --logical\n", Strings::ExecutingName.c_str());
LOGD(" %s -c /dev/block/platform/bootdevice/by-name --list\n\n", Strings::ExecutingName.c_str());
LOGD("%s <t.me/ShawkTeam | Topics | pmt>\n", Display::UsingDocDispString->docs_strs_l15);
}
/* end of code */

170
jni/LanguageTools.cpp Executable file
View File

@@ -0,0 +1,170 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_STAT
#define INC_STRINGKEYS
#include <PartitionManager/PartitionManager.h>
using namespace PartitionManager;
/* pmt's man doc file path on termux */
#define TERMUX_PMT_MANDOC "/data/data/com.termux/files/usr/share/man/man8/pmt.8.gz"
#define PMTLANG_CONF "/sdcard/.pmtlang.conf"
#define PMT_SW_POINT "/sdcard/.pmtlangsw"
struct langdb_general* Display::UsingDispString = nullptr;
static fstream langconf;
string supp_langs[] = {
"en",
"tr",
""
};
static bool
LangControl(const string lang)
{
for (int i = 0; !supp_langs[i].empty(); i++)
{
if (lang == supp_langs[i])
return true;
}
return false;
}
bool Functions::LoadLanguage(void)
{
string lang_fpr = "en";
langconf.close();
VLOGD("LoadLanguage: checking install type...\n");
if (Functions::GetState(TERMUX_PMT_MANDOC) == 0)
Booleans::InstalledOnTermux = true;
VLOGD("LoadLanguage: trying to open `%s' with 'open <fstream>'\n", PMTLANG_CONF);
langconf.open(PMTLANG_CONF, ios::in | ios::out);
VLOGD("LoadLanguage: checking status: `%s'...\n", PMTLANG_CONF);
if (!langconf.is_open())
{
langconf.open(PMTLANG_CONF, ios::out | ios::trunc);
VLOGD("LoadLanguage: calling SetLanguage()...\n");
Functions::SetLanguage("en", 1);
Display::UsingDispString = &Display::LangEn;
Strings::CurrentLanguage = "en";
if (langconf.is_open())
langconf.close();
return true;
}
else
{
VLOGD("LoadLanguage: reading `%s'\n", PMTLANG_CONF);
while (getline(langconf, lang_fpr))
{
if (lang_fpr == "en")
goto SetEn;
else if (lang_fpr == "tr")
goto SetTr;
else
{
VLOGD("LoadLanguage: calling SetLanguage()\n");
Functions::SetLanguage("en", 1);
VLOGD("LoadLanguage: re-calling LoadLanguage()\n");
Functions::LoadLanguage();
return true;
}
}
if (!getline(langconf, lang_fpr))
{
VLOGD("LoadLanguage: calling SetLanguage()\n");
Functions::SetLanguage("en", 1);
VLOGD("LoadLanguage: re-calling LoadLanguage()\n");
Functions::LoadLanguage();
return true;
}
}
SetEn:
langconf.close();
Display::UsingDispString = &Display::LangEn;
Strings::CurrentLanguage = "en";
VLOGD("LoadLanguage: loaded \"en\"\n");
return true;
SetTr:
langconf.close();
Display::UsingDispString = &Display::LangTr;
Strings::CurrentLanguage = "tr";
VLOGD("LoadLanguage: loaded \"tr\"\n");
return true;
return false;
}
void Functions::SetLanguage(const string& lang, unsigned short null_conf_stat)
{
VLOGD("SetLanguage: checking speficed language (from input).\n");
if (!LangControl(lang.c_str()))
LOGE("Unknown language: %s.\n", lang.c_str());
langconf.close();
VLOGD("SetLanguage: trying to open `%s' with 'open <fstream>'\n", PMTLANG_CONF);
langconf.open(PMTLANG_CONF, ios::out | ios::trunc);
if (!langconf.is_open())
LOGE("Failed!!! Cannot open/write config file.\n");
VLOGD("SetLanguage: write \"%s\" to `%s' with 'std <iostream>'\n", lang.c_str(), PMTLANG_CONF);
langconf << lang;
if (!langconf)
LOGE("Failed!!! Couldn't write config!\n");
else
langconf.close();
if (null_conf_stat != 1)
{
VLOGD("SetLanguage: generating dummy file `%s' with 'ofstream <fstream>'\n", PMT_SW_POINT);
ofstream sw_point(PMT_SW_POINT, ios::trunc);
if (sw_point.is_open())
sw_point.close();
}
}
bool Functions::CleanSWPoint(void)
{
if (Functions::GetState(PMT_SW_POINT) == 0)
{
VLOGD("CleanSWPoint: removing (force) `%s' with 'remove <unistd.h>'\n", PMT_SW_POINT);
remove(PMT_SW_POINT);
return true;
}
else
return false;
}
/* end of code */

View File

@@ -3,7 +3,7 @@
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* Licensed under the Apache License, Version 2.0 (the "License";
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
@@ -16,16 +16,15 @@
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define INC_STRINGKEYS
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#include <PartitionManager/PartitionManager.h>
struct pmt_langdb_general en = {
namespace PartitionManager {
namespace Display {
struct langdb_general LangEn = {
.lang_by_s = "YZBruh & r0manas",
.language = "English",
.lang_prefix = "en",
@@ -34,13 +33,12 @@ struct pmt_langdb_general en = {
.not_dir = "is not a directory.",
.not_in_dev = "Nothing found in /dev. Use force mode to avoid this error.",
.not_open = "Couldn't open",
.not_block = "The specified partition is not recognized as a block device.",
.not_block = "The specified partition is not recognized as a block device. Use force mode to avoid this error.",
.not_read = "Couldn't read",
.not_readdir = "Couldn't read directory",
.not_write = "Couldn't write",
.not_gen = "Couldn't generate",
.no_root = "Root access could not be detected! Please run this with root permissions.",
.no_target = "No target specified (backup, flash, or format)",
.expected_backup_arg = "Expected backup argument 2 (1 of them are not mandatory), retrieved",
.expected_flash_arg = "Expected flash argument 2, retrieved",
.expected_format_arg = "Expected format argument 2, retrieved",
@@ -48,10 +46,10 @@ struct pmt_langdb_general en = {
.multiple_wiewers = "Multiple viewers can't be used on the same line.",
.common_symbol_rule = "When specifying arguments for an option, ensure they do not begin with '-'. Each argument must correspond correctly to its respective option.",
.req_part_name = "Partition name required.",
.part_not_found = "Partition not found!",
.part_not_found = "Partition not found! Maybe a logical partition?",
.unsupported_fs = "Formatter: unsupported filesystem",
.cannot_stat = "Can't retrieve file status",
.ffile_more_part = "Flash file size exceeds partition capacity.",
.ffile_more_part = "Flash file size exceeds partition capacity. Use force mode to avoid this error (not recommended, riscy!).",
.cannot_get_bsz = "Failed to retrieve partition block size.",
.format_fail = "Formatting failed! There is a possibility of data damage.",
.depr_backup_opt = "These options for the backup are unavailable.",
@@ -60,24 +58,32 @@ struct pmt_langdb_general en = {
.depr_Vlicense_opt = "No memory for unnecessary options!",
.depr_ch_list_opt = "Use -p argument for listing partitions.",
.not_spec_opt = "Specify the necessary arguments, not option",
.some_spec = "You may have indicated options, but they don't work much unless you speficy a main transaction",
.logical_warn = "This device uses logical partitions.",
.ab_warn = "This device uses A/B partition style.",
.out_not_spec = "Output file name not specified. Using default name",
.out_not_spec = "Output file name not specified. Using created name",
.please_rerun = "Please rerun the command.",
.part_disk_sz = "Partition disk size",
.part_disk_sz = "Partition (backup) size",
.flash_file_sz = "Flash file size",
.part_disk_sz_fail = "Failed to retrieve partition disk size.",
.flash_file_sz_fail = "Failed to retrieve flash file size.",
.unknown_opr = "Unknown operand",
.list_of_dir = "Directory listing",
.req_an_arg = "option requires an argument",
.list_of_general = "List of general partitions",
.list_of_logc = "List of logical partitions",
.success_backup = "Backup successful. Output",
.success_flash = "Flash successful",
.success_format = "Format successful",
.formatting = "Formatting",
.warn = "WARNING",
.fatal = "FATAL ERROR",
.is_requires_arg = "requires an argument",
.unknw_arg = "unknown option",
.switching_lang = "Switching language...",
.welcome = "language!",
.welcome_ = "Welcome to ",
.for_more = "for more information",
.s_and_v = "Silent and verbose mode cannot be used together!",
.try_h = "Try",
.usage_head = "Usage",
.depr_opt_str = "DEPRECATED OPTION",
@@ -86,26 +92,26 @@ struct pmt_langdb_general en = {
.compiler_str = "Compiler",
.version_str = "version",
.bin_str = "binary",
.fs_str = "Filesystem",
.unknw_str = "unknown",
.by_str = "By"
};
struct pmt_langdb_general tr = {
struct langdb_general LangTr = {
.lang_by_s = "YZBruh",
.language = "Türkçe",
.lang_prefix = "tr",
.not_logical = "Bu cihaz mantıksal (logical) bölümlere sahip değil!",
.not_file = "Bu bir dosya değil",
.not_dir = "Bu bir dizin değil",
.not_in_dev = "Bu bir şakamı? Bunun /dev dizini ile bi r ilgisi yok (içermiyor). Bu hatayla karşılaşmak istemiyorsanız zorlama (force) modu kullanın.",
.not_in_dev = "Bu bir şakamı? Bunun /dev dizini ile bir ilgisi yok (içermiyor). Bu hatayla karşılaşmak istemiyorsanız zorlama (force) modu kullanın.",
.not_open = "ılamıyor",
.not_block = "Belirtilen bölüm bir blok değil. Yani aslında bu bir bölüm bile değil (disk). Bu hatayı almak için şanslı olmak gerek..!",
.not_block = "Belirtilen bölüm bir blok değil. Yani aslında bu bir bölüm bile değil (disk). Bu hatayı almak için şanslı olmak gerek..! Bu hatayla karşılaşmak istemiyorsanız zorlama (force) modu kullanın.",
.not_read = "Veri okunamıyor",
.not_readdir = "Dizin verisi okunamıyor",
.not_write = "Veri yazılamıyor",
.not_gen = "Oluşturulamıyor",
.no_root = "Root erişimi tespit edilemedi! Lütfen root erişimi ile çalıştırın.",
.no_target = "Hedef işlem yok (yedek, flaş veya format).",
.expected_backup_arg = "Beklenen yedekleme argümanı 2 (bir tanesi zorunlu değil), alınan",
.expected_flash_arg = "Beklenen flaş argümanı 2, alınan",
.expected_format_arg = "Beklenen format argümanı 2, alınan",
@@ -113,10 +119,10 @@ struct pmt_langdb_general tr = {
.multiple_wiewers = "Birden fazla görüntüleme işlemi yapan fonksiyonlar bir arada kullanılamaz. Aynı anda sadece bir tanesi kullanılabilir.",
.common_symbol_rule = "Bir seçeneğin argümanını verirken argüman önüne '-' sembolü getirilemez. Sembolü kaldırın ve tekrar deneyin.",
.req_part_name = "Bölüm adı gereklidir.",
.part_not_found = "Bölüm bulunamadı!",
.part_not_found = "Bölüm bulunamadı! Belki mantıksal (logical) bir bölümdür?",
.unsupported_fs = "Formatlayıcı: desteklenmeyen dosya sistemi:",
.cannot_stat = "Durumu tespit edilemedi",
.ffile_more_part = "Flaşlanacak dosyanın boyutu mevcut bölüm boyutundan fazla.",
.ffile_more_part = "Flaşlanacak dosyanın boyutu mevcut bölüm boyutundan fazla. Bu hatayla karşılaşmak istemiyorsanız zorlama (force) modu kullanın (bunu yapmanız asla önerilmez).",
.cannot_get_bsz = "Bölüm blok boyutu tespit edilemedi!",
.format_fail = "Formatlama başarısız oldu. Bazı şeyler zarar görmüş olabilir!",
.depr_backup_opt = "Yedek için artık bu seçeneği kullanamazsınız.",
@@ -124,25 +130,33 @@ struct pmt_langdb_general tr = {
.depr_format_opt = "Formatlama için artıi bu seçeneği kullanamazsınız.",
.depr_Vlicense_opt = "Gereksiz seçeneklere bellek yok!",
.depr_ch_list_opt = "Listeleme için -p seçeneğini kullanabilirsiniz.",
.logical_warn = "Uyarı: bu cihaz mantıksal (logical) bölümlere sahip.",
.not_spec_opt = "Seçenek değil, gerekli argümanları belirtin",
.ab_warn = "Uyarı: bu cihazın bazı bölümleri A/B kullanıyor.",
.out_not_spec = "Uyarı: çıktı dosya belirtilmedi. Çıktı dosya adı bölüm adına göre belirlenecek.",
.logical_warn = "Bu cihaz mantıksal (logical) bölümlere sahip.",
.not_spec_opt = "Seçenek değil, gerekli argümanları verin",
.some_spec = "Seçenek belirtmiş olabilirsiniz fakat, ana işlem belirtmedikçe pek işe yaramazlar",
.ab_warn = "Bu cihazın bazı bölümleri A/B kullanıyor.",
.out_not_spec = "Çıktı dosya adı belirtilmedi. Oluşturulan çıktı adı",
.please_rerun = "Lütfen yeniden çalıştırın",
.part_disk_sz = "Bölümün disk boyutu",
.part_disk_sz = "Bölümün (yedek) boyutu",
.flash_file_sz = "Flaşlanacak dosyanın boyutu",
.flash_file_sz_fail = "Uyarı: flaşlanacak dosyanın boyutu tespit edilemedi.",
.part_disk_sz_fail = "Uyarı: bölüm boyutunun boyutu tespit edilemedi.",
.unknown_opr = "Bilinmeyen işlem",
.list_of_dir = "Dizin içeriğinin listesi",
.req_an_arg = "bu seçenek argüman gerektirir",
.list_of_general = "Genel bölümlerin listesi",
.list_of_logc = "Mantıksal (logical) bölümlerin listesi",
.success_backup = "Başarılı. Çıktı",
.success_flash = "Başarılı.",
.success_format = "Formatlama başarılı",
.formatting = "Formatlanıyor",
.warn = "UYARI",
.fatal = "KRİTİK HATA",
.is_requires_arg = "bir argüman gereklidir",
.unknw_arg = "bilinmeyen seçenek",
.switching_lang = "Dil değiştiriliyor...",
.welcome = "diline hoş geldiniz!",
.welcome_ = NULL,
.for_more = "komutunu kullanabilirsiniz",
.s_and_v = "Sessiz ve ayrıntılı günlüklenme aynı anda kullanılamaz!",
.try_h = "Daha fazla bilgi",
.usage_head = "Kullanımı",
.depr_opt_str = "KALDIRILMIŞ SEÇENEK",
@@ -151,56 +165,52 @@ struct pmt_langdb_general tr = {
.compiler_str = "Derleyici",
.version_str = "versiyon",
.bin_str = "yapı",
.fs_str = "Dosya sistemi",
.unknw_str = "bilinmeyen",
.by_str = "Çeviriyi yapan(lar):"
};
struct pmt_langdb_docs en_docs = {
.docs_strs_l1 = "backup PARTITION [OUTPUT] [OPTIONS]...",
.docs_strs_l2 = "flash PARTITION FILE [OPTIONS]...",
.docs_strs_l3 = "format PARTITION FILE_SYSTEM[ext/2/3/4] [OPTIONS]...",
struct langdb_docs LangDocEn = {
.docs_strs_l1 = "[OPTIONS] backup PARTITION [OUTPUT] [OPTIONS]...",
.docs_strs_l2 = "[OPTIONS] flash PARTITION FILE [OPTIONS]...",
.docs_strs_l3 = "[OPTIONS] format PARTITION FILE_SYSTEM[ext/2/3/4] [OPTIONS]...",
.docs_strs_l4 = "Options",
.docs_strs_l5 = "It is meant to determine whether the target partition is logical.",
.docs_strs_l6 = "It is meant to specify a custom /dev context. Only classic partitions (default: /dev/block/by-name).",
.docs_strs_l6 = "It is meant to specify a custom /dev context. Only normal partitions (default: /dev/block/by-name).",
.docs_strs_l7 = "List partitions.",
.docs_strs_l8 = "Information and warning messages are silenced in normal work.",
.docs_strs_l9 = "Force mode. Some things are ignored.",
.docs_strs_l10 = "Set current language.",
.docs_strs_l11 = "See version.",
.docs_strs_l12 = "See this help message.",
.docs_strs_l13 = "Examples",
.docs_strs_l14 = "Report bugs to",
.docs_strs_l10 = "Verbose mode. Print detailed informations etc.",
.docs_strs_l11 = "Set current language.",
.docs_strs_l12 = "See version.",
.docs_strs_l13 = "See this help message.",
.docs_strs_l14 = "Examples",
.docs_strs_l15 = "Report bugs and suggestions to",
.or_str = "or",
.usage_docstr = "Usage"
};
struct pmt_langdb_docs tr_docs = {
.docs_strs_l1 = "backup BÖLÜM [ÇIKTI] [SEÇENEKLER]...",
.docs_strs_l2 = "flash BÖLÜM DOSYA [SEÇENEKLER]...",
.docs_strs_l3 = "format BÖLÜM DOSYA_SİSTEMİ[ext/2/3/4] [SEÇENEKLER]...",
struct langdb_docs LangDocTr = {
.docs_strs_l1 = "[SEÇENEKLER] backup BÖLÜM [ÇIKTI] [SEÇENEKLER]...",
.docs_strs_l2 = "[SEÇENEKLER] flash BÖLÜM DOSYA [SEÇENEKLER]...",
.docs_strs_l3 = "[SEÇENEKLER] format BÖLÜM DOSYA_SİSTEMİ[ext/2/3/4] [SEÇENEKLER]...",
.docs_strs_l4 = "Seçenekler",
.docs_strs_l5 = "Mantıksal (logical) bölüm ile işlem yapın.",
.docs_strs_l6 = "Özel /dev bağlamı belirtin. Sadece normal bölümler içindir (Varsayılan: /dev/block/by-name).",
.docs_strs_l7 = "Bölümler listelenir.",
.docs_strs_l8 = "Bilgi ve uyarı mesajları susturulur.",
.docs_strs_l9 = "Zorlama modu. Bazı şeyler göz ardı edilir.",
.docs_strs_l10 = "Mevcut dili ayarlayın.",
.docs_strs_l11 = "Sürümü görüntüleyin.",
.docs_strs_l12 = "Bu yardım mesajını görüntüleyin.",
.docs_strs_l13 = "Örnekler",
.docs_strs_l14 = "Sorunları şu adrese bildirin:",
.docs_strs_l10 = "Ayrıntılı bilgi modu. Daha fazla bilgi mesajı verilir.",
.docs_strs_l11 = "Mevcut dili ayarlayın.",
.docs_strs_l12 = "Sürümü görüntüleyin.",
.docs_strs_l13 = "Bu yardım mesajını görüntüleyin.",
.docs_strs_l14 = "Örnekler",
.docs_strs_l15 = "Sorunları ve önerileri şuraya bildirin:",
.or_str = "yada",
.usage_docstr = "Kullanımı"
};
struct pmt_langdb_langs lang[] = {
{"en"},
{"tr"},
{NULL}
};
#ifdef __cplusplus
}
#endif
} /* namespace Display */
} /* namespace PartitionManager */
/* end of code */

131
jni/ListPartitions.cpp Executable file
View File

@@ -0,0 +1,131 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_DIRENT
#define INC_STRINGKEYS
#include <PartitionManager/PartitionManager.h>
using namespace PartitionManager;
#define CUR_DEV_CNTX "/dev/block/by-name"
#define LGC_DEV_CNTX "/dev/block/mapper"
static DIR *dir;
static int
list(const string& operation, const char* target_dir)
{
static int count;
struct dirent **list;
bool list_parts = (operation == "print") ? true : false;
dir = nullptr;
dir = opendir(target_dir);
if (list_parts)
{
count = scandir(target_dir, &list, nullptr, alphasort);
if (count < 0)
LOGE("%s: `%s': %s\n", Display::UsingDispString->not_readdir, target_dir, strqerror());
for (int i = 0; i < count; i++)
{
if (list[i]->d_name[0] != '.' \
&& strncmp(list[i]->d_name, "com.", 4) != 0 \
&& strcmp(list[i]->d_name, "by-uuid") != 0 \
&& strcmp(list[i]->d_name, "userdata") != 0)
LOGD(" - [ %-16s ]\n", list[i]->d_name);
free(list[i]);
}
free(list);
list = nullptr;
goto directory;
}
directory:
if (dir != nullptr)
{
closedir(dir);
return 0;
}
else
return -1;
return 2;
}
/* list existing partitions */
int Functions::ListPartitions(void)
{
VLOGD("ListPartitions: selecting context...\n");
string acc_cxt = (Booleans::UseCustomContext) ? Strings::CustomContext : CUR_DEV_CNTX;
VLOGD("ListPartitions: trying to access `%s'...\n", acc_cxt.c_str());
if (list("access", acc_cxt.c_str()) != 0)
{
if (!Booleans::ForceMode)
LOGE("%s: `%s': %s\n", Display::UsingDispString->not_open, acc_cxt.c_str(), strqerror());
else
return 1;
}
else
{
LOGD("%s:\n", Display::UsingDispString->list_of_general);
list("print", acc_cxt.c_str());
}
if (Booleans::UsesLogical)
{
VLOGD("ListPartitions: checking for listing `%s'...\n", LGC_DEV_CNTX);
if (list("access", LGC_DEV_CNTX) != 0)
LOGE("%s: `%s': %s\n", Display::UsingDispString->not_open, LGC_DEV_CNTX, strqerror());
else
{
LOGD("\n%s:\n", Display::UsingDispString->list_of_logc);
list("print", LGC_DEV_CNTX);
}
}
VLOGD("ListPartitions: (if have) warnings are printed...\n");
if (Booleans::UsesLogical)
{
LOGD("\n");
LOGW("%s\n", Display::UsingDispString->logical_warn);
}
if (Booleans::UsesSlots)
{
if (!Booleans::UsesSlots)
LOGD("\n");
LOGW("%s\n", Display::UsingDispString->ab_warn);
}
return 0;
}
/* end of code */

View File

@@ -31,34 +31,37 @@ PMT_INCDIR := $(INCLUDE_DIR)/pmt
# the presence of all source files that are on this list will be checked
SRCS_REQ := \
place-holder/debug.c \
place-holder/help.c \
place-holder/get_stat.c \
place-holder/lang_tools.c \
place-holder/languages.c \
place-holder/partitiontool.c \
place-holder/pmt.c \
place-holder/root.c \
place-holder/tools.c \
place-holder/version.c
place-holder/Debug.cpp \
place-holder/Help.cpp \
place-holder/GetState.cpp \
place-holder/LanguageTools.cpp \
place-holder/Languages.cpp \
place-holder/PartitionTool.cpp \
place-holder/PartitionManager.cpp \
place-holder/Root.cpp \
place-holder/Tools.cpp \
place-holder/Version.cpp
# objects to be used when executable file is created
OBJS_EXEC := \
$(SOURCE_DIR)/$(TARGET).o \
$(SOURCE_DIR)/help.o \
$(SOURCE_DIR)/version.o \
$(SOURCE_DIR)/get_stat.o \
$(SOURCE_DIR)/tools.o \
$(SOURCE_DIR)/lang_tools.o \
$(SOURCE_DIR)/languages.o
$(SOURCE_DIR)/Debug.o \
$(SOURCE_DIR)/Root.o \
$(SOURCE_DIR)/PartitionManager.o \
$(SOURCE_DIR)/PartitionTool.o \
$(SOURCE_DIR)/ListPartitions.o \
$(SOURCE_DIR)/Help.o \
$(SOURCE_DIR)/Version.o \
$(SOURCE_DIR)/GetState.o \
$(SOURCE_DIR)/Tools.o \
$(SOURCE_DIR)/Languages.o \
$(SOURCE_DIR)/LanguageTools.o
HEADERS_REQ := \
$(PMT_INCDIR)/pmt/ExternC.h \
$(PMT_INCDIR)/pmt/Deprecates.h \
$(PMT_INCDIR)/pmt/HelpMessages.h \
$(PMT_INCDIR)/pmt/PartitionManager.h \
$(PMT_INCDIR)/pmt/StringKeys.h \
$(PMT_INCDIR)/pmt/VersionVars.h
$(PMT_INCDIR)/PartitionManager/Deprecates.h \
$(PMT_INCDIR)/PartitionManager/HelpFn.h \
$(PMT_INCDIR)/PartitionManager/PartitionManager.h \
$(PMT_INCDIR)/PartitionManager/StringKeys.h \
$(PMT_INCDIR)/PartitionManager/VersionFnVars.h
PROGRESS_LIST := \
welcome \
@@ -68,18 +71,10 @@ PROGRESS_LIST := \
pr_obj \
$(OBJS) \
make_outdirs \
pr_sts \
$(STATIC_LIBS) \
make_executable \
wait \
end_progress
define check_hf
@ [ ! -f "$1" ] \
&& $(E_NS) " ==> Couldn't found required header file: include/pmt/`basename $1`" \
&& exit 1
endef
# all target for building
all: $(PROGRESS_LIST)
@@ -92,29 +87,20 @@ welcome:
&& $(E_NS)
$(E) " -------------------------------- " \
&& $(E_NS)
@ if [ -f $(SOURCE_DIR)/debug.o ]; then \
$(E_NS) " - Please clean up before you build it." && echo; \
$(E_NS) " ----------------------------------- "; \
exit 1; \
fi
$(E) " - Checking required source files..."
pr_obj:
$(E) " - Building objects..."
pr_sts:
$(E) " - Making static libraries..."
wait:
@ sleep 2
make_outdirs:
@ rm -rf $(IN_OUT_DIR)
@ mkdir $(BINARY_DIR)
@ mkdir $(PACKAGE_DIR)
@ mkdir $(STATICLIB_DIR)
@ mkdir -p $(BINARY_DIR)
@ mkdir -p $(PACKAGE_DIR)
place-holder/%.c:
place-holder/%.cpp:
$(E) " CHK $(SOURCE_DIRNAME)/`basename $@`"
@ if [ ! -f "$(SOURCE_DIR)/`basename $@`" ]; then \
$(E_NS) " ==> Couldn't found required source file: $(SOURCE_DIRNAME)/`basename $@`"; \
@@ -122,24 +108,20 @@ place-holder/%.c:
fi
$(PMT_INCDIR)/%.h:
$(E) " CHK include/pmt/`basename $@`"
@ if [ ! -f "$(INCLUDE_DIR)/pmt/`basename $@`" ]; then \
$(E_NS) " ==> Couldn't found required header file: include/pmt/`basename $@`"; \
$(E) " CHK include/PartitionManager/`basename $@`"
@ if [ ! -f "$(INCLUDE_DIR)/PartitionManager/`basename $@`" ]; then \
$(E_NS) " ==> Couldn't found required header file: include/PartitionManager/`basename $@`"; \
exit 1; \
fi
$(SOURCE_DIR)/%.o: $(SOURCE_DIR)/%.c
$(E) " CC $(SOURCE_DIRNAME)/`basename $@`"
@ $(CC) $(CFLAGS) -c "$<" || exit 1
$(TARGET)_%:
$(E) " AR lib$@.a"
@ $(AR) rcs "lib$@.a" "$(SOURCE_DIR)/$$(echo "$@" | cut -d'_' -f2).o"
$(SOURCE_DIR)/%.o: $(SOURCE_DIR)/%.cpp
$(E) " CXX $(SOURCE_DIRNAME)/`basename $@`"
@ $(CXX) -x c++ $(CXXFLAGS) -c "$<" || exit 1
make_executable:
$(E) " - Making executable file..."
$(E) " LD $(TARGET)"
@ $(CC) $(CFLAGS) -L$(SOURCE_DIR) $(foreach st,$(STATIC_LIBS),$(shell echo -n -l$(st) )) -o $(TARGET) $(OBJS_EXEC) || exit 1
@ $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJS_EXEC) || exit 1
end_progress:
@ abort_build() { \
@@ -152,7 +134,6 @@ end_progress:
exit 1; \
}; \
mv $(TARGET) $(BINARY_DIR) || abort_build; \
mv *.a $(STATICLIB_DIR) || abort_build; \
$(E_NS) " - Generating package..."; \
cp $(BINARY_DIR)/$(TARGET) $(PACKAGE_DIR) || abort_build; \
$(E_NS) " XZ $(OUT_DIRNAME)/package/$(TARGET)-`date +%Y%m%d`.xz"
@@ -165,7 +146,6 @@ end_progress:
.PHONY: clean
clean:
$(eval STATICLIBS = $(wildcard $(SOURCE_DIR)/*.a))
$(eval OBJS = $(wildcard $(SOURCE_DIR)/*.o))
$(info Cleaning files...)
$(foreach obj, \
@@ -173,10 +153,5 @@ clean:
$(call m_stat_nn,$(SOURCE_DIRNAME)/$(shell basename $(obj))) \
$(call erase,$(obj)) \
)
$(foreach lib, \
$(STATICLIBS), \
$(call m_stat_nn,$(SOURCE_DIRNAME)/$(shell basename $(lib))) \
$(call erase,$(lib)) \
)
# end

703
jni/PartitionManager.cpp Executable file
View File

@@ -0,0 +1,703 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_STAT
#define INC_LIBGEN
#define INC_STRINGKEYS
#include <PartitionManager/PartitionManager.h>
#include <PartitionManager/Deprecates.h>
#include <PartitionManager/HelpFn.h>
#include <PartitionManager/VersionFnVars.h>
/* add value to variables that are added globally and are not worth */
namespace PartitionManager {
namespace Strings {
string OutputName = "";
string CustomContext = "";
string TargetPartition = "";
string TargetFlashFile = "";
string TargetFormatFS = "";
string PartitionType = "";
string ExecutingName = "";
string CurrentLanguage = "";
} /* namespace Strings */
namespace Booleans {
bool UseLogical = false;
bool UseCustomContext = false;
bool UsesSlots = false;
bool UsesLogical = false;
bool SilentEnabled = false;
bool FlashMode = false;
bool BackupMode = false;
bool FormatMode = false;
bool ForceMode = false;
bool VerboseMode = false;
bool InstalledOnTermux = false;
bool ActivateRoot = false;
} /* namespace Booleans */
} /* namespace PartitionManager */
/* variable for use in control of '-' expression */
static string common_symbol_rule;
namespace PartitionManager {
namespace Functions {
/**
* He controls whether the '-' sign at
* the beginning of the given word
*/
static void
CheckOptSymbol(const string symbol)
{
if (!symbol.empty())
{
if (strncmp(symbol.c_str(), "-", 1) == 0)
LOGE("%s\n", common_symbol_rule.c_str());
}
}
static bool
ControlArg(const char* argv_holder)
{
if (argv_holder[0] != '-')
return true;
return false;
}
} /* namespace Functions */
} /* namespace PartitionManager */
static void
deprecated(const char opt, const char* deprecation_message, const char* opt_long = "ISNULL")
{
VLOGE("Deprecated Option: -%c (--%s). Printing error...\n", opt, opt_long);
DEPR_HANDLE(opt, opt_long, deprecation_message);
exit(1);
}
static void
PrContextInput(const string& context)
{
PartitionManager::Booleans::UseCustomContext = true;
PartitionManager::Strings::CustomContext = context;
PartitionManager::Functions::CheckOptSymbol(PartitionManager::Strings::CustomContext);
}
using namespace PartitionManager;
class PartitionManagerBase {
protected:
char* BaseFunctionName = nullptr;
int StartCode = -1;
bool IsRequiredOnlyOneArg = false;
public:
void CallTargetBaseFunction(void)
{
VLOGD("CallTargetBaseFunction [class]: Start(%d)\n", StartCode);
Functions::Start(StartCode);
}
void GenericNumericalController(int searchOn, int total, const char* MissingArgMessage)
{
if (total <= searchOn)
{
VLOGE("ArgumentProcessor [class]: Missing argument total (for %s function).\n", BaseFunctionName);
LOGE("%s 0.\n", MissingArgMessage);
}
if (!IsRequiredOnlyOneArg)
{
if (total <= (searchOn + 1))
{
VLOGE("ArgumentProcessor [class]: Missing argument total (for %s function).\n", BaseFunctionName);
LOGE("%s 1.\n", MissingArgMessage);
}
}
}
virtual void ArgumentProcessor(int searchOn, int total, char** arguments) { /* dummy, it's place holder */ }
};
class PartitionManagerBackup : public PartitionManagerBase {
public:
void ArgumentProcessor(int searchOn, int total, char** arguments) override
{
BaseFunctionName = "backup";
StartCode = 1;
IsRequiredOnlyOneArg = true;
GenericNumericalController(searchOn, total, Display::UsingDispString->expected_backup_arg);
if (Functions::ControlArg(arguments[searchOn]))
Strings::TargetPartition = arguments[searchOn];
else
LOGE("%s.\n", Display::UsingDispString->not_spec_opt);
Strings::OutputName = Strings::TargetPartition;
if (total > (searchOn + 1) && Functions::ControlArg(arguments[(searchOn + 1)]))
{
VLOGD("ArgumentProcessor [class]: Non-mandatory argument was detected and retrieved (for %s function).\n", BaseFunctionName);
Strings::OutputName = arguments[(searchOn + 1)];
}
Functions::CheckOptSymbol(Strings::TargetPartition);
Functions::CheckOptSymbol(Strings::OutputName);
}
};
class PartitionManagerFlash : public PartitionManagerBase {
public:
void ArgumentProcessor(int searchOn, int total, char** arguments) override
{
BaseFunctionName = "flash";
StartCode = 2;
IsRequiredOnlyOneArg = false;
GenericNumericalController(searchOn, total, Display::UsingDispString->expected_flash_arg);
if (Functions::ControlArg(arguments[searchOn]))
Strings::TargetPartition = arguments[searchOn ];
else
LOGE("%s.\n", Display::UsingDispString->not_spec_opt);
if (Functions::ControlArg(arguments[(searchOn + 1)]))
Strings::TargetFlashFile = arguments[(searchOn + 1)];
else
LOGE("%s.\n", Display::UsingDispString->not_spec_opt);
Functions::CheckOptSymbol(Strings::TargetFlashFile);
Functions::CheckOptSymbol(Strings::TargetPartition);
}
};
class PartitionManagerFormat : public PartitionManagerBase {
public:
void ArgumentProcessor(int searchOn, int total, char** arguments) override
{
BaseFunctionName = "format";
StartCode = 3;
IsRequiredOnlyOneArg = false;
GenericNumericalController(searchOn, total, Display::UsingDispString->expected_format_arg);
if (Functions::ControlArg(arguments[searchOn]))
Strings::TargetPartition = arguments[searchOn];
else
LOGE("%s.\n", Display::UsingDispString->not_spec_opt);
if (Functions::ControlArg(arguments[(searchOn + 1)]))
Strings::TargetFormatFS = arguments[(searchOn + 1)];
else
LOGE("%s.\n", Display::UsingDispString->not_spec_opt);
Functions::CheckOptSymbol(Strings::TargetFormatFS);
Functions::CheckOptSymbol(Strings::TargetPartition);
}
};
int main(int argc, char** argv)
{
Strings::ExecutingName = basename(argv[0]);
for (int i = 0; i <= (argc - 1); i++)
{
if (strncmp(argv[i], "-V", 2) == 0 || strcmp(argv[i], "--verbose") == 0)
Booleans::VerboseMode = true;
else
continue;
}
/* Generate classes */
VLOGD("Generating classes...\n");
PartitionManagerBase* Base;
PartitionManagerBase BaseTemplate;
PartitionManagerBackup BackupArgProcessorBase;
PartitionManagerFlash FlashArgProcessorBase;
PartitionManagerFormat FormatArgProcessorBase;
VLOGD("Main function started. Setting up locale. Calling 'setlocale <clocale>'\n");
setlocale(LC_ALL, "");
int argc_n = argc;
char buf[256];
char** args = argv;
VLOGD("Checking stdin status...\n");
if (!isatty(fileno(stdin)))
{
VLOGD("stdin is not empty.\n");
VLOGD("Parsing stdin arguments...\n");
while (fgets(buf, sizeof(buf), stdin) != nullptr)
{
buf[strcspn(buf, "\n")] = 0;
args[argc_n] = strdup(buf);
argc_n++;
}
VLOGD("Parsing completed.\n");
}
else
VLOGD("stdin empty.\n");
/* load language */
VLOGD("Loading language... Calling LoadLanguage()...\n");
if (!Functions::LoadLanguage())
{
cout << "LoadLanguage() process failed..!" << endl;
abort();
}
common_symbol_rule = Display::UsingDispString->common_symbol_rule;
argc = argc_n;
int argc_parse = (argc - 1);
char** args_ctrl = args;
args_ctrl++;
static bool ViewHelp = false;
static bool ViewVersion = false;
static bool LogicalSpeficy = false;
static bool ListRequired = false;
static bool MultipleViewers = false;
static bool SetLanguageReq = false;
static bool SomeSpec = false;
static char* SpeficedLanguagePr;
static string Option;
static string Target;
static int SearchResult = 3;
static int SearchOnMainInt = -1;
VLOGD("Parsing standart arguments...\n");
while (argc_parse && args_ctrl[0] != nullptr)
{
if (args_ctrl[0][0] != '-')
{
argc_parse--;
args_ctrl++;
continue;
}
for (int x = 1; true; x++)
{
Option = args_ctrl[0];
SomeSpec = true;
switch (args_ctrl[0][x])
{
case '-':
if (Option == "--backup")
deprecated('b', Display::UsingDispString->depr_backup_opt, "backup");
else if (Option == "--flash")
deprecated('F', Display::UsingDispString->depr_flash_opt, "flash");
else if (Option == "--format")
deprecated('r', Display::UsingDispString->depr_format_opt, "format");
else if (Option == "--license")
deprecated('L', Display::UsingDispString->depr_Vlicense_opt, "license");
else if (Option == "--logical")
{
VLOGD("Logical partition type specified.\n");
LogicalSpeficy = true;
break;
}
else if (Option == "--context")
{
VLOGD("Custom context specified.\n");
if (argc_parse > 1)
PrContextInput(args_ctrl[1]);
else
LOGE("--context: %s.\n%s `%s --help' %s.\n", \
Display::UsingDispString->is_requires_arg, \
Display::UsingDispString->try_h, \
Strings::ExecutingName.c_str(), \
Display::UsingDispString->for_more);
break;
}
else if (Option == "--list")
{
VLOGD("It was requested to list the partitions.\n");
ListRequired = true;
if (ViewVersion || ViewHelp)
MultipleViewers = true;
break;
}
else if (Option == "--force")
{
VLOGD("Force mode speficed.\n");
Booleans::ForceMode = true;
break;
}
else if (Option == "--verbose")
{
VLOGD("Verbose mode speficed.\n");
Booleans::VerboseMode = true;
break;
}
else if (Option == "--silent")
{
VLOGD("Silent mode speficed.\n");
Booleans::SilentEnabled = true;
break;
}
else if (Option == "--set-language")
{
VLOGD("It was requested to adjust the language.\n");
if (argc_parse > 1)
{
VLOGE("Language inputs: getting inputs...\n");
SetLanguageReq = true;
SpeficedLanguagePr = args_ctrl[1];
}
else
LOGE("--set-language: %s.\n%s `%s --help' %s.\n", \
Display::UsingDispString->is_requires_arg, \
Display::UsingDispString->try_h, \
Strings::ExecutingName.c_str(), \
Display::UsingDispString->for_more);
break;
}
else if (Option == "--version")
{
VLOGD("The version info was requested to be displayed.\n");
ViewVersion = true;
if (ListRequired || ViewHelp)
MultipleViewers = true;
break;
}
else if (Option == "--help")
{
VLOGD("The help message was requested to be displayed.\n");
ViewHelp = true;
if (ViewVersion || ListRequired)
MultipleViewers = true;
break;
}
else
{
VLOGE("Unknown Option: %s\n", args_ctrl[0]);
LOGE("%s: %s.\n%s `%s --help' %s.\n", args_ctrl[0], \
Display::UsingDispString->unknw_arg, \
Display::UsingDispString->try_h, \
Strings::ExecutingName.c_str(), \
Display::UsingDispString->for_more);
}
break;
case 'b':
deprecated('b', Display::UsingDispString->depr_backup_opt, "backup");
break;
case 'F':
deprecated('F', Display::UsingDispString->depr_flash_opt, "flash");
break;
case 'r':
deprecated('r', Display::UsingDispString->depr_format_opt, "format");
break;
case 'L':
deprecated('L', Display::UsingDispString->depr_Vlicense_opt, "license");
break;
case 'D':
deprecated('D', Display::UsingDispString->depr_ch_list_opt);
break;
case 'l':
VLOGD("Logical partition type specified.\n");
LogicalSpeficy = true;
continue;
case 'c':
VLOGD("Custom context speficed.\n");
if (argc_parse > 1)
{
VLOGE("Context inputs: getting inputs...\n");
PrContextInput(args_ctrl[1]);
continue;
}
else
LOGE("-c: %s.\n%s `%s --help' %s.\n", \
Display::UsingDispString->is_requires_arg, \
Display::UsingDispString->try_h, \
Strings::ExecutingName.c_str(), \
Display::UsingDispString->for_more);
break;
case 'p':
VLOGD("It was requested to list the partitions.\n");
ListRequired = true;
if (ViewVersion || ViewHelp)
MultipleViewers = true;
continue;
case 'f':
VLOGD("Force mode speficed.\n");
Booleans::ForceMode = true;
continue;
case 'V':
VLOGD("Verbose mode speficed.\n");
Booleans::VerboseMode = true;
continue;
case 's':
VLOGD("Silent mode speficed.\n");
Booleans::SilentEnabled = true;
continue;
case 'S':
VLOGD("It was requested to adjust the language.\n");
if (argc_parse > 1)
{
VLOGE("Language inputs: getting inputs...\n");
SetLanguageReq = true;
SpeficedLanguagePr = args_ctrl[1];
continue;
}
else
LOGE("-S: %s.\n%s `%s --help' %s.\n", \
Display::UsingDispString->is_requires_arg, \
Display::UsingDispString->try_h, \
Strings::ExecutingName.c_str(), \
Display::UsingDispString->for_more);
case 'v':
VLOGD("The version info was requested to be displayed.\n");
ViewVersion = true;
if (ListRequired || ViewHelp)
MultipleViewers = true;
continue;
case '\0':
break;
default:
VLOGE("Unknown Option: -%c\n", args_ctrl[0][x]);
LOGE("-%c: %s.\n%s `%s --help' %s.\n", args_ctrl[0][x], \
Display::UsingDispString->unknw_arg, \
Display::UsingDispString->try_h, \
Strings::ExecutingName.c_str(), \
Display::UsingDispString->for_more);
}
break;
}
argc_parse--;
args_ctrl++;
}
Base = &BaseTemplate;
argc_parse = argc;
VLOGD("Starting cycle for trapping main options...\n");
while (1)
{
if ((argc_parse - 1) == 0)
{
VLOGD("MainFnController: argc - 1 = 0. Breaking...\n");
break;
}
if (args[(argc_parse - 1)][0] == '-')
{
VLOGD("MainFnController: args[%d] starts with '-'. Continue.\n", (argc_parse - 1));
argc_parse--;
continue;
}
else
{
Target = args[(argc_parse - 1)];
SearchOnMainInt = argc_parse;
VLOGD("MainFnController: args[%d] = %s\n", (argc_parse - 1), args[(argc_parse - 1)]);
VLOGD("MainFnController: variable of \"Target\" (string): %s\n", Target.c_str());
if (Target == "backup")
{
Base = &BackupArgProcessorBase;
Booleans::BackupMode = true;
break;
}
else if (Target == "flash")
{
Base = &FlashArgProcessorBase;
Booleans::FlashMode = true;
break;
}
else if (Target == "format")
{
Base = &FormatArgProcessorBase;
Booleans::FormatMode = true;
break;
}
else
{
Target = "";
SearchOnMainInt = -1;
argc_parse--;
continue;
}
}
break;
}
if (Booleans::SilentEnabled && Booleans::VerboseMode)
{
VLOGE("Silent and verbose mode is one-way.\n");
cout << Strings::ExecutingName << ": " << Display::UsingDispString->s_and_v << endl;
exit(1);
}
VLOGD("Checking last language switch status...\n");
if (Functions::CleanSWPoint())
{
VLOGD("Last transactions found that language was changed between.\n");
if (Display::UsingDispString->welcome_ != nullptr)
LOGD("%s", Display::UsingDispString->welcome_);
LOGD("%s %s %s %s.\n", Display::UsingDispString->language, Display::UsingDispString->welcome, Display::UsingDispString->by_str, Display::UsingDispString->lang_by_s);
}
/* check argument total */
VLOGD("argc (arguments) total: %d.\n", argc);
if (argc < 2)
LOGE("%s.\n%s '%s --help' %s.\n", Display::UsingDispString->missing_operand, Display::UsingDispString->try_h, Strings::ExecutingName.c_str(), Display::UsingDispString->for_more);
/* stop the program if multiple viewer is used */
if (MultipleViewers)
{
VLOGE("Multiple viewer option selected!\n");
LOGE("%s\n", Display::UsingDispString->multiple_wiewers);
}
/* controller to handle viewer */
if (ViewHelp)
{
VLOGD("The help message was asked to display. It's displayed... Calling DisplayHelp()\n");
Functions::DisplayHelp();
return 0;
}
else if (ViewVersion)
{
VLOGD("The version info message was asked to display. It's displayed... Calling DisplayVersion()\n");
Functions::DisplayVersion();
return 0;
}
else if (ListRequired)
{
VLOGD("Partitions were asked to be listed. It's listed... Calling CheckRoot() (root check is required), CheckDevPoint() (for generating warnings etc.) and ListPartitions()\n");
Functions::CheckRoot();
VLOGD("CheckRoot() completed.\n");
Functions::CheckDevPoint();
VLOGD("CheckDevPoint() completed.\n");
return Functions::ListPartitions();
}
if (SetLanguageReq)
{
VLOGD("The language was asked to adjust. Calling SetLanguage()...\n");
LOGD("%s: %s\n", Strings::ExecutingName.c_str(), Display::UsingDispString->switching_lang);
Functions::SetLanguage(SpeficedLanguagePr, 0);
sleep(2);
VLOGD("SetLanguage() completed.\n");
LOGD("%s: %s.\n", Strings::ExecutingName.c_str(), Display::UsingDispString->please_rerun);
return 0;
}
if (Target.empty())
{
VLOGE("There's no job to do.\n");
LOGD("%s: %s.\n", Strings::ExecutingName.c_str(), Display::UsingDispString->missing_operand);
if (SomeSpec)
LOGD("%s.\n", Display::UsingDispString->some_spec);
LOGD("%s '%s --help' %s.\n",Display::UsingDispString->try_h, Strings::ExecutingName.c_str(), Display::UsingDispString->for_more);
exit(1);
}
Base->ArgumentProcessor(SearchOnMainInt, argc, args);
if (Booleans::FormatMode)
{
VLOGD("File system name specified for formatting is being contaminated...\n");
if (Strings::TargetFormatFS != "ext4" \
&& Strings::TargetFormatFS != "ext3" \
&& Strings::TargetFormatFS != "ext2")
{
VLOGE("Unsupported file system: %s.\n", Strings::TargetFormatFS.c_str());
LOGE("%s: %s\n", Display::UsingDispString->unsupported_fs, Strings::TargetFormatFS.c_str());
}
}
/* checks */
VLOGD("Checking root status... Calling CheckRoot()...\n");
Functions::CheckRoot();
VLOGD("Checking A/B and logical device status... Calling CheckDevPoint()...\n");
Functions::CheckDevPoint();
if (LogicalSpeficy)
{
VLOGD("Logical partition type speficed. Checking partition statust's...\n");
if (Booleans::UsesLogical)
Booleans::UseLogical = true;
else
LOGE("%s\n", Display::UsingDispString->not_logical);
}
if (Booleans::FlashMode)
{
VLOGD("The status of the specified file for flashing is being checked...\n");
SearchResult = Functions::GetState(Strings::TargetFlashFile);
if (SearchResult == 1)
LOGE("%s: `%s': %s\n", Display::UsingDispString->cannot_stat, Strings::TargetFlashFile.c_str(), strqerror());
else if (SearchResult == -1)
LOGE("`%s': %s\n", Strings::TargetFlashFile.c_str(), Display::UsingDispString->not_file);
}
/* custom context checker */
if (Booleans::UseCustomContext)
{
VLOGD("The status of the \"dev\" is controlled in the specified custom /dev context...\n");
if (strncmp(Strings::CustomContext.c_str(), "/dev", 4) != 0)
{
if (!Booleans::ForceMode)
LOGE("%s\n", Display::UsingDispString->not_in_dev);
}
VLOGD("The specified custom /dev context is being put in countless...\n");
SearchResult = Functions::GetState(Strings::CustomContext, "dir");
if (SearchResult == 1)
LOGE("%s: `%s': %s\n", Display::UsingDispString->cannot_stat, Strings::CustomContext.c_str(), strqerror());
else if (SearchResult == -1)
LOGE("`%s': %s\n", Strings::CustomContext.c_str(), Display::UsingDispString->not_dir);
}
VLOGD("The partition specification status is controlled...\n");
if (Strings::TargetPartition.empty())
{
if (!Booleans::ForceMode)
LOGE("%s\n%s `%s --help' %s\n", Display::UsingDispString->req_part_name, Display::UsingDispString->try_h, Strings::ExecutingName.c_str(), Display::UsingDispString->for_more);
}
else
{
VLOGD("The call of main operations is being checked in case of the call...\n");
if (!Target.empty())
Base->CallTargetBaseFunction();
}
}
/* end of code */

52
jni/PartitionTool.cpp Executable file
View File

@@ -0,0 +1,52 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#include <PartitionManager/PartitionManager.h>
using namespace PartitionManager;
static bool
accf(const string fp)
{
VLOGD("accf <local function>: trying to access `%s' with 'access <unistd.h>'\n", fp.c_str());
return (access(fp.c_str(), F_OK) == 0) ? true : false;
}
/* check parts */
void Functions::CheckDevPoint(void)
{
VLOGD("CheckDevPoint: selecting context...\n");
string dpoint = (Booleans::UseCustomContext) ? Strings::CustomContext : "/dev/block/by-name";
/* true = ab | false = a only */
Booleans::UsesSlots = (accf(dpoint + "/boot_a")) ? true : false;
if (Booleans::UsesSlots)
VLOGW("CheckDevPoint: 1 warning generated: A/B status.\n");
/* true = logical | false = normal */
Booleans::UsesLogical = (accf(dpoint + "/super")) ? true : false;
if (Booleans::UsesLogical)
VLOGW("CheckDevPoint: 1 warning generated: logical partitions status.\n");
}
/* end of code */

View File

@@ -16,26 +16,22 @@
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_STRINGKEYS
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#include <PartitionManager/PartitionManager.h>
/* root checker function */
void check_root(void)
void PartitionManager::Functions::CheckRoot(void)
{
/* a quick, easy method for verifying root */
if (getuid() != 0)
LOGE("%s\n", current->no_root);
}
VLOGD("CheckRoot: trying to get UID with 'getuid <unistd.h>'\n");
#ifdef __cplusplus
if (getuid() != 0)
{
VLOGE("CheckRoot: cannot get UID. Not executed with root!\n");
LOGE("%s\n", PartitionManager::Display::UsingDispString->no_root);
}
}
#endif /* __cplusplus */
/* end of code */

243
jni/Tools.cpp Executable file
View File

@@ -0,0 +1,243 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_STAT
#define INC_DEBUGERS
#define INC_TOOLS_REQS
#define INC_STRINGKEYS
#include <PartitionManager/PartitionManager.h>
namespace PartitionManager {
namespace Functions {
/**
* it is meant to calculate the size of the quickly given file.
* its purpose is for rapid processing
*/
static double
CalculateSizeDouble(const string& fp)
{
VLOGD("CalculateSizeDouble: calculating file size: `%s'\n", fp.c_str());
VLOGD("CalculateSizeDouble: reading `%s' with 'ifstream <fstream>'\n", fp.c_str());
ifstream target(fp, ios::binary | ios::ate);
return (!target) ? -1 : static_cast<double>(target.tellg()) / (1024 * 1024);
}
static long long
CalculateSizeLongLong(const string& fp)
{
VLOGD("CalculateSizeLongLong: calculating file size: `%s'\n", fp.c_str());
VLOGD("CalculateSizeLongLong: reading `%s' with 'ifstream <fstream>'\n", fp.c_str());
ifstream target(fp, ios::binary | ios::ate);
return (!target) ? -1 : static_cast<long long>(target.tellg());
}
/**
* error that the partition is not found.
* It's for quick action.
*/
static void
PartitionNotFound(const char* p) { LOGE("`%s': %s\n", p, Display::UsingDispString->part_not_found); }
/* the partitions are meant to quickly find. */
static void
SearchPartition(const string& fp)
{
VLOGD("SearchPartition: calling GetState()...\n");
static int op = GetState(fp, "blk");
if (op == 1)
PartitionNotFound(fp.c_str());
else if (op == -1 && !Booleans::ForceMode)
LOGE("%s\n", Display::UsingDispString->not_block);
}
} /* namespace Functions */
} /* namespace PartitionNotFound */
using namespace PartitionManager;
/* to stop use of function type */
#define PartitionNotFound Functions::PartitionNotFound()
int Functions::Start(unsigned short progress_code)
{
/* required variables */
static fstream sourceF;
static fstream targetF;
static string accessPrefix;
static string opName;
static int BFSIZE = 1;
static char formatterCmd[200];
static long long copiedData = 0;
if (Booleans::UseLogical)
accessPrefix = "/dev/block/mapper/" + Strings::TargetPartition;
else
accessPrefix = (Booleans::UseCustomContext) ? (Strings::CustomContext) + ("/") + (Strings::TargetPartition) : ("/dev/block/by-name/") + (Strings::TargetPartition);
VLOGD("PartitionManager: calling SearchPartition() for searching partition (path); `%s'\n", accessPrefix.c_str());
Functions::SearchPartition(accessPrefix);
static long long count = (long long)(CalculateSizeLongLong(accessPrefix) + ((1024 * 1024) * 10));
BFSIZE = (int)(CalculateSizeLongLong(accessPrefix) / (10240 * 10240));
if (BFSIZE < 1)
BFSIZE = 1;
const int bfsize = BFSIZE;
char buffer[bfsize];
VLOGD("PartitionManager: calculating sizes...\n");
double partition_size = Functions::CalculateSizeDouble(accessPrefix);
double flashfile_size;
if (!Strings::TargetFlashFile.empty())
flashfile_size = Functions::CalculateSizeDouble(Strings::TargetFlashFile);
if (progress_code < 3)
{
if (partition_size != -1)
LOGD("%s: %.2fM\n", Display::UsingDispString->part_disk_sz, partition_size);
else
LOGW("%s\n", Display::UsingDispString->part_disk_sz_fail);
}
if (progress_code == 1)
{
VLOGD("PartitionManager: trying to open `%s' with 'open <fstream>'.\n", accessPrefix.c_str());
sourceF.open(accessPrefix, ios::binary | ios::in);
if (!sourceF.is_open())
LOGE("%s: %s: %s\n", Display::UsingDispString->not_read, accessPrefix.c_str(), strqerror());
/* determine output */
if (Strings::OutputName == Strings::TargetPartition)
{
opName = Strings::OutputName + ".img";
VLOGW("PartitionManager: output not speficed. Selecting automaticly.\n");
LOGW("%s: %s\n", Display::UsingDispString->out_not_spec, opName.c_str());
}
else
opName = Strings::OutputName;
VLOGD("Checking output status...\n");
if (GetState(opName) == 0)
LOGE("`%s': File exits.\n", opName.c_str());
VLOGD("PartitionManager: trying to open `%s' with 'open <fstream>'.\n", opName.c_str());
targetF.open(opName, ios::binary | ios::out);
if (!targetF.is_open())
LOGE("%s: %s: %s\n", Display::UsingDispString->not_gen, opName.c_str(), strqerror());
VLOGD("PartitionManager: read (partition) and write (output) 'read, write <fstream>'\n");
/* start writing */
while (sourceF.read(buffer, bfsize) && copiedData < count)
{
streamsize readed_data = sourceF.gcount();
targetF.write(buffer, readed_data);
if (targetF.fail())
{
if (Functions::GetState(opName) == 0)
remove(opName.c_str());
LOGF("%s: %s: %s\n", Display::UsingDispString->not_write, opName.c_str(), strqerror());
}
copiedData += readed_data;
}
/* close files */
sourceF.close();
targetF.close();
LOGD("%s: %s\n", Display::UsingDispString->success_backup, opName.c_str());
}
else if (progress_code == 2)
{
if (flashfile_size != -1)
LOGD("%s: %.2fM\n", Display::UsingDispString->flash_file_sz, flashfile_size);
else
LOGW("%s\n", Display::UsingDispString->flash_file_sz_fail);
if (partition_size != -1 && flashfile_size != -1)
{
if (flashfile_size > partition_size && !Booleans::ForceMode)
LOGE("%s\n", Display::UsingDispString->ffile_more_part);
}
VLOGD("PartitionManager: trying to open `%s' with 'open <fstream>'.\n", Strings::TargetFlashFile.c_str());
sourceF.open(Strings::TargetFlashFile, ios::binary | ios::in);
if (!sourceF.is_open())
LOGF("%s: %s: %s\n", Display::UsingDispString->not_read, Strings::TargetFlashFile.c_str(), strqerror());
VLOGD("PartitionManager: trying to open `%s' with 'open <fstream>'.\n", accessPrefix.c_str());
targetF.open(accessPrefix, ios::binary | ios::in | ios::out | ios::trunc);
if (!targetF.is_open())
LOGF("%s: %s: %s\n", Display::UsingDispString->not_read, accessPrefix.c_str(), strqerror());
VLOGD("PartitionManager: read (flash file) and write (partition) 'read, write <fstream>'\n");
/* start writing */
while (sourceF.read(buffer, bfsize) && copiedData < count)
{
streamsize readed_data = sourceF.gcount();
targetF.write(buffer, readed_data);
if (targetF.fail())
LOGF("%s: %s: %s\n", Display::UsingDispString->not_write, accessPrefix.c_str(), strqerror());
copiedData += readed_data;
}
sourceF.close();
targetF.close();
LOGD("%s.\n", Display::UsingDispString->success_flash);
}
else if (progress_code == 3)
{
/* get target partition block size */
VLOGD("PartitionManager: getting block size `%s' with 'statvfs <sys/statvfs.h>'\n", accessPrefix.c_str());
struct statvfs file_sys_inf;
if (statvfs(accessPrefix.c_str(), &file_sys_inf) != 0)
LOGE("%s\n", Display::UsingDispString->cannot_get_bsz);
/* generate mke2fs command */
VLOGD("PartitionManager: generating command...\n");
sprintf(formatterCmd, "/system/bin/mke2fs -Fq -t %s -b %lu %s &>/data/local/tmp/mke2fs", Strings::TargetFormatFS.c_str(), file_sys_inf.f_bsize, accessPrefix.c_str());
LOGD("%s: `%s'. %s: %s\n", Display::UsingDispString->formatting, accessPrefix.c_str(), Display::UsingDispString->fs_str, Strings::TargetFormatFS.c_str());
/* run command */
VLOGD("PartitionManager: executing command: \"%s\"\n", formatterCmd);
if (system(formatterCmd) != 0)
LOGF("%s\n", Display::UsingDispString->format_fail);
LOGD("%s.\n", Display::UsingDispString->success_format);
}
return 0;
}
/* end of code */

54
jni/Version.cpp Executable file
View File

@@ -0,0 +1,54 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define INC_MAIN_LIBS
#define INC_STRINGKEYS
#define VERSIONING
#include <PartitionManager/PartitionManager.h>
#include <PartitionManager/VersionFnVars.h>
using namespace PartitionManager;
void Functions::DisplayVersion(void)
{
VLOGD("DisplayVersion: printing main info...\n");
LOGD("%s %s %d.%d.%d (C++) (%d%d%d) ", Strings::ExecutingName.c_str(), Display::UsingDispString->version_str, PMT_MAJOR, PMT_MINOR, PMT_PATCHLEVEL, PMT_MAJOR, PMT_MINOR, PMT_PATCHLEVEL);
#if __SIZEOF_POINTER__ == 4
LOGD("32-bit %s\n", Display::UsingDispString->bin_str);
#elif __SIZEOF_POINTER__ == 8
LOGD("64-bit %s\n", Display::UsingDispString->bin_str);
#else
LOGD("<%s> %s\n", Display::UsingDispString->unknw_str, Display::UsingDispString->bin_str);
#endif
VLOGD("DisplayVersion: build type: ");
#if defined(__clang__) && !defined(__NDK_BUILD)
if (Booleans::VerboseMode)
printf("clang (manual).\n");
LOGD("%s: clang %d.%d.%d\n", Display::UsingDispString->compiler_str, __clang_major__, __clang_minor__, __clang_patchlevel__);
#elif defined(__NDK_BUILD)
if (Booleans::VerboseMode)
printf("NDK.\n");
LOGD("%s\n", __NDK_CXX_VERSION__);
#endif
}
/* end of code */

View File

@@ -1,71 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
void debug(LogLevel status, const char* _Nullable fmt, ...)
{
va_list args;
va_start(args, fmt);
switch (status)
{
case LOG_LEVEL_ERR:
if (!pmt_silent)
{
fprintf(stderr, "%s: ", bin_name);
vfprintf(stderr, fmt, args);
}
exit(1);
break;
case LOG_LEVEL_WARN:
if (!pmt_silent)
{
fprintf(stderr, "%s: ", current->warn);
vfprintf(stderr, fmt, args);
}
break;
case LOG_LEVEL_FATAL:
if (!pmt_silent)
{
fprintf(stderr, "%s: ", current->fatal);
vfprintf(stderr, fmt, args);
}
abort();
break;
case LOG_LEVEL_DEBUG:
if (!pmt_silent)
vfprintf(stdout, fmt, args);
break;
}
va_end(args);
}
#ifdef __cplusplus
}
#endif
/* end of code */

View File

@@ -1,71 +0,0 @@
/* By YZBruh */
/*
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define HELP
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#include <pmt/HelpMessages.h>
extern char* bin_name;
extern char* curr_lang;
struct pmt_langdb_docs* curr_docs = NULL;
static void
prepare_langconf_docs(void)
{
if (strcmp(curr_lang, "en") == 0)
curr_docs = &en_docs;
else if (strcmp(curr_lang, "tr") == 0)
curr_docs = &tr_docs;
}
void help(void)
{
prepare_langconf_docs();
printf("%s: %s %s\n", curr_docs->usage_docstr, bin_name, curr_docs->docs_strs_l1);
printf(" %s: %s %s\n", curr_docs->or_str, bin_name, curr_docs->docs_strs_l2);
printf(" %s: %s %s\n\n", curr_docs->or_str, bin_name, curr_docs->docs_strs_l3);
printf("%s: \n", curr_docs->docs_strs_l4);
printf(" -l, --logical %s\n", curr_docs->docs_strs_l5);
printf(" -c, --context %s\n", curr_docs->docs_strs_l6);
printf(" -p, --list %s\n", curr_docs->docs_strs_l7);
printf(" -s, --silent %s\n", curr_docs->docs_strs_l8);
printf(" -f, --force %s\n", curr_docs->docs_strs_l9);
printf(" -S, --set-lang %s\n", curr_docs->docs_strs_l10);
printf(" -v, --version %s\n", curr_docs->docs_strs_l11);
printf(" --help %s\n\n", curr_docs->docs_strs_l12);
printf("%s:\n", curr_docs->docs_strs_l13);
printf(" %s backup boot_a -c /dev/block/platform/bootdevice/by-name\n", bin_name);
printf(" %s flash boot_a /sdcard/twrp/boot.img -c /dev/block/platform/bootdevice/by-name\n", bin_name);
printf(" %s format system_a ext4 --logical\n", bin_name);
printf(" %s -c /dev/block/platform/bootdevice/by-name --list\n\n", bin_name);
printf("%s <t.me/ShawkTeam | Topics | pmt>\n", curr_docs->docs_strs_l14);
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
/* end of code */

View File

@@ -1,165 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_STAT
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
/* pmt's man doc file path on termux */
#define TERMUX_PMT_MANDOC "/data/data/com.termux/files/usr/share/man/man8/pmt.8.gz"
#define PMTLANG_CONF "/sdcard/.pmtlang.conf"
#define PMT_SW_POINT "/sdcard/.pmtlangsw"
extern struct pmt_langdb_langs lang[];
struct pmt_langdb_general* current = NULL;
char* curr_lang;
static FILE *langconf;
static const char*
langctrl(const char* _Nonnull lang_)
{
for (int langct = 0; lang[langct].lang_pr != NULL; langct++)
{
if (strcmp(lang_, lang[langct].lang_pr) == 0)
return lang_;
}
return NULL;
}
int loadlang(void)
{
static char lang_fpr[3] = "en";
langconf = NULL;
if (get_stat(TERMUX_PMT_MANDOC, "file") == 0)
pmt_inst_on_termux = true;
langconf = fopen(PMTLANG_CONF, "r+");
if (langconf == NULL)
{
langconf = fopen(PMTLANG_CONF, "w+");
if (langconf == NULL || langconf != NULL)
{
setlang("en", 1);
current = &en;
curr_lang = "en";
if (langconf != NULL)
fclose(langconf);
return 0;
}
}
else
{
while (fgets(lang_fpr, sizeof(lang_fpr), langconf) != NULL)
{
if (strcmp(lang_fpr, "en") == 0)
{
fclose(langconf);
current = &en;
curr_lang = "en";
return 0;
}
else if (strcmp(lang_fpr, "tr") == 0)
{
fclose(langconf);
current = &tr;
curr_lang = "tr";
return 0;
}
else
{
fclose(langconf);
setlang("en", 0);
loadlang();
return 0;
}
}
if (fgets(lang_fpr, sizeof(lang_fpr), langconf) == NULL)
{
setlang("en", 1);
loadlang();
return 0;
}
}
return 1;
}
void setlang(const char* _Nonnull lang, int null_conf_stat)
{
if (langctrl(lang) == NULL)
LOGE("Unknown language: %s.\n", lang);
if (get_stat(PMTLANG_CONF, "file") == 0)
remove(PMTLANG_CONF);
langconf = NULL;
langconf = fopen(PMTLANG_CONF, "w");
if (langconf == NULL)
LOGE("Failed!!! Cannot open/write config file.\n");
if (fprintf(langconf, "%s", lang) < 2)
LOGE("Failed!!! Couldn't write config!\n");
else
fclose(langconf);
static int status;
if (null_conf_stat != 1)
{
status = open(PMT_SW_POINT, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (status == 0)
close(status);
}
}
int search_sls(void)
{
if (get_stat(PMT_SW_POINT, "file") == 0)
{
remove(PMT_SW_POINT);
return 0;
}
else
return 1;
}
#ifdef __cplusplus
}
#endif
/* end of code */

View File

@@ -1,127 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_DIRENT
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
/* current /dev context */
#define CUR_DEV_CNTX "/dev/block/by-name"
/* for logical partitions */
#define LGC_DEV_CNTX "/dev/block/mapper"
static DIR *dir;
static int
list(const char* operation, const char* target_dir)
{
static bool list = false;
static int count;
struct dirent **nlist;
dir = NULL;
if (strcmp(operation, "access") == 0)
list = false;
else if (strcmp(operation, "print") == 0)
list = true;
else
return -1;
dir = opendir(target_dir);
if (dir != NULL)
{
closedir(dir);
return 0;
}
else
return -1;
if (list)
{
count = scandir(target_dir, &nlist, NULL, alphasort);
if (count < 0)
LOGE("%s: `%s': %s\n", current->not_readdir, target_dir, strerror(errno));
for (int cont_count = 0; cont_count < count; cont_count++)
{
if (nlist[cont_count]->d_name[0] != '.')
LOGD("%s\n", nlist[cont_count]->d_name);
free(nlist[cont_count]);
}
free(nlist);
return 0;
}
return 2;
}
/* list existing partitions */
int listpart(void)
{
static char acc_cxt[350];
if (pmt_use_cust_cxt)
sprintf(acc_cxt, "%s", cust_cxt);
else
sprintf(acc_cxt, "%s", CUR_DEV_CNTX);
if (list("access", acc_cxt) != 0)
{
if (!pmt_force_mode)
LOGE("%s: `%s': %s\n", current->not_open, acc_cxt, strerror(errno));
else
return 1;
}
else
list("print", acc_cxt);
if (pmt_logical)
{
if (list("access", LGC_DEV_CNTX) != 0)
LOGE("%s: `%s': %s\n", current->not_open, LGC_DEV_CNTX, strerror(errno));
else
list("print", LGC_DEV_CNTX);
}
if (pmt_ab)
LOGD("%s: %s\n", bin_name, current->ab_warn);
if (pmt_logical)
LOGD("%s: %s\n", bin_name, current->logical_warn);
return 0;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
/* end of code */

View File

@@ -1,76 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#include <pmt/PartitionManager.h>
static int
accf(const char* _Nonnull target) { return access(target, F_OK); }
/* check parts */
void check_dev_point(void)
{
/* true = ab | false = a */
if (pmt_use_cust_cxt)
{
static char cust_cxt_ck_path[150];
sprintf(cust_cxt_ck_path, "%s/boot_a", cust_cxt);
if (accf(cust_cxt_ck_path) != 0)
pmt_ab = false;
else
pmt_ab = true;
}
else
{
if (accf("/dev/block/by-name/boot_a") != 0)
pmt_ab = false;
else
pmt_ab = true;
}
/* true = logical | false = classic */
if (pmt_use_cust_cxt)
{
static char cust_cxt_ckl_path[150];
sprintf(cust_cxt_ckl_path, "%s/super", cust_cxt);
if (accf(cust_cxt_ckl_path) != 0)
pmt_logical = false;
else
pmt_logical = true;
}
else
{
if (accf("/dev/block/by-name/super") != 0)
pmt_logical = false;
else
pmt_logical = true;
}
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
/* end */

407
jni/pmt.c
View File

@@ -1,407 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* force use C std (if default is C++) */
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define INC_DEBUGERS
#define INC_STAT
#define INC_GETOPT
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#include <pmt/Deprecates.h>
#include <pmt/HelpMessages.h>
#define opt_symbol "-"
/* add value to variables that are added globally and are not worth */
char* out = NULL;
char* cust_cxt = NULL;
char* target_partition = NULL;
char* target_flash_file = NULL;
char* partition_type = NULL;
char* format_fs = NULL;
char* bin_name = NULL;
bool pmt_use_logical = false;
bool pmt_use_cust_cxt = false;
bool pmt_ab = false;
bool pmt_logical = false;
bool pmt_silent = false;
bool pmt_flash = false;
bool pmt_backup = false;
bool pmt_format = false;
bool pmt_force_mode = false;
bool pmt_inst_on_termux = false;
/* variable for use in control of '-' expression */
static char common_symbol_rule[350];
/**
* He controls whether the '-' sign at
* the beginning of the given word
*/
static void
check_optsym(const char* _Nullable symbol)
{
if (symbol != NULL)
{
if (strncmp(symbol, opt_symbol, 1) == 0)
LOGE("%s\n", common_symbol_rule);
}
}
static bool
ctrl_arg(const char* _Nullable argv_holder)
{
if (strcmp(argv_holder, "--logical") != 0 && strcmp(argv_holder, "--context") != 0 && strcmp(argv_holder, "--silent") != 0 && strcmp(argv_holder, "-l") != 0 && strcmp(argv_holder, "-c") != 0 && strcmp(argv_holder, "-s") != 0)
return true;
return false;
}
/* classic main function (C binary here xd) */
int main(int argc, char** argv)
{
bin_name = argv[0];
int argc_n = argc;
char buf[256];
char** args = malloc((argc + 1) * sizeof(char *));
/* copy original arguments */
for (int i = 0; i < argc; i++)
args[i] = argv[i];
if (!isatty(fileno(stdin)))
{
while (fgets(buf, sizeof(buf), stdin) != NULL)
{
buf[strcspn(buf, "\n")] = 0;
args = realloc(args, (argc_n + 1) * sizeof(char *));
args[argc_n] = strdup(buf);
argc_n++;
}
}
argc = argc_n;
/* load language */
if (loadlang() != 0)
{
printf("loadlang fail\n");
exit(1);
}
sprintf(common_symbol_rule, "%s", current->common_symbol_rule);
if (search_sls() == 0)
{
if (current->welcome_ != NULL)
LOGD("%s", current->welcome_);
LOGD("%s %s %s %s.\n", current->language, current->welcome, current->by_str, current->lang_by_s);
}
/* check argument total */
if (argc < 2)
LOGE("%s.\n%s `%s --help' %s.\n", current->missing_operand, current->try_h, args[0], current->for_more);
/* a structure for long arguments */
struct option option_table[] = {
{"backup", no_argument, 0, 'b'},
{"flash", no_argument, 0, 'F'},
{"format", no_argument, 0, 'r'},
{"is_dummy", no_argument, 0, 'D'},
{"logical", no_argument, 0, 'l'},
{"context", required_argument, 0, 'c'},
{"list", no_argument, 0, 'p'},
{"silent", no_argument, 0, 's'},
{"force", no_argument, 0, 'f'},
{"set-language", required_argument, 0, 'S'},
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 0},
{"license", no_argument, 0, 'L'},
{0, 0, 0, 0}
};
/* boolean statements (only valid in this file) to distinguish. and pointer from a shortcut for the symbol rule */
static bool wiew_help = false;
static bool wiew_version = false;
static bool logical_spec = false;
static bool list_partitions = false;
static bool combo_wiewers = false;
static bool pmt_setlang = false;
static char* langpr;
static int search_result = 3;
static int opt;
if (strcmp(args[1], "backup") == 0)
{
if (argc <= 2)
LOGE("%s 0.\n", current->expected_backup_arg);
if (ctrl_arg(args[2]))
target_partition = args[2];
else
LOGE("%s.\n", current->not_spec_opt);
out = target_partition;
if (argc > 3 && ctrl_arg(args[3]))
out = args[3];
check_optsym(target_partition);
check_optsym(out);
pmt_backup = true;
}
else if (strcmp(args[1], "flash") == 0)
{
if (argc <= 2)
LOGE("%s 0.\n", current->expected_flash_arg);
if (argc <= 3)
LOGE("%s 1.\n", current->expected_flash_arg);
if (ctrl_arg(args[2]))
target_partition = args[2];
else
LOGE("%s.\n", current->not_spec_opt);
if (ctrl_arg(args[3]))
target_flash_file = args[3];
else
LOGE("%s.\n", current->not_spec_opt);
check_optsym(target_flash_file);
check_optsym(target_partition);
pmt_flash = true;
}
else if (strcmp(args[1], "format") == 0)
{
if (argc <= 2)
LOGE("%s 0.\n", current->expected_format_arg);
if (argc <= 3)
LOGE("%s 1.\n", current->expected_format_arg);
if (ctrl_arg(args[2]))
target_partition = args[2];
else
LOGE("%s.\n", current->not_spec_opt);
if (ctrl_arg(args[3]))
format_fs = args[3];
else
LOGE("%s.\n", current->not_spec_opt);
check_optsym(format_fs);
check_optsym(target_partition);
pmt_format = true;
}
/* control for each argument */
while ((opt = getopt_long(argc, args, "bFrDlc:psfS:vL", option_table, NULL)) != -1)
{
/* process arguments */
switch (opt)
{
/* handle deprecates */
case 'b':
DEPR_HANDLE('b', "backup", current->depr_backup_opt);
exit(1);
break;
case 'F':
DEPR_HANDLE('F', "flash", current->depr_flash_opt);
exit(1);
break;
case 'r':
DEPR_HANDLE('r', "format", current->depr_format_opt);
exit(1);
break;
case 'D':
DEPR_HANDLE('D', "NULLPTR", current->depr_ch_list_opt);
exit(1);
break;
case 'L':
DEPR_HANDLE('L', "license", current->depr_Vlicense_opt);
exit(1);
break;
/* logical partitions option */
case 'l':
logical_spec = true;
break;
/* context selector option */
case 'c':
pmt_use_cust_cxt = true;
cust_cxt = strdup(optarg);
check_optsym(cust_cxt);
break;
/* partition lister function */
case 'p':
list_partitions = true;
/* check combo wiewer options and progress */
if (wiew_version || wiew_help) combo_wiewers = true;
break;
/* force mode option */
case 'f':
pmt_force_mode = true;
break;
/* silent mode option */
case 's':
pmt_silent = true;
break;
/* language setter option */
case 'S':
pmt_setlang = true;
langpr = strdup(optarg);
break;
/* version info option */
case 'v':
wiew_version = true;
/* check combo wiewer options and progress */
if (list_partitions || wiew_help) combo_wiewers = true;
break;
/* help message opption */
case 0:
wiew_help = true;
/* check combo wiewer options and progress */
if (wiew_version || list_partitions) combo_wiewers = true;
break;
/* for invalid options */
case '?':
LOGD("%s `%s --help' %s\n", current->try_h, args[0], current->for_more);
return 1;
break;
default:
LOGD("%s: %s [backup] [flash] [format] [-l | --logical] [-c | --context] [-p | --list] [-s | --silent] [-v | --version] [--help]\n", current->usage_head, args[0]);
return 1;
}
}
/* stop the program if multiple viewer is used */
if (combo_wiewers)
LOGE("%s", current->multiple_wiewers);
/* controller to handle viewer */
if (wiew_help)
{
help();
return 0;
}
else if (wiew_version)
{
version();
return 0;
}
else if (list_partitions)
{
check_root();
return listpart();
}
if (pmt_setlang)
{
LOGD("%s: %s\n", args[0], current->switching_lang);
setlang(langpr, 0);
sleep(2);
LOGD("%s: %s.\n", args[0], current->please_rerun);
return 0;
}
if (!pmt_backup && !pmt_flash && !pmt_format)
LOGE("%s.\n%s `%s --help` %s\n", current->no_target, current->try_h, args[0], current->for_more);
if (pmt_format)
{
if (strcmp(format_fs, "ext4") != 0 && strcmp(format_fs, "ext3") != 0 && strcmp(format_fs, "ext2") != 0)
LOGE("%s: %s\n", current->unsupported_fs, format_fs);
}
/* checks */
check_root();
check_dev_point();
if (logical_spec)
{
if (pmt_logical)
pmt_use_logical = true;
else
LOGE("%s\n", current->not_logical);
}
if (pmt_flash)
{
search_result = get_stat(target_flash_file, "file");
if (search_result == 1)
LOGE("%s `%s': %s\n", current->cannot_stat, target_flash_file, strerror(errno));
else if (search_result == -1)
LOGE("`%s': %s\n", target_flash_file, current->not_file);
}
/* custom context checker */
if (pmt_use_cust_cxt)
{
search_result = get_stat(cust_cxt, "dir");
if (search_result == 1)
LOGE("%s `%s': %s\n", current->cannot_stat, cust_cxt, strerror(errno));
else if (search_result == -1)
LOGE("`%s': %s\n", cust_cxt, current->not_dir);
if (strstr(cust_cxt, "/dev") == NULL && !pmt_force_mode)
LOGE("%s\n", current->not_in_dev);
}
if (target_partition == NULL)
{
if (!pmt_force_mode)
LOGE("%s\n%s `%s --help' %s\n", current->req_part_name, current->try_h, args[0], current->for_more);
}
else
{
/**
* 1 = backup mode
*
* 2 = flash mode
*
* 3 = format
*/
if (pmt_backup)
return pmt(1);
else if (pmt_flash)
return pmt(2);
else if (pmt_format)
return pmt(3);
}
}
#ifdef __cplusplus
}
#endif
/* end of code */

View File

@@ -1,210 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define BFSIZE 1024
#define INC_MAIN_LIBS
#define INC_STAT
#define INC_DEBUGERS
#define INC_TOOLS_REQS
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#define count (1024 * 1024 * 1024)
/**
* it is meant to calculate the size of the quickly given file.
* its purpose is for rapid processing
*/
static double
calc_flsz(const char* _Nonnull filepath)
{
static int calc_flsz_file;
calc_flsz_file = open(filepath, O_RDONLY);
if (calc_flsz_file == -1)
return calc_flsz_file;
static off_t flsz;
flsz = lseek(calc_flsz_file, 0, SEEK_END);
close(calc_flsz_file);
if (flsz == (off_t)-1)
return -1;
return (double)flsz / (1024 * 1024);
}
/**
* error that the partition is not found.
* It's for quick action.
*/
static void
partition_not_found(void) { LOGE("%s\n", current->part_not_found); }
/* to stop use of function type */
#define partition_not_found partition_not_found()
/* the partitions are meant to quickly find. */
static void
search_partition(const char* _Nonnull partition)
{
static int partition_results = 0;
partition_results = get_stat(partition, "blk");
if (partition_results == 1)
partition_not_found;
else if (partition_results == -1)
LOGE("%s\n", current->not_block);
}
int pmt(unsigned short progress_code)
{
/* required variables */
static int srcf, targetf;
static char acc_part_path[512];
static char formatter_cmd[200];
static char outf[512];
static char buffer[BFSIZE];
static ssize_t readed_data;
static unsigned long long copied_data = 0;
if (pmt_use_logical)
sprintf(acc_part_path, "/dev/block/mapper/%s", target_partition);
else
{
if (pmt_use_cust_cxt)
sprintf(acc_part_path, "%s/%s", cust_cxt, target_partition);
else
sprintf(acc_part_path, "/dev/block/by-name/%s", target_partition);
}
search_partition(acc_part_path);
if (progress_code == 1)
{
if (calc_flsz(acc_part_path) != -1)
LOGD("%s: %.2fM\n", current->part_disk_sz, calc_flsz(acc_part_path));
else
LOGW("%s\n", current->part_disk_sz_fail);
srcf = open(acc_part_path, O_RDONLY);
if (srcf == -1)
LOGE("%s: %s: %s\n", current->not_read, acc_part_path, strerror(errno));
/* determine output */
if (strcmp(out, target_partition) == 0)
{
sprintf(outf, "%s.img", out);
LOGW("%s: %s\n", current->out_not_spec, outf);
}
else
sprintf(outf, "%s", out);
targetf = open(outf, O_WRONLY | O_CREAT | O_TRUNC, 0660);
if (targetf == -1)
LOGE("%s: %s: %s\n", current->not_gen, outf, strerror(errno));
/* start writing */
while ((readed_data = read(srcf, buffer, BFSIZE)) > 0 && copied_data < count)
{
ssize_t writed_data = write(targetf, buffer, readed_data);
if (writed_data != readed_data)
{
if (get_stat(outf, "file") == 0)
remove(outf);
LOGF("%s: %s: %s\n", current->not_write, acc_part_path, strerror(errno));
}
copied_data += writed_data;
}
/* close files */
close(srcf);
close(targetf);
LOGD("%s: %s\n", current->success_backup, outf);
}
else if (progress_code == 2)
{
if (calc_flsz(target_flash_file) != -1)
LOGD("%s: %.2fM\n", current->flash_file_sz, calc_flsz(target_flash_file));
else
LOGW("%s\n", current->flash_file_sz_fail);
if (calc_flsz(acc_part_path) != -1)
LOGD("%s: %.2fM\n", current->part_disk_sz, calc_flsz(acc_part_path));
else
LOGW("%s\n", current->part_disk_sz_fail);
if (calc_flsz(target_flash_file) != -1 && calc_flsz(acc_part_path) != -1)
{
if (calc_flsz(target_flash_file) > calc_flsz(acc_part_path))
LOGE("%s\n", current->ffile_more_part);
}
srcf = open(target_flash_file, O_RDONLY);
if (srcf == -1)
LOGF("%s: %s: %s\n", current->not_read, target_flash_file, strerror(errno));
targetf = open(acc_part_path, O_WRONLY | O_CREAT | O_TRUNC, 0660);
if (targetf == -1)
LOGF("%s: %s: %s\n", current->not_read, acc_part_path, strerror(errno));
/* start writing */
while ((readed_data = read(srcf, buffer, BFSIZE)) > 0 && copied_data < count)
{
ssize_t writed_data = write(targetf, buffer, readed_data);
if (writed_data != readed_data)
LOGF("%s: %s: %s\n", current->not_write, acc_part_path, strerror(errno));
copied_data += writed_data;
}
close(srcf);
close(targetf);
LOGD("%s.\n", current->success_flash);
}
else if (progress_code == 3)
{
/* get target partition block size */
struct statvfs file_sys_inf;
if (statvfs(acc_part_path, &file_sys_inf) != 0)
LOGE("%s\n", current->cannot_get_bsz);
/* generate mke2fs command */
sprintf(formatter_cmd, "mke2fs -Fq -t %s -b %lu %s", format_fs, file_sys_inf.f_bsize, acc_part_path);
/* run command */
if (system(formatter_cmd) != 0)
LOGF("%s\n", current->format_fail);
}
return 0;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
/* end of code */

View File

@@ -1,53 +0,0 @@
/* By YZBruh */
/**
* Copyright 2024 Partition Manager
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef __cplusplus
extern "C" {
#endif
#define INC_MAIN_LIBS
#define VERSIONING
#include <pmt/PartitionManager.h>
#include <pmt/StringKeys.h>
#include <pmt/VersionVars.h>
void version(void)
{
LOGD("%s %s %d.%d.%d (%d%d%d) ", bin_name, current->version_str, PMT_MAJOR, PMT_MINOR, PMT_PATCHLEVEL, PMT_MAJOR, PMT_MINOR, PMT_PATCHLEVEL);
#if __SIZEOF_POINTER__ == 4
LOGD("32-bit %s\n", current->bin_str);
#elif __SIZEOF_POINTER__ == 8
LOGD("64-bit %s\n", current->bin_str);
#else
LOGD("<%s> %s\n", current->unknw_str, current->bin_str);
#endif
#if defined(__clang__) && !defined(__NDK_BUILD)
LOGD("%s: clang %d.%d.%d\n", current->compiler_str, __clang_major__, __clang_minor__, __clang_patchlevel__);
#elif defined(__NDK_BUILD)
LOGD("%s\n", __NDK_CC_VERSION__);
#endif
}
#ifdef __cplusplus
}
#endif
/* end of code */