Skip to content

Commit 27aa276

Browse files
committed
move EnsureNullTerminated to tools.h, capitalized and free memory after use
1 parent 2dbeb81 commit 27aa276

File tree

2 files changed

+14
-18
lines changed

2 files changed

+14
-18
lines changed

flang/runtime/command.cpp

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -282,28 +282,11 @@ std::int32_t RTNAME(GetEnvVariable)(const Descriptor &name,
282282
return StatOk;
283283
}
284284

285-
const char *ensureNullTerminated(
286-
const char *str, size_t length, Terminator &terminator) {
287-
if (length <= strlen(str)) {
288-
char *newCmd{(char *)malloc(length + 1)};
289-
if (newCmd == NULL) {
290-
terminator.Crash("Command not null-terminated, memory allocation failed "
291-
"for null-terminated newCmd.");
292-
}
293-
294-
strncpy(newCmd, str, length);
295-
newCmd[length] = '\0';
296-
return newCmd;
297-
} else {
298-
return str;
299-
}
300-
}
301-
302285
void RTNAME(System)(const Descriptor &command, const Descriptor *exitstat,
303286
const char *sourceFile, int line) {
304287
Terminator terminator{sourceFile, line};
305288

306-
const char *newCmd{ensureNullTerminated(
289+
const char *newCmd{EnsureNullTerminated(
307290
command.OffsetElement(), command.ElementBytes(), terminator)};
308291
int status{std::system(newCmd)};
309292

@@ -315,6 +298,7 @@ void RTNAME(System)(const Descriptor &command, const Descriptor *exitstat,
315298
int exitstatVal{WEXITSTATUS(status)};
316299
StoreLengthToDescriptor(exitstat, exitstatVal, terminator);
317300
#endif
301+
FreeMemory((void *)newCmd);
318302
}
319303
}
320304

flang/runtime/tools.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,5 +411,17 @@ RT_API_ATTRS void ShallowCopy(const Descriptor &to, const Descriptor &from,
411411
bool toIsContiguous, bool fromIsContiguous);
412412
RT_API_ATTRS void ShallowCopy(const Descriptor &to, const Descriptor &from);
413413

414+
inline RT_API_ATTRS const char *EnsureNullTerminated(
415+
const char *str, size_t length, Terminator &terminator) {
416+
if (length <= std::strlen(str)) {
417+
char *newCmd{(char *)AllocateMemoryOrCrash(terminator, length + 1)};
418+
std::memcpy(newCmd, str, length);
419+
newCmd[length] = '\0';
420+
return newCmd;
421+
} else {
422+
return str;
423+
}
424+
}
425+
414426
} // namespace Fortran::runtime
415427
#endif // FORTRAN_RUNTIME_TOOLS_H_

0 commit comments

Comments
 (0)