CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
Ardupilot

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: Ardupilot/ardupilot
Path: blob/master/libraries/AP_Filesystem/AP_Filesystem_backend.cpp
Views: 1798
1
/*
2
This program is free software: you can redistribute it and/or modify
3
it under the terms of the GNU General Public License as published by
4
the Free Software Foundation, either version 3 of the License, or
5
(at your option) any later version.
6
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
11
12
You should have received a copy of the GNU General Public License
13
along with this program. If not, see <http://www.gnu.org/licenses/>.
14
*/
15
16
#include <AP_HAL/AP_HAL.h>
17
#include "AP_Filesystem.h"
18
19
extern const AP_HAL::HAL& hal;
20
21
/*
22
Load a file's contents into memory. Returned object must be `delete`d to free
23
the data. The data is guaranteed to be null-terminated such that it can be
24
treated as a string.
25
*/
26
FileData *AP_Filesystem_Backend::load_file(const char *filename)
27
{
28
struct stat st;
29
if (stat(filename, &st) != 0) {
30
return nullptr;
31
}
32
FileData *fd = NEW_NOTHROW FileData(this);
33
if (fd == nullptr) {
34
return nullptr;
35
}
36
// add one byte for null termination; ArduPilot's malloc will zero it.
37
void *data = malloc(st.st_size+1);
38
if (data == nullptr) {
39
delete fd;
40
return nullptr;
41
}
42
int d = open(filename, O_RDONLY);
43
if (d == -1) {
44
free(data);
45
delete fd;
46
return nullptr;
47
}
48
if (read(d, data, st.st_size) != st.st_size) {
49
close(d);
50
free(data);
51
delete fd;
52
return nullptr;
53
}
54
close(d);
55
fd->length = st.st_size; // length does not include our added termination
56
fd->data = (const uint8_t *)data;
57
return fd;
58
}
59
60
/*
61
unload a FileData object
62
*/
63
void AP_Filesystem_Backend::unload_file(FileData *fd)
64
{
65
if (fd->data != nullptr) {
66
free(const_cast<uint8_t *>(fd->data));
67
fd->data = nullptr;
68
}
69
}
70
71
// return true if file operations are allowed
72
bool AP_Filesystem_Backend::file_op_allowed(void) const
73
{
74
if (!hal.util->get_soft_armed() || !hal.scheduler->in_main_thread()) {
75
return true;
76
}
77
return false;
78
}
79
80
/*
81
destructor for FileData
82
*/
83
FileData::~FileData()
84
{
85
if (backend != nullptr) {
86
((AP_Filesystem_Backend *)backend)->unload_file(this);
87
}
88
}
89
90
91