Skip to content

char_backend_file closes file handle in writefn, causing errors on subsequent writes #35

@donghyun-kang-dn

Description

@donghyun-kang-dn

Hi,

First of all, thanks for sharing this great project.

I am attempting to use char_backend_file as a UART module backend to log VP results efficiently. However, I encountered an issue where the logging fails after the first transaction.

Observation
It appears that char_backend_file::writefn closes the file handle (w_file) immediately after processing a transaction. This causes subsequent write attempts to fail because the file stream is no longer open.

Relevant Code
https://github.com/quic/qbox/blob/6531ba37fcec3ac1718c5a8bbe8455906db37675/systemc-components/backends/char_backend_file/include/char_backend_file.h#L115

// Current implementation
    void writefn(tlm::tlm_generic_payload& txn, sc_core::sc_time& t)
    {
        uint8_t* data = txn.get_data_ptr();
        for (int i = 0; i < txn.get_streaming_width(); i++) {
            size_t ret = fwrite(&data[i], sizeof(uint8_t), 1, w_file);
            if (ret != 1) {
                SCP_ERR(()) << "Error writing to the file.\n";
            }
        }
         fclose(w_file); // <--- This closes the file after every transaction
    }

Comparison
In contrast, the char_backend_stdio uses fflush(stdout) to handle the end of a transaction, keeping the stream open for continuous logging.

Proposed Fix
I believe the file should remain open during the simulation and only be closed upon destruction. I have tested the following modification, and it works as expected:

    void writefn(tlm::tlm_generic_payload& txn, sc_core::sc_time& t)
    {
        uint8_t* data = txn.get_data_ptr();
        for (int i = 0; i < txn.get_streaming_width(); i++) {
            size_t ret = fwrite(&data[i], sizeof(uint8_t), 1, w_file);
            if (ret != 1) {
                SCP_ERR(()) << "Error writing to the file.\n";
            }
        }
        fflush(w_file);  // Use fflush instead of fclose
    }

    // Add destructor to clean up file handles
    ~char_backend_file() 
    {
        if (w_file != nullptr) {
            fclose(w_file);
            w_file = nullptr;
        }
        if (r_file != nullptr) {
            fclose(r_file);
            r_file = nullptr;
        }
    }

Question
Is the current behavior (closing the file immediately) intended for a specific use case? If not, and this is indeed a bug, it would be great if this could be fixed in the upstream repo.

Thanks!

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions