Debian Codegraph @

crt/aws-c-common/source/process_common.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/common/process.h>
7 #include <aws/common/string.h>
8
9 #include <stdio.h>
10 #include <sys/types.h>
11
12 enum { MAX_BUFFER_SIZE = 2048 };
13
14 int aws_run_command_result_init(struct aws_allocator *allocator, struct aws_run_command_result *result) {
15 if (!allocator || !result) {
16 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
17 }
18 AWS_ZERO_STRUCT(*result);
19 return AWS_OP_SUCCESS;
20 }
21
22 void aws_run_command_result_cleanup(struct aws_run_command_result *result) {
23 if (!result) {
24 return;
25 }
26 aws_string_destroy_secure(result->std_out);
27 aws_string_destroy_secure(result->std_err);
28 }
29
30 #if defined(AWS_OS_WINDOWS) && !defined(AWS_OS_WINDOWS_DESKTOP)
31 int aws_run_command(
32 struct aws_allocator *allocator,
33 struct aws_run_command_options *options,
34 struct aws_run_command_result *result) {
35 (void)allocator;
36 (void)options;
37 (void)result;
38 return aws_raise_error(AWS_ERROR_UNSUPPORTED_OPERATION);
39 }
40 #else
41
42 int aws_run_command(
43 struct aws_allocator *allocator,
44 struct aws_run_command_options *options,
45 struct aws_run_command_result *result) {
46
47 AWS_FATAL_ASSERT(allocator);
48 AWS_FATAL_ASSERT(options);
49 AWS_FATAL_ASSERT(result);
50
51 FILE *output_stream;
52 char output_buffer[MAX_BUFFER_SIZE];
53 struct aws_byte_buf result_buffer;
54 int ret = AWS_OP_ERR;
55 if (aws_byte_buf_init(&result_buffer, allocator, MAX_BUFFER_SIZE)) {
56 goto on_finish;
57 }
58
59 # if defined(AWS_OS_WINDOWS)
60 output_stream = _popen(options->command, "r");
61 # else
62 output_stream = popen(options->command, "r");
63 # endif
64
65 if (output_stream) {
66 while (!feof(output_stream)) {
67 if (fgets(output_buffer, MAX_BUFFER_SIZE, output_stream) != NULL) {
68 struct aws_byte_cursor cursor = aws_byte_cursor_from_c_str(output_buffer);
69 if (aws_byte_buf_append_dynamic(&result_buffer, &cursor)) {
70 goto on_finish;
71 }
72 }
73 }
74 # if defined(AWS_OS_WINDOWS)
75 result->ret_code = _pclose(output_stream);
76 # else
77 result->ret_code = pclose(output_stream);
78 # endif
79 }
80
81 struct aws_byte_cursor trim_cursor = aws_byte_cursor_from_buf(&result_buffer);
82 struct aws_byte_cursor trimmed_cursor = aws_byte_cursor_trim_pred(&trim_cursor, aws_char_is_space);
83 if (trimmed_cursor.len) {
84 result->std_out = aws_string_new_from_array(allocator, trimmed_cursor.ptr, trimmed_cursor.len);
85 if (!result->std_out) {
86 goto on_finish;
87 }
88 }
89 ret = AWS_OP_SUCCESS;
90
91 on_finish:
92 aws_byte_buf_clean_up_secure(&result_buffer);
93 return ret;
94 }
95 #endif /* !AWS_OS_WINDOWS */